Whamcloud - gitweb
LU-2655 obdclass: selinux support
[fs/lustre-release.git] / lustre / utils / mount_utils_ldiskfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/utils/mount_utils_ldiskfs.c
37  *
38  * Author: Nathan Rutman <nathan@clusterfs.com>
39 */
40
41 /* This source file is compiled into both mkfs.lustre and tunefs.lustre */
42
43 #if HAVE_CONFIG_H
44 #  include "config.h"
45 #endif /* HAVE_CONFIG_H */
46
47 #ifndef _GNU_SOURCE
48 #define _GNU_SOURCE
49 #endif
50 #include "mount_utils.h"
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <unistd.h>
54 #include <fcntl.h>
55 #include <stdarg.h>
56 #include <mntent.h>
57 #include <glob.h>
58
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 #include <sys/mount.h>
62 #include <sys/utsname.h>
63
64 #include <string.h>
65 #include <getopt.h>
66 #include <limits.h>
67 #include <ctype.h>
68
69 #ifdef __linux__
70 /* libcfs.h is not really needed here, but on SLES10/PPC, fs.h includes idr.h
71  * which requires BITS_PER_LONG to be defined */
72 #include <libcfs/libcfs.h>
73 #ifndef BLKGETSIZE64
74 #include <linux/fs.h> /* for BLKGETSIZE64 */
75 #endif
76 #include <linux/version.h>
77 #endif
78 #include <lustre_disk.h>
79 #include <lustre_param.h>
80 #include <lnet/lnetctl.h>
81 #include <lustre_ver.h>
82
83 #ifdef HAVE_SELINUX
84 #include <selinux/selinux.h>
85 #endif
86
87 #define MAX_HW_SECTORS_KB_PATH  "queue/max_hw_sectors_kb"
88 #define MAX_SECTORS_KB_PATH     "queue/max_sectors_kb"
89 #define SCHEDULER_PATH          "queue/scheduler"
90 #define STRIPE_CACHE_SIZE       "md/stripe_cache_size"
91
92 #define DEFAULT_SCHEDULER       "deadline"
93
94 extern char *progname;
95
96 #define L_BLOCK_SIZE 4096
97 /* keep it less than LL_FID_NAMELEN */
98 #define DUMMY_FILE_NAME_LEN             25
99 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
100
101 /*
102  * Concatenate context of the temporary mount point iff selinux is enabled
103  */
104 #ifdef HAVE_SELINUX
105 void append_context_for_mount(char *mntpt, struct mkfs_opts *mop)
106 {
107         security_context_t fcontext;
108
109         if (getfilecon(mntpt, &fcontext) < 0) {
110                 /* Continuing with default behaviour */
111                 fprintf(stderr, "%s: Get file context failed : %s\n",
112                         progname, strerror(errno));
113                 return;
114         }
115
116         if (fcontext != NULL) {
117                 strcat(mop->mo_ldd.ldd_mount_opts, ",context=");
118                 strcat(mop->mo_ldd.ldd_mount_opts, fcontext);
119                 freecon(fcontext);
120         }
121 }
122 #endif
123
124 /* Write the server config files */
125 int ldiskfs_write_ldd(struct mkfs_opts *mop)
126 {
127         char mntpt[] = "/tmp/mntXXXXXX";
128         char filepnm[128];
129         char *dev;
130         FILE *filep;
131         int ret = 0;
132         size_t num;
133
134         /* Mount this device temporarily in order to write these files */
135         if (!mkdtemp(mntpt)) {
136                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
137                         progname, mntpt, strerror(errno));
138                 return errno;
139         }
140
141         /*
142          * Append file context to mount options if SE Linux is enabled
143          */
144         #ifdef HAVE_SELINUX
145         if (is_selinux_enabled() > 0)
146                 append_context_for_mount(mntpt, mop);
147         #endif
148
149         dev = mop->mo_device;
150         if (mop->mo_flags & MO_IS_LOOP)
151                 dev = mop->mo_loopdev;
152
153         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
154                     mop->mo_ldd.ldd_mount_opts);
155         if (ret) {
156                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
157                         progname, dev, strerror(errno));
158                 ret = errno;
159                 if (errno == ENODEV) {
160                         fprintf(stderr, "Is the %s module available?\n",
161                                 MT_STR(&mop->mo_ldd));
162                 }
163                 goto out_rmdir;
164         }
165
166         /* Set up initial directories */
167         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
168         ret = mkdir(filepnm, 0777);
169         if ((ret != 0) && (errno != EEXIST)) {
170                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
171                         progname, filepnm, strerror(errno));
172                 goto out_umnt;
173         } else if (errno == EEXIST) {
174                 ret = 0;
175         }
176
177         /* Save the persistent mount data into a file. Lustre must pre-read
178            this file to get the real mount options. */
179         vprint("Writing %s\n", MOUNT_DATA_FILE);
180         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
181         filep = fopen(filepnm, "w");
182         if (!filep) {
183                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
184                         progname, filepnm, strerror(errno));
185                 goto out_umnt;
186         }
187         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
188         if (num < 1 && ferror(filep)) {
189                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
190                         progname, filepnm, strerror(errno));
191                 fclose(filep);
192                 goto out_umnt;
193         }
194         fclose(filep);
195
196 out_umnt:
197         umount(mntpt);
198 out_rmdir:
199         rmdir(mntpt);
200         return ret;
201 }
202
203 static int readcmd(char *cmd, char *buf, int len)
204 {
205         FILE *fp;
206         int red;
207
208         fp = popen(cmd, "r");
209         if (!fp)
210                 return errno;
211
212         red = fread(buf, 1, len, fp);
213         pclose(fp);
214
215         /* strip trailing newline */
216         if (buf[red - 1] == '\n')
217                 buf[red - 1] = '\0';
218
219         return (red == 0) ? -ENOENT : 0;
220 }
221
222 int ldiskfs_read_ldd(char *dev, struct lustre_disk_data *mo_ldd)
223 {
224         char tmpdir[] = "/tmp/dirXXXXXX";
225         char cmd[PATH_MAX];
226         char filepnm[128];
227         FILE *filep;
228         int ret = 0;
229         int cmdsz = sizeof(cmd);
230
231         /* Make a temporary directory to hold Lustre data files. */
232         if (!mkdtemp(tmpdir)) {
233                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
234                         progname, tmpdir, strerror(errno));
235                 return errno;
236         }
237
238         /* TODO: it's worth observing the get_mountdata() function that is
239            in mount_utils.c for getting the mountdata out of the
240            filesystem */
241
242         /* Construct debugfs command line. */
243         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
244                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
245
246         ret = run_command(cmd, cmdsz);
247         if (ret)
248                 verrprint("%s: Unable to dump %s dir (%d)\n",
249                           progname, MOUNT_CONFIGS_DIR, ret);
250
251         sprintf(filepnm, "%s/mountdata", tmpdir);
252         filep = fopen(filepnm, "r");
253         if (filep) {
254                 size_t num_read;
255                 vprint("Reading %s\n", MOUNT_DATA_FILE);
256                 num_read = fread(mo_ldd, sizeof(*mo_ldd), 1, filep);
257                 if (num_read < 1 && ferror(filep)) {
258                         fprintf(stderr, "%s: Unable to read from file %s: %s\n",
259                                 progname, filepnm, strerror(errno));
260                 }
261                 fclose(filep);
262         }
263
264         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
265         run_command(cmd, cmdsz);
266         if (ret)
267                 verrprint("Failed to read old data (%d)\n", ret);
268
269         /* As long as we at least have the label, we're good to go */
270         snprintf(cmd, sizeof(cmd), E2LABEL" %s", dev);
271         ret = readcmd(cmd, mo_ldd->ldd_svname, sizeof(mo_ldd->ldd_svname) - 1);
272
273         return ret;
274 }
275
276
277 /* Display the need for the latest e2fsprogs to be installed. make_backfs
278  * indicates if the caller is make_lustre_backfs() or not. */
279 void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
280 {
281         static int msg_displayed;
282
283         if (msg_displayed) {
284                 fprintf(stderr, "WARNING: %s does not support %s "
285                         "feature.\n\n", E2FSPROGS, feature);
286                 return;
287         }
288
289         msg_displayed++;
290
291         fprintf(stderr, "WARNING: The %s package currently installed on "
292                 "your system does not support \"%s\" feature.\n",
293                 E2FSPROGS, feature);
294 #if !(HAVE_LDISKFSPROGS)
295         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
296                 "http://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
297                 "to enable this feature.\n");
298 #endif
299         if (make_backfs)
300                 fprintf(stderr, "Feature will not be enabled until %s"
301                         "is updated and '%s -O %s %%{device}' "
302                         "is run.\n\n", E2FSPROGS, TUNE2FS, feature);
303 }
304
305 /* Check whether the file exists in the device */
306 static int file_in_dev(char *file_name, char *dev_name)
307 {
308         FILE *fp;
309         char debugfs_cmd[256];
310         unsigned int inode_num;
311         int i;
312
313         /* Construct debugfs command line. */
314         snprintf(debugfs_cmd, sizeof(debugfs_cmd),
315                  "%s -c -R 'stat %s' '%s' 2>&1 | egrep '(Inode|unsupported)'",
316                  DEBUGFS, file_name, dev_name);
317
318         fp = popen(debugfs_cmd, "r");
319         if (!fp) {
320                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
321                 return 0;
322         }
323
324         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
325                 pclose(fp);
326                 return 1;
327         }
328         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd) - 1, fp);
329         if (i) {
330                 debugfs_cmd[i] = 0;
331                 fprintf(stderr, "%s", debugfs_cmd);
332                 if (strstr(debugfs_cmd, "unsupported feature")) {
333                         disp_old_e2fsprogs_msg("an unknown", 0);
334                 }
335                 pclose(fp);
336                 return -1;
337         }
338         pclose(fp);
339         return 0;
340 }
341
342 /* Check whether the device has already been used with lustre */
343 int ldiskfs_is_lustre(char *dev, unsigned *mount_type)
344 {
345         int ret;
346
347         ret = file_in_dev(MOUNT_DATA_FILE, dev);
348         if (ret) {
349                 /* in the -1 case, 'extents' means IS a lustre target */
350                 *mount_type = LDD_MT_LDISKFS;
351                 return 1;
352         }
353
354         ret = file_in_dev(LAST_RCVD, dev);
355         if (ret) {
356                 *mount_type = LDD_MT_LDISKFS;
357                 return 1;
358         }
359
360         return 0;
361 }
362
363 /* Check if a certain feature is supported by e2fsprogs.
364  * Firstly we try to use "debugfs supported_features" command to check if
365  * the feature is supported. If this fails we try to set this feature with
366  * mke2fs to check for its support. */
367 static int is_e2fsprogs_feature_supp(const char *feature)
368 {
369         static char supp_features[4096] = "";
370         FILE *fp;
371         char cmd[PATH_MAX];
372         char imgname[] = "/tmp/test-img-XXXXXX";
373         int fd = -1;
374         int ret = 1;
375
376         if (supp_features[0] == '\0') {
377                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
378                          DEBUGFS);
379
380                 /* Using popen() instead of run_command() since debugfs does
381                  * not return proper error code if command is not supported */
382                 fp = popen(cmd, "r");
383                 if (!fp) {
384                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
385                         return 0;
386                 }
387                 ret = fread(supp_features, 1, sizeof(supp_features) - 1, fp);
388                 supp_features[ret] = '\0';
389                 fclose(fp);
390         }
391         if (ret > 0 && strstr(supp_features,
392                               strncmp(feature, "-O ", 3) ? feature : feature+3))
393                 return 0;
394
395         if ((fd = mkstemp(imgname)) < 0)
396                 return -1;
397         else
398                 close(fd);
399
400         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
401                  MKE2FS, feature, imgname);
402         /* run_command() displays the output of mke2fs when it fails for
403          * some feature, so use system() directly */
404         ret = system(cmd);
405         unlink(imgname);
406
407         return ret;
408 }
409
410
411 /**
412  * append_unique: append @key or @key=@val pair to @buf only if @key does not
413  *                exists
414  *      @buf: buffer to hold @key or @key=@val
415  *      @prefix: prefix string before @key
416  *      @key: key string
417  *      @val: value string if it's a @key=@val pair
418  */
419 static void append_unique(char *buf, char *prefix, char *key, char *val,
420                           size_t maxbuflen)
421 {
422         char *anchor, *end;
423         int  len;
424
425         if (key == NULL)
426                 return;
427
428         anchor = end = strstr(buf, key);
429         /* try to find exact match string in @buf */
430         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
431                 ++end;
432         len = end - anchor;
433         if (anchor == NULL || strlen(key) != len ||
434                         strncmp(anchor, key, len) != 0) {
435                 if (prefix != NULL)
436                         strscat(buf, prefix, maxbuflen);
437
438                 strscat(buf, key, maxbuflen);
439                 if (val != NULL) {
440                         strscat(buf, "=", maxbuflen);
441                         strscat(buf, val, maxbuflen);
442                 }
443         }
444 }
445
446 static int enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
447                                         size_t maxbuflen, int user_spec)
448 {
449         if (IS_OST(&mop->mo_ldd)) {
450                 append_unique(anchor, user_spec ? "," : " -O ",
451                               "extents", NULL, sizeof(mop->mo_mkfsopts));
452                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
453         } else if (IS_MDT(&mop->mo_ldd)) {
454                 append_unique(anchor, user_spec ? "," : " -O ",
455                               "dirdata", NULL, maxbuflen);
456                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
457                 append_unique(anchor, ",", "^extents", NULL, maxbuflen);
458         } else {
459                 append_unique(anchor, user_spec ? "," : " -O ",
460                               "uninit_bg", NULL, maxbuflen);
461         }
462
463         /* Multiple mount protection enabled only if failover node specified */
464         if (mop->mo_flags & MO_FAILOVER) {
465                 if (is_e2fsprogs_feature_supp("-O mmp") == 0)
466                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
467                 else
468                         disp_old_e2fsprogs_msg("mmp", 1);
469         }
470
471         /* Allow more than 65000 subdirectories */
472         if (is_e2fsprogs_feature_supp("-O dir_nlink") == 0)
473                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
474
475         /* The following options are only valid for ext4-based ldiskfs.
476          * If --backfstype=ext3 is specified, do not enable them. */
477         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
478                 return 0;
479
480         /* Enable quota by default */
481         if (is_e2fsprogs_feature_supp("-O quota") == 0) {
482                 append_unique(anchor, ",", "quota", NULL, maxbuflen);
483         } else {
484                 fatal();
485                 fprintf(stderr, "\"-O quota\" must be supported by "
486                         "e2fsprogs, please upgrade your e2fsprogs.\n");
487                 return EINVAL;
488         }
489
490         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
491         if (is_e2fsprogs_feature_supp("-O huge_file") == 0)
492                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
493
494         /* Enable large block addresses if the LUN is over 2^32 blocks. */
495         if (mop->mo_device_sz / (L_BLOCK_SIZE >> 10) >= 0x100002000ULL &&
496             is_e2fsprogs_feature_supp("-O 64bit") == 0)
497                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
498
499         /* Cluster inode/block bitmaps and inode table for more efficient IO.
500          * Align the flex groups on a 1MB boundary for better performance. */
501         /* This -O feature needs to go last, since it adds the "-G" option. */
502         if (is_e2fsprogs_feature_supp("-O flex_bg") == 0) {
503                 char tmp_buf[64];
504
505                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
506
507                 if (IS_OST(&mop->mo_ldd)) {
508                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
509                                  (1 << 20) / L_BLOCK_SIZE);
510                         strscat(anchor, tmp_buf, maxbuflen);
511                 }
512         }
513         /* Don't add any more "-O" options here, see last comment above */
514         return 0;
515 }
516
517 /**
518  * moveopts_to_end: find the option string, move remaining strings to
519  *                  where option string starts, and append the option
520  *                  string at the end
521  *      @start: where the option string starts before the move
522  *      RETURN: where the option string starts after the move
523  */
524 static char *moveopts_to_end(char *start)
525 {
526         char save[512];
527         char *end, *idx;
528
529         /* skip whitespace before options */
530         end = start + 2;
531         while (*end == ' ')
532                 ++end;
533
534         /* find end of option characters */
535         while (*end != ' ' && *end != '\0')
536                 ++end;
537
538         /* save options */
539         strncpy(save, start, end - start);
540         save[end - start] = '\0';
541
542         /* move remaining options up front */
543         if (*end)
544                 memmove(start, end, strlen(end));
545         *(start + strlen(end)) = '\0';
546
547         /* append the specified options */
548         if (*(start + strlen(start) - 1) != ' ')
549                 strcat(start, " ");
550         idx = start + strlen(start);
551         strcat(start, save);
552
553         return idx;
554 }
555
556 /* Build fs according to type */
557 int ldiskfs_make_lustre(struct mkfs_opts *mop)
558 {
559         __u64 device_sz = mop->mo_device_sz, block_count = 0;
560         char mkfs_cmd[PATH_MAX];
561         char buf[64];
562         char *start;
563         char *dev;
564         int ret = 0, ext_opts = 0;
565         size_t maxbuflen;
566
567         if (!(mop->mo_flags & MO_IS_LOOP)) {
568                 mop->mo_device_sz = get_device_size(mop->mo_device);
569
570                 if (mop->mo_device_sz == 0)
571                         return ENODEV;
572
573                 /* Compare to real size */
574                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
575                         device_sz = mop->mo_device_sz;
576                 else
577                         mop->mo_device_sz = device_sz;
578         }
579
580         if (mop->mo_device_sz != 0) {
581                 if (mop->mo_device_sz < 8096){
582                         fprintf(stderr, "%s: size of filesystem must be larger "
583                                 "than 8MB, but is set to %lldKB\n",
584                                 progname, (long long)mop->mo_device_sz);
585                         return EINVAL;
586                 }
587                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
588                 /* If the LUN size is just over 2^32 blocks, limit the
589                  * filesystem size to 2^32-1 blocks to avoid problems with
590                  * ldiskfs/mkfs not handling this size.  Bug 22906 */
591                 if (block_count > 0xffffffffULL && block_count < 0x100002000ULL)
592                         block_count = 0xffffffffULL;
593         }
594
595         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
596             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
597             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
598                 long inode_size = 0;
599
600                 /* Journal size in MB */
601                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
602                         /* Choose our own default journal size */
603                         long journal_sz = 0, max_sz;
604                         if (device_sz > 1024 * 1024) /* 1GB */
605                                 journal_sz = (device_sz / 102400) * 4;
606                         /* cap journal size at 1GB */
607                         if (journal_sz > 1024L)
608                                 journal_sz = 1024L;
609                         /* man mkfs.ext3 */
610                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
611                         if (journal_sz > max_sz)
612                                 journal_sz = max_sz;
613                         if (journal_sz) {
614                                 sprintf(buf, " -J size=%ld", journal_sz);
615                                 strscat(mop->mo_mkfsopts, buf,
616                                         sizeof(mop->mo_mkfsopts));
617                         }
618                 }
619
620                 /* Inode size (for extended attributes).  The LOV EA size is
621                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
622                  * and we want some margin above that for ACLs, other EAs... */
623                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
624                         if (IS_MDT(&mop->mo_ldd)) {
625                                 if (mop->mo_stripe_count > 72)
626                                         inode_size = 512; /* bz 7241 */
627                                 /* see also "-i" below for EA blocks */
628                                 else if (mop->mo_stripe_count > 32)
629                                         inode_size = 2048;
630                                 else if (mop->mo_stripe_count > 10)
631                                         inode_size = 1024;
632                                 else
633                                         inode_size = 512;
634                         } else if (IS_OST(&mop->mo_ldd)) {
635                                 /* We store MDS FID and OST objid in EA on OST
636                                  * we need to make inode bigger as well. */
637                                 inode_size = 256;
638                         }
639
640                         if (inode_size > 0) {
641                                 sprintf(buf, " -I %ld", inode_size);
642                                 strscat(mop->mo_mkfsopts, buf,
643                                         sizeof(mop->mo_mkfsopts));
644                         }
645                 }
646
647                 /* Bytes_per_inode: disk size / num inodes */
648                 if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
649                     strstr(mop->mo_mkfsopts, "-N") == NULL) {
650                         long bytes_per_inode = 0;
651
652                         /* Allocate more inodes on MDT devices.  There is
653                          * no data stored on the MDT, and very little extra
654                          * metadata beyond the inode.  It could go down as
655                          * low as 1024 bytes, but this is conservative.
656                          * Account for external EA blocks for wide striping. */
657                         if (IS_MDT(&mop->mo_ldd)) {
658                                 bytes_per_inode = inode_size + 1536;
659
660                                 if (mop->mo_stripe_count > 72) {
661                                         int extra = mop->mo_stripe_count * 24;
662                                         extra = ((extra - 1) | 4095) + 1;
663                                         bytes_per_inode += extra;
664                                 }
665                         }
666
667                         /* Allocate fewer inodes on large OST devices.  Most
668                          * filesystems can be much more aggressive than even
669                          * this, but it is impossible to know in advance. */
670                         if (IS_OST(&mop->mo_ldd)) {
671                                 /* OST > 16TB assume average file size 1MB */
672                                 if (device_sz > (16ULL << 30))
673                                         bytes_per_inode = 1024 * 1024;
674                                 /* OST > 4TB assume average file size 512kB */
675                                 else if (device_sz > (4ULL << 30))
676                                         bytes_per_inode = 512 * 1024;
677                                 /* OST > 1TB assume average file size 256kB */
678                                 else if (device_sz > (1ULL << 30))
679                                         bytes_per_inode = 256 * 1024;
680                                 /* OST > 10GB assume average file size 64kB,
681                                  * plus a bit so that inodes will fit into a
682                                  * 256x flex_bg without overflowing */
683                                 else if (device_sz > (10ULL << 20))
684                                         bytes_per_inode = 69905;
685                         }
686
687                         if (bytes_per_inode > 0) {
688                                 sprintf(buf, " -i %ld", bytes_per_inode);
689                                 strscat(mop->mo_mkfsopts, buf,
690                                         sizeof(mop->mo_mkfsopts));
691                         }
692                 }
693
694                 if (verbose < 2) {
695                         strscat(mop->mo_mkfsopts, " -q",
696                                 sizeof(mop->mo_mkfsopts));
697                 }
698
699                 /* start handle -O mkfs options */
700                 if ((start = strstr(mop->mo_mkfsopts, "-O")) != NULL) {
701                         if (strstr(start + 2, "-O") != NULL) {
702                                 fprintf(stderr,
703                                         "%s: don't specify multiple -O options\n",
704                                         progname);
705                                 return EINVAL;
706                         }
707                         start = moveopts_to_end(start);
708                         maxbuflen = sizeof(mop->mo_mkfsopts) -
709                                 (start - mop->mo_mkfsopts) - strlen(start);
710                         ret = enable_default_ext4_features(mop, start, maxbuflen, 1);
711                 } else {
712                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts),
713                               maxbuflen = sizeof(mop->mo_mkfsopts) -
714                                       strlen(mop->mo_mkfsopts);
715                         ret = enable_default_ext4_features(mop, start, maxbuflen, 0);
716                 }
717                 if (ret)
718                         return ret;
719                 /* end handle -O mkfs options */
720
721                 /* start handle -E mkfs options */
722                 if ((start = strstr(mop->mo_mkfsopts, "-E")) != NULL) {
723                         if (strstr(start + 2, "-E") != NULL) {
724                                 fprintf(stderr,
725                                         "%s: don't specify multiple -E options\n",
726                                         progname);
727                                 return EINVAL;
728                         }
729                         start = moveopts_to_end(start);
730                         maxbuflen = sizeof(mop->mo_mkfsopts) -
731                                 (start - mop->mo_mkfsopts) - strlen(start);
732                         ext_opts = 1;
733                 } else {
734                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
735                         maxbuflen = sizeof(mop->mo_mkfsopts) -
736                                 strlen(mop->mo_mkfsopts);
737                 }
738
739                 /* In order to align the filesystem metadata on 1MB boundaries,
740                  * give a resize value that will reserve a power-of-two group
741                  * descriptor blocks, but leave one block for the superblock.
742                  * Only useful for filesystems with < 2^32 blocks due to resize
743                  * limitations. */
744                 if (IS_OST(&mop->mo_ldd) && mop->mo_device_sz > 100 * 1024 &&
745                     mop->mo_device_sz * 1024 / L_BLOCK_SIZE <= 0xffffffffULL) {
746                         unsigned group_blocks = L_BLOCK_SIZE * 8;
747                         unsigned desc_per_block = L_BLOCK_SIZE / 32;
748                         unsigned resize_blks;
749
750                         resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
751                         snprintf(buf, sizeof(buf), "%u", resize_blks);
752                         append_unique(start, ext_opts ? "," : " -E ",
753                                       "resize", buf, maxbuflen);
754                         ext_opts = 1;
755                 }
756
757                 /* Avoid zeroing out the full journal - speeds up mkfs */
758                 if (is_e2fsprogs_feature_supp("-E lazy_journal_init") == 0)
759                         append_unique(start, ext_opts ? "," : " -E ",
760                                       "lazy_journal_init", NULL, maxbuflen);
761                 /* end handle -E mkfs options */
762
763                 /* Allow reformat of full devices (as opposed to
764                    partitions.)  We already checked for mounted dev. */
765                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
766
767                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
768                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
769                          mop->mo_ldd.ldd_svname);
770         } else {
771                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
772                         progname, mop->mo_ldd.ldd_mount_type,
773                         MT_STR(&mop->mo_ldd));
774                 return EINVAL;
775         }
776
777         /* For loop device format the dev, not the filename */
778         dev = mop->mo_device;
779         if (mop->mo_flags & MO_IS_LOOP)
780                 dev = mop->mo_loopdev;
781
782         vprint("formatting backing filesystem %s on %s\n",
783                MT_STR(&mop->mo_ldd), dev);
784         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
785         vprint("\t4k blocks     "LPU64"\n", block_count);
786         vprint("\toptions       %s\n", mop->mo_mkfsopts);
787
788         /* mkfs_cmd's trailing space is important! */
789         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
790         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
791         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
792         if (block_count != 0) {
793                 sprintf(buf, " "LPU64, block_count);
794                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
795         }
796
797         vprint("mkfs_cmd = %s\n", mkfs_cmd);
798         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
799         if (ret) {
800                 fatal();
801                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
802         }
803         return ret;
804 }
805
806 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
807                            char *default_mountopts, int default_len,
808                            char *always_mountopts, int always_len)
809 {
810         struct lustre_disk_data *ldd = &mop->mo_ldd;
811         int ret;
812
813         /* Set MO_IS_LOOP to indicate a loopback device is needed */
814         ret = is_block(mop->mo_device);
815         if (ret < 0) {
816                 return errno;
817         } else if (ret == 0) {
818                 mop->mo_flags |= MO_IS_LOOP;
819         }
820
821         strscat(default_mountopts, ",errors=remount-ro", default_len);
822         if (IS_MDT(ldd) || IS_MGS(ldd))
823                 strscat(always_mountopts, ",user_xattr", always_len);
824
825         return 0;
826 }
827
828 int read_file(const char *path, char *buf, int size)
829 {
830         FILE *fd;
831
832         fd = fopen(path, "r");
833         if (fd == NULL)
834                 return errno;
835
836         /* should not ignore fgets(3)'s return value */
837         if (!fgets(buf, size, fd)) {
838                 fprintf(stderr, "reading from %s: %s", path, strerror(errno));
839                 fclose(fd);
840                 return 1;
841         }
842         fclose(fd);
843         return 0;
844 }
845
846 int write_file(const char *path, const char *buf)
847 {
848         FILE *fd;
849
850         fd = fopen(path, "w");
851         if (fd == NULL)
852                 return errno;
853
854         fputs(buf, fd);
855         fclose(fd);
856         return 0;
857 }
858
859 int set_blockdev_scheduler(const char *path, const char *scheduler)
860 {
861         char buf[PATH_MAX], *c;
862         int rc;
863
864         /* Before setting the scheduler, we need to check to see if it's
865          * already set to "noop". If it is, we don't want to override
866          * that setting. If it's set to anything other than "noop", set
867          * the scheduler to what has been passed in. */
868
869         rc = read_file(path, buf, sizeof(buf));
870         if (rc) {
871                 if (verbose)
872                         fprintf(stderr, "%s: cannot open '%s': %s\n",
873                                 progname, path, strerror(errno));
874                 return rc;
875         }
876
877         /* The expected format of buf: noop anticipatory deadline [cfq] */
878         c = strchr(buf, '[');
879
880         /* If c is NULL, the format is not what we expect. Play it safe
881          * and error out. */
882         if (c == NULL) {
883                 if (verbose)
884                         fprintf(stderr, "%s: cannot parse scheduler "
885                                         "options for '%s'\n", progname, path);
886                 return -EINVAL;
887         }
888
889         if (strncmp(c+1, "noop", 4) == 0)
890                 return 0;
891
892         rc = write_file(path, scheduler);
893         if (rc) {
894                 if (verbose)
895                         fprintf(stderr, "%s: cannot set scheduler on "
896                                         "'%s': %s\n", progname, path,
897                                         strerror(errno));
898                 return rc;
899         }
900
901         return rc;
902 }
903
904 /* This is to tune the kernel for good SCSI performance.
905  * For that we set the value of /sys/block/{dev}/queue/max_sectors_kb
906  * to the value of /sys/block/{dev}/queue/max_hw_sectors_kb */
907 int set_blockdev_tunables(char *source, struct mount_opts *mop, int fan_out)
908 {
909         glob_t glob_info = { 0 };
910         struct stat stat_buf;
911         char *chk_major, *chk_minor;
912         char *savept = NULL, *dev;
913         char *ret_path;
914         char buf[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
915         char real_path[PATH_MAX] = {'\0'};
916         int i, rc = 0;
917         int major, minor;
918
919         if (!source)
920                 return -EINVAL;
921
922         ret_path = realpath(source, real_path);
923         if (ret_path == NULL) {
924                 if (verbose)
925                         fprintf(stderr, "warning: %s: cannot resolve: %s\n",
926                                 source, strerror(errno));
927                 return -EINVAL;
928         }
929
930         if (strncmp(real_path, "/dev/loop", 9) == 0)
931                 return 0;
932
933         if ((real_path[0] != '/') && (strpbrk(real_path, ",:") != NULL))
934                 return 0;
935
936         snprintf(path, sizeof(path), "/sys/block%s", real_path + 4);
937         if (access(path, X_OK) == 0)
938                 goto set_params;
939
940         /* The name of the device say 'X' specified in /dev/X may not
941          * match any entry under /sys/block/. In that case we need to
942          * match the major/minor number to find the entry under
943          * sys/block corresponding to /dev/X */
944
945         /* Don't chop tail digit on /dev/mapper/xxx, LU-478 */
946         if (strncmp(real_path, "/dev/mapper", 11) != 0) {
947                 dev = real_path + strlen(real_path);
948                 while (--dev > real_path && isdigit(*dev))
949                         *dev = 0;
950
951                 if (strncmp(real_path, "/dev/md_", 8) == 0)
952                         *dev = 0;
953         }
954
955         rc = stat(real_path, &stat_buf);
956         if (rc) {
957                 if (verbose)
958                         fprintf(stderr, "warning: %s, device %s stat failed\n",
959                                 strerror(errno), real_path);
960                 return rc;
961         }
962
963         major = major(stat_buf.st_rdev);
964         minor = minor(stat_buf.st_rdev);
965         rc = glob("/sys/block/*", GLOB_NOSORT, NULL, &glob_info);
966         if (rc) {
967                 if (verbose)
968                         fprintf(stderr, "warning: failed to read entries under "
969                                 "/sys/block\n");
970                 globfree(&glob_info);
971                 return rc;
972         }
973
974         for (i = 0; i < glob_info.gl_pathc; i++){
975                 snprintf(path, sizeof(path), "%s/dev", glob_info.gl_pathv[i]);
976
977                 rc = read_file(path, buf, sizeof(buf));
978                 if (rc)
979                         continue;
980
981                 if (buf[strlen(buf) - 1] == '\n')
982                         buf[strlen(buf) - 1] = '\0';
983
984                 chk_major = strtok_r(buf, ":", &savept);
985                 chk_minor = savept;
986                 if (major == atoi(chk_major) &&minor == atoi(chk_minor))
987                         break;
988         }
989
990         if (i == glob_info.gl_pathc) {
991                 if (verbose)
992                         fprintf(stderr,"warning: device %s does not match any "
993                                 "entry under /sys/block\n", real_path);
994                 globfree(&glob_info);
995                 return -EINVAL;
996         }
997
998         /* Chop off "/dev" from path we found */
999         path[strlen(glob_info.gl_pathv[i])] = '\0';
1000         globfree(&glob_info);
1001
1002 set_params:
1003         if (strncmp(real_path, "/dev/md", 7) == 0) {
1004                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
1005                          STRIPE_CACHE_SIZE);
1006
1007                 rc = read_file(real_path, buf, sizeof(buf));
1008                 if (rc) {
1009                         if (verbose)
1010                                 fprintf(stderr, "warning: opening %s: %s\n",
1011                                         real_path, strerror(errno));
1012                         return 0;
1013                 }
1014
1015                 if (atoi(buf) >= mop->mo_md_stripe_cache_size)
1016                         return 0;
1017
1018                 if (strlen(buf) - 1 > 0) {
1019                         snprintf(buf, sizeof(buf), "%d",
1020                                  mop->mo_md_stripe_cache_size);
1021                         rc = write_file(real_path, buf);
1022                         if (rc && verbose)
1023                                 fprintf(stderr, "warning: opening %s: %s\n",
1024                                         real_path, strerror(errno));
1025                 }
1026                 /* Return since raid and disk tunables are different */
1027                 return rc;
1028         }
1029
1030         snprintf(real_path, sizeof(real_path), "%s/%s", path,
1031                  MAX_HW_SECTORS_KB_PATH);
1032         rc = read_file(real_path, buf, sizeof(buf));
1033         if (rc) {
1034                 if (verbose)
1035                         fprintf(stderr, "warning: opening %s: %s\n",
1036                                 real_path, strerror(errno));
1037                 /* No MAX_HW_SECTORS_KB_PATH isn't necessary an
1038                  * error for some device. */
1039                 rc = 0;
1040         }
1041
1042         if (strlen(buf) - 1 > 0) {
1043                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
1044                          MAX_SECTORS_KB_PATH);
1045                 rc = write_file(real_path, buf);
1046                 if (rc) {
1047                         if (verbose)
1048                                 fprintf(stderr, "warning: writing to %s: %s\n",
1049                                         real_path, strerror(errno));
1050                         /* No MAX_SECTORS_KB_PATH isn't necessary an
1051                          * error for some device. */
1052                         rc = 0;
1053                 }
1054         }
1055
1056         /* Purposely ignore errors reported from set_blockdev_scheduler.
1057          * The worst that will happen is a block device with an "incorrect"
1058          * scheduler. */
1059         snprintf(real_path, sizeof(real_path), "%s/%s", path, SCHEDULER_PATH);
1060         set_blockdev_scheduler(real_path, DEFAULT_SCHEDULER);
1061
1062         if (fan_out) {
1063                 char *slave = NULL;
1064                 glob_info.gl_pathc = 0;
1065                 glob_info.gl_offs = 0;
1066                 /* if device is multipath device, tune its slave devices */
1067                 snprintf(real_path, sizeof(real_path), "%s/slaves/*", path);
1068                 rc = glob(real_path, GLOB_NOSORT, NULL, &glob_info);
1069
1070                 for (i = 0; rc == 0 && i < glob_info.gl_pathc; i++){
1071                         slave = basename(glob_info.gl_pathv[i]);
1072                         snprintf(real_path, sizeof(real_path), "/dev/%s", slave);
1073                         rc = set_blockdev_tunables(real_path, mop, 0);
1074                 }
1075
1076                 if (rc == GLOB_NOMATCH) {
1077                         /* no slave device is not an error */
1078                         rc = 0;
1079                 } else if (rc && verbose) {
1080                         if (slave == NULL) {
1081                                 fprintf(stderr, "warning: %s, failed to read"
1082                                         " entries under %s/slaves\n",
1083                                         strerror(errno), path);
1084                         } else {
1085                                 fprintf(stderr, "unable to set tunables for"
1086                                         " slave device %s (slave would be"
1087                                         " unable to handle IO request from"
1088                                         " master %s)\n",
1089                                         real_path, source);
1090                         }
1091                 }
1092                 globfree(&glob_info);
1093         }
1094
1095         return rc;
1096 }
1097
1098 int ldiskfs_tune_lustre(char *dev, struct mount_opts *mop)
1099 {
1100         return set_blockdev_tunables(dev, mop, 1);
1101 }
1102
1103 int ldiskfs_label_lustre(struct mount_opts *mop)
1104 {
1105         char label_cmd[PATH_MAX];
1106         int rc;
1107
1108         snprintf(label_cmd, sizeof(label_cmd),
1109                  TUNE2FS" -f -L '%s' '%s' >/dev/null 2>&1",
1110                  mop->mo_ldd.ldd_svname, mop->mo_source);
1111         rc = run_command(label_cmd, sizeof(label_cmd));
1112
1113         return rc;
1114 }
1115
1116 /* return canonicalized absolute pathname, even if the target file does not
1117  * exist, unlike realpath */
1118 static char *absolute_path(char *devname)
1119 {
1120         char  buf[PATH_MAX + 1];
1121         char *path;
1122         char *ptr;
1123
1124         path = malloc(PATH_MAX + 1);
1125         if (path == NULL)
1126                 return NULL;
1127
1128         if (devname[0] != '/') {
1129                 if (getcwd(buf, sizeof(buf) - 1) == NULL) {
1130                         free(path);
1131                         return NULL;
1132                 }
1133                 strcat(buf, "/");
1134                 strcat(buf, devname);
1135         } else {
1136                 strcpy(buf, devname);
1137         }
1138         /* truncate filename before calling realpath */
1139         ptr = strrchr(buf, '/');
1140         if (ptr == NULL) {
1141                 free(path);
1142                 return NULL;
1143         }
1144         *ptr = '\0';
1145         if (path != realpath(buf, path)) {
1146                 free(path);
1147                 return NULL;
1148         }
1149         /* add the filename back */
1150         strcat(path, "/");
1151         strcat(path, ptr + 1);
1152         return path;
1153 }
1154
1155 /* Determine if a device is a block device (as opposed to a file) */
1156 int is_block(char* devname)
1157 {
1158         struct stat st;
1159         int     ret = 0;
1160         char    *devpath;
1161
1162         devpath = absolute_path(devname);
1163         if (devpath == NULL) {
1164                 fprintf(stderr, "%s: failed to resolve path to %s\n",
1165                         progname, devname);
1166                 return -1;
1167         }
1168
1169         ret = access(devname, F_OK);
1170         if (ret != 0) {
1171                 if (strncmp(devpath, "/dev/", 5) == 0) {
1172                         /* nobody sane wants to create a loopback file under
1173                          * /dev. Let's just report the device doesn't exist */
1174                         fprintf(stderr, "%s: %s apparently does not exist\n",
1175                                 progname, devpath);
1176                         ret = -1;
1177                         goto out;
1178                 }
1179                 ret = 0;
1180                 goto out;
1181         }
1182         ret = stat(devpath, &st);
1183         if (ret != 0) {
1184                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
1185                 goto out;
1186         }
1187         ret = S_ISBLK(st.st_mode);
1188 out:
1189         free(devpath);
1190         return ret;
1191 }
1192
1193 static int is_feature_enabled(const char *feature, const char *devpath)
1194 {
1195         char cmd[PATH_MAX];
1196         FILE *fp;
1197         char enabled_features[4096] = "";
1198         int ret = 1;
1199
1200         snprintf(cmd, sizeof(cmd), "%s -R features %s 2>&1",
1201                  DEBUGFS, devpath);
1202
1203         /* Using popen() instead of run_command() since debugfs does
1204          * not return proper error code if command is not supported */
1205         fp = popen(cmd, "r");
1206         if (!fp) {
1207                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
1208                 return 0;
1209         }
1210
1211         ret = fread(enabled_features, 1, sizeof(enabled_features) - 1, fp);
1212         enabled_features[ret] = '\0';
1213         fclose(fp);
1214
1215         if (strstr(enabled_features, feature))
1216                 return 1;
1217         return 0;
1218 }
1219
1220 /* Enable quota accounting */
1221 int ldiskfs_enable_quota(struct mkfs_opts *mop)
1222 {
1223         char *dev;
1224         char cmd[512];
1225         int cmdsz = sizeof(cmd), ret;
1226
1227         if (is_e2fsprogs_feature_supp("-O quota") != 0) {
1228                 fprintf(stderr, "%s: \"-O quota\" is is not supported by "
1229                         "current e2fsprogs\n", progname);
1230                 return EINVAL;
1231         }
1232
1233         dev = mop->mo_device;
1234         if (mop->mo_flags & MO_IS_LOOP)
1235                 dev = mop->mo_loopdev;
1236
1237         /* Quota feature is already enabled? */
1238         if (is_feature_enabled("quota", dev)) {
1239                 vprint("Quota feature is already enabled.\n");
1240                 return 0;
1241         }
1242
1243         /* Turn on quota feature by "tune2fs -O quota" */
1244         snprintf(cmd, cmdsz, "%s -O quota %s", TUNE2FS, dev);
1245         ret = run_command(cmd, cmdsz);
1246         if (ret)
1247                 fprintf(stderr, "command:%s (%d)", cmd, ret);
1248
1249         return ret;
1250 }
1251
1252 int ldiskfs_init(void)
1253 {
1254         /* Required because full path to DEBUGFS is not specified */
1255         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin", 0);
1256
1257         return 0;
1258 }
1259
1260 void ldiskfs_fini(void)
1261 {
1262         return;
1263 }
1264