Whamcloud - gitweb
LU-14767 utils: mkfs.lustre allow lazy_itable_init=1
[fs/lustre-release.git] / lustre / utils / libmount_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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/mount_utils_ldiskfs.c
32  *
33  * Author: Nathan Rutman <nathan@clusterfs.com>
34 */
35
36 /* This source file is compiled into both mkfs.lustre and tunefs.lustre */
37
38 #if HAVE_CONFIG_H
39 #  include "config.h"
40 #endif /* HAVE_CONFIG_H */
41
42 #ifndef _GNU_SOURCE
43 #define _GNU_SOURCE
44 #endif
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <inttypes.h>
50 #include <unistd.h>
51 #include <dirent.h>
52 #include <fcntl.h>
53 #include <mntent.h>
54
55 #include <sys/types.h>
56 #include <sys/stat.h>
57 #include <sys/mount.h>
58 #include <sys/utsname.h>
59 #include <sys/sysmacros.h>
60
61 #include <string.h>
62 #include <getopt.h>
63 #include <limits.h>
64 #include <ctype.h>
65
66 #include <ext2fs/ext2fs.h>
67
68 #ifndef BLKGETSIZE64
69 #include <linux/fs.h> /* for BLKGETSIZE64 */
70 #endif
71 #include <linux/major.h>
72 #include <linux/types.h>
73 #include <linux/version.h>
74 #include <linux/lnet/lnetctl.h>
75 #include <linux/lustre/lustre_ver.h>
76 #include <libcfs/util/string.h>
77
78 #include "mount_utils.h"
79
80 #define MAX_HW_SECTORS_KB_PATH  "queue/max_hw_sectors_kb"
81 #define MAX_SECTORS_KB_PATH     "queue/max_sectors_kb"
82 #define SCHEDULER_PATH          "queue/scheduler"
83 #define STRIPE_CACHE_SIZE       "md/stripe_cache_size"
84
85 #define DEFAULT_SCHEDULER       "deadline"
86
87 extern char *progname;
88
89 static ext2_filsys backfs;
90 static int open_flags = EXT2_FLAG_64BITS | EXT2_FLAG_SKIP_MMP |
91                         EXT2_FLAG_IGNORE_SB_ERRORS | EXT2_FLAG_SUPER_ONLY;
92
93 /* keep it less than LL_FID_NAMELEN */
94 #define DUMMY_FILE_NAME_LEN             25
95 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
96
97 static void append_unique(char *buf, char *prefix, char *key, char *val,
98                           size_t maxbuflen);
99 static bool is_e2fsprogs_feature_supp(const char *feature);
100 static void disp_old_e2fsprogs_msg(const char *feature, int make_backfs);
101
102 /* Determine if a device is a block device (as opposed to a file) */
103 static int is_block(char *devname)
104 {
105         struct stat st;
106         int     ret = 0;
107         char    *devpath;
108
109         ret = cfs_abs_path(devname, &devpath);
110         if (ret != 0) {
111                 fprintf(stderr, "%s: failed to resolve path '%s': %s\n",
112                         progname, devname, strerror(-ret));
113                 return -1;
114         }
115
116         ret = access(devname, F_OK);
117         if (ret != 0) {
118                 if (strncmp(devpath, "/dev/", 5) == 0) {
119                         /* nobody sane wants to create a loopback file under
120                          * /dev. Let's just report the device doesn't exist */
121                         fprintf(stderr, "%s: %s apparently does not exist\n",
122                                 progname, devpath);
123                         ret = -1;
124                         goto out;
125                 }
126                 ret = 0;
127                 goto out;
128         }
129         ret = stat(devpath, &st);
130         if (ret != 0) {
131                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
132                 goto out;
133         }
134         ret = S_ISBLK(st.st_mode);
135 out:
136         free(devpath);
137         return ret;
138 }
139
140 /* Write the server config files */
141 int ldiskfs_write_ldd(struct mkfs_opts *mop)
142 {
143         char mntpt[] = "/tmp/mntXXXXXX";
144         char filepnm[192];
145         char *dev;
146         FILE *filep;
147         int ret = 0;
148         size_t num;
149
150         /* Mount this device temporarily in order to write these files */
151         if (!mkdtemp(mntpt)) {
152                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
153                         progname, mntpt, strerror(errno));
154                 return errno;
155         }
156
157         dev = mop->mo_device;
158         if (mop->mo_flags & MO_IS_LOOP)
159                 dev = mop->mo_loopdev;
160
161         /* Multiple mount protection enabled if failover node specified */
162         if (mop->mo_flags & MO_FAILOVER) {
163                 if (!backfs)
164                         ext2fs_open(dev, open_flags, 0, 0,
165                                     unix_io_manager, &backfs);
166                 if (!backfs || !ext2fs_has_feature_mmp(backfs->super)) {
167                         if (is_e2fsprogs_feature_supp("-O mmp")) {
168                                 char *command = filepnm;
169
170                                 snprintf(command, sizeof(filepnm),
171                                          TUNE2FS" -O mmp '%s' >/dev/null 2>&1",
172                                          dev);
173                                 ret = run_command(command, sizeof(filepnm));
174                                 if (ret)
175                                         fprintf(stderr,
176                                                 "%s: Unable to set 'mmp' "
177                                                 "on %s: %d\n",
178                                                 progname, dev, ret);
179                         } else {
180                                 disp_old_e2fsprogs_msg("mmp", 1);
181                         }
182                         /* avoid stale cache after following operations */
183                         if (backfs) {
184                                 ext2fs_close(backfs);
185                                 backfs = NULL;
186                         }
187                 }
188         }
189
190         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
191                 (mop->mo_mountopts == NULL) ?
192                 "errors=remount-ro" : mop->mo_mountopts);
193         if (ret) {
194                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
195                         progname, dev, strerror(errno));
196                 ret = errno;
197                 if (errno == ENODEV) {
198                         fprintf(stderr, "Is the %s module available?\n",
199                                 MT_STR(&mop->mo_ldd));
200                 }
201                 goto out_rmdir;
202         }
203
204         /* Set up initial directories */
205         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
206         ret = mkdir(filepnm, 0777);
207         if ((ret != 0) && (errno != EEXIST)) {
208                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
209                         progname, filepnm, strerror(errno));
210                 goto out_umnt;
211         } else if (errno == EEXIST) {
212                 ret = 0;
213         }
214
215         /* Save the persistent mount data into a file. Lustre must pre-read
216            this file to get the real mount options. */
217         vprint("Writing %s\n", MOUNT_DATA_FILE);
218         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
219         filep = fopen(filepnm, "w");
220         if (!filep) {
221                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
222                         progname, filepnm, strerror(errno));
223                 goto out_umnt;
224         }
225         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
226         if (num < 1 && ferror(filep)) {
227                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
228                         progname, filepnm, strerror(errno));
229                 fclose(filep);
230                 goto out_umnt;
231         }
232         fsync(filep->_fileno);
233         fclose(filep);
234
235 out_umnt:
236         umount(mntpt);
237 out_rmdir:
238         rmdir(mntpt);
239         return ret;
240 }
241
242 static int readcmd(char *cmd, char *buf, int len)
243 {
244         FILE *fp;
245         int red;
246
247         fp = popen(cmd, "r");
248         if (!fp)
249                 return errno;
250
251         red = fread(buf, 1, len, fp);
252         pclose(fp);
253
254         /* strip trailing newline */
255         if (buf[red - 1] == '\n')
256                 buf[red - 1] = '\0';
257
258         return (red == 0) ? -ENOENT : 0;
259 }
260
261 int ldiskfs_read_ldd(char *dev, struct lustre_disk_data *mo_ldd)
262 {
263         errcode_t retval;
264         ext2_ino_t ino;
265         ext2_file_t file;
266         unsigned int got;
267         char cmd[PATH_MAX];
268         int ret = 0;
269
270         if (!backfs) {
271                 retval = ext2fs_open(dev, open_flags, 0, 0,
272                                      unix_io_manager, &backfs);
273                 if (retval) {
274                         fprintf(stderr, "Unable to open fs on %s\n", dev);
275                         goto read_label;
276                 }
277         }
278         retval = ext2fs_namei(backfs, EXT2_ROOT_INO, EXT2_ROOT_INO,
279                               MOUNT_DATA_FILE, &ino);
280         if (retval) {
281                 fprintf(stderr, "Error while looking up %s\n", MOUNT_DATA_FILE);
282                 goto read_label;
283         }
284         retval = ext2fs_file_open(backfs, ino, 0, &file);
285         if (retval) {
286                 fprintf(stderr, "Error while opening file %s\n",
287                         MOUNT_DATA_FILE);
288                 goto read_label;
289         }
290         retval = ext2fs_file_read(file, mo_ldd, sizeof(*mo_ldd), &got);
291         if (retval || got == 0)
292                 fprintf(stderr, "Failed to read file %s\n", MOUNT_DATA_FILE);
293 read_label:
294         /* As long as we at least have the label, we're good to go */
295         snprintf(cmd, sizeof(cmd), E2LABEL" %s", dev);
296         ret = readcmd(cmd, mo_ldd->ldd_svname, sizeof(mo_ldd->ldd_svname) - 1);
297
298         return ret;
299 }
300
301 int ldiskfs_erase_ldd(struct mkfs_opts *mop, char *param)
302 {
303         return 0;
304 }
305
306 void ldiskfs_print_ldd_params(struct mkfs_opts *mop)
307 {
308         printf("Parameters:%s\n", mop->mo_ldd.ldd_params);
309 }
310
311 /* Display the need for the latest e2fsprogs to be installed. make_backfs
312  * indicates if the caller is make_lustre_backfs() or not. */
313 static void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
314 {
315         static int msg_displayed;
316
317         if (msg_displayed) {
318                 fprintf(stderr, "WARNING: %s does not support %s "
319                         "feature.\n\n", E2FSPROGS, feature);
320                 return;
321         }
322
323         msg_displayed++;
324
325         fprintf(stderr, "WARNING: The %s package currently installed on "
326                 "your system does not support \"%s\" feature.\n",
327                 E2FSPROGS, feature);
328 #if !(HAVE_LDISKFSPROGS)
329         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
330                 "https://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
331                 "to enable this feature.\n");
332 #endif
333         if (make_backfs)
334                 fprintf(stderr,
335                         "Feature will not be enabled until %s is updated and '%s -O %s %%{device}' is run.\n\n",
336                         E2FSPROGS, TUNE2FS, feature);
337 }
338
339 /* Check whether the file exists in the device */
340 static int file_in_dev(char *file_name, char *dev_name)
341 {
342         ext2_ino_t ino;
343         errcode_t retval;
344
345         if (!backfs) {
346                 retval = ext2fs_open(dev_name, open_flags, 0, 0,
347                                      unix_io_manager, &backfs);
348                 if (retval)
349                         return 0;
350         }
351         retval = ext2fs_namei(backfs, EXT2_ROOT_INO, EXT2_ROOT_INO,
352                               file_name, &ino);
353         if (!retval)
354                 return 1;
355
356         return 0;
357 }
358
359 /* Check whether the device has already been used with lustre */
360 int ldiskfs_is_lustre(char *dev, unsigned *mount_type)
361 {
362         int ret;
363
364         ret = file_in_dev(MOUNT_DATA_FILE, dev);
365         if (ret) {
366                 /* in the -1 case, 'extents' means IS a lustre target */
367                 *mount_type = LDD_MT_LDISKFS;
368                 return 1;
369         }
370
371         ret = file_in_dev(LAST_RCVD, dev);
372         if (ret) {
373                 *mount_type = LDD_MT_LDISKFS;
374                 return 1;
375         }
376
377         return 0;
378 }
379
380 /* Check if a certain feature is supported by e2fsprogs.
381  * Firstly we try to use "debugfs supported_features" command to check if
382  * the feature is supported. If this fails we try to set this feature with
383  * mke2fs to check for its support. */
384 static bool is_e2fsprogs_feature_supp(const char *feature)
385 {
386         static char supp_features[4096] = "";
387         FILE *fp;
388         char cmd[PATH_MAX];
389         char imgname[] = "/tmp/test-img-XXXXXX";
390         int fd;
391         int ret;
392
393         if (supp_features[0] == '\0') {
394                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
395                          DEBUGFS);
396
397                 /* Using popen() instead of run_command() since debugfs does
398                  * not return proper error code if command is not supported */
399                 fp = popen(cmd, "r");
400                 if (!fp) {
401                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
402                 } else {
403                         ret = fread(supp_features, 1,
404                                     sizeof(supp_features) - 1, fp);
405                         supp_features[ret] = '\0';
406                         pclose(fp);
407                 }
408         }
409
410         if (strstr(supp_features,
411                    strncmp(feature, "-O ", 3) ? feature : feature + 3))
412                 return true;
413
414         if ((fd = mkstemp(imgname)) < 0)
415                 return false;
416
417         close(fd);
418
419         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
420                  MKE2FS, feature, imgname);
421         /* run_command() displays the output of mke2fs when it fails for
422          * some feature, so use system() directly */
423         ret = system(cmd);
424         unlink(imgname);
425
426         return ret == 0;
427 }
428
429 /**
430  * append_unique: append @key or @key=@val pair to @buf only if @key does not
431  *                exists
432  *      @buf: buffer to hold @key or @key=@val
433  *      @prefix: prefix string before @key
434  *      @key: key string
435  *      @val: value string if it's a @key=@val pair
436  */
437 static void append_unique(char *buf, char *prefix, char *key, char *val,
438                           size_t maxbuflen)
439 {
440         char *anchor, *end;
441         int  len;
442
443         if (key == NULL)
444                 return;
445
446         anchor = end = strstr(buf, key);
447         /* try to find exact match string in @buf */
448         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
449                 ++end;
450         len = end - anchor;
451         if (anchor == NULL || strlen(key) != len ||
452                         strncmp(anchor, key, len) != 0) {
453                 if (prefix != NULL)
454                         strscat(buf, prefix, maxbuflen);
455
456                 strscat(buf, key, maxbuflen);
457                 if (val != NULL) {
458                         strscat(buf, "=\"", maxbuflen);
459                         strscat(buf, val, maxbuflen);
460                         strscat(buf, "\"", maxbuflen);
461                 }
462         }
463 }
464
465 static int enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
466                                         size_t maxbuflen, bool user_spec)
467 {
468         unsigned long long blocks = mop->mo_device_kb / mop->mo_blocksize_kb;
469         bool enable_64bit = false;
470
471         /* Enable large block addresses if the LUN is over 2^32 blocks. */
472         if (blocks > 0xffffffffULL && is_e2fsprogs_feature_supp("-O 64bit"))
473                 enable_64bit = true;
474
475         if (IS_OST(&mop->mo_ldd)) {
476                 append_unique(anchor, user_spec ? "," : " -O ",
477                               "extents", NULL, maxbuflen);
478                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
479         } else if (IS_MDT(&mop->mo_ldd)) {
480                 append_unique(anchor, user_spec ? "," : " -O ",
481                               "dirdata", NULL, maxbuflen);
482                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
483                 if (enable_64bit)
484                         append_unique(anchor, ",", "extents", NULL, maxbuflen);
485                 else
486                         append_unique(anchor, ",", "^extents", NULL, maxbuflen);
487         } else {
488                 append_unique(anchor, user_spec ? "," : " -O ",
489                               "uninit_bg", NULL, maxbuflen);
490         }
491
492         /* Multiple mount protection enabled only if failover node specified */
493         if (mop->mo_flags & MO_FAILOVER) {
494                 if (is_e2fsprogs_feature_supp("-O mmp"))
495                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
496                 else
497                         disp_old_e2fsprogs_msg("mmp", 1);
498         }
499
500         /* Allow more than 65000 subdirectories */
501         if (is_e2fsprogs_feature_supp("-O dir_nlink"))
502                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
503
504         /* The following options are only valid for ext4-based ldiskfs.
505          * If --backfstype=ext3 is specified, do not enable them. */
506         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
507                 return 0;
508
509         /* Enable quota by default */
510         if (is_e2fsprogs_feature_supp("-O quota")) {
511                 append_unique(anchor, ",", "quota", NULL, maxbuflen);
512                 /* Enable project quota by default */
513                 if (is_e2fsprogs_feature_supp("-O project"))
514                         append_unique(anchor, ",", "project", NULL, maxbuflen);
515         } else {
516                 fatal();
517                 fprintf(stderr, "\"-O quota\" must be supported by "
518                         "e2fsprogs, please upgrade your e2fsprogs.\n");
519                 return EINVAL;
520         }
521
522         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
523         if (is_e2fsprogs_feature_supp("-O huge_file"))
524                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
525
526         if (enable_64bit)
527                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
528
529         if (blocks >= 0x1000000000 && is_e2fsprogs_feature_supp("-O meta_bg"))
530                 append_unique(anchor, ",", "meta_bg", NULL, maxbuflen);
531
532         if (enable_64bit || strstr(mop->mo_mkfsopts, "meta_bg"))
533                 append_unique(anchor, ",", "^resize_inode", NULL, maxbuflen);
534
535         /* Allow xattrs larger than one block, stored in a separate inode */
536         if (IS_MDT(&mop->mo_ldd) && is_e2fsprogs_feature_supp("-O ea_inode"))
537                 append_unique(anchor, ",", "ea_inode", NULL, maxbuflen);
538
539         /* Allow more than 10M directory entries */
540         if (IS_MDT(&mop->mo_ldd) && is_e2fsprogs_feature_supp("-O large_dir"))
541                 append_unique(anchor, ",", "large_dir", NULL, maxbuflen);
542
543         /* Cluster inode/block bitmaps and inode table for more efficient IO.
544          * Align the flex groups on a 1MB boundary for better performance. */
545         /* This -O feature needs to go last, since it adds the "-G" option. */
546         if (is_e2fsprogs_feature_supp("-O flex_bg")) {
547                 char tmp_buf[64];
548
549                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
550
551                 if (IS_OST(&mop->mo_ldd) &&
552                     strstr(mop->mo_mkfsopts, "-G") == NULL) {
553                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
554                                  1024 / mop->mo_blocksize_kb);
555                         strscat(anchor, tmp_buf, maxbuflen);
556                 }
557         }
558         /* Don't add any more "-O" options here, see last comment above */
559         return 0;
560 }
561
562 /**
563  * moveopts_to_end: find the option string, move remaining strings to
564  *                  where option string starts, and append the option
565  *                  string at the end
566  *      @start: where the option string starts before the move
567  *      RETURN: where the option string starts after the move
568  */
569 static char *moveopts_to_end(char *start)
570 {
571         size_t len;
572         char save[512];
573         char *end, *idx;
574
575         /* skip whitespace before options */
576         end = start + 2;
577         while (*end == ' ')
578                 ++end;
579
580         /* find end of option characters */
581         while (*end != ' ' && *end != '\0')
582                 ++end;
583
584         len = end - start;
585         if (len >= sizeof(save))
586                 len = sizeof(save) - 1;
587
588         /* save options */
589         strncpy(save, start, len);
590         save[len] = '\0';
591
592         /* move remaining options up front */
593         if (*end)
594                 memmove(start, end, strlen(end));
595         *(start + strlen(end)) = '\0';
596
597         /* append the specified options */
598         if (*(start + strlen(start) - 1) != ' ')
599                 strcat(start, " ");
600         idx = start + strlen(start);
601         strcat(start, save);
602
603         return idx;
604 }
605
606 /* Build fs according to type */
607 int ldiskfs_make_lustre(struct mkfs_opts *mop)
608 {
609         char mkfs_cmd[PATH_MAX];
610         char buf[64];
611         char *start;
612         char *dev;
613         int ret = 0, ext_opts = 0;
614         bool enable_64bit = false;
615         long inode_size = 0;
616         size_t maxbuflen;
617
618         mop->mo_blocksize_kb = 4;
619
620         start = strstr(mop->mo_mkfsopts, "-b");
621         if (start) {
622                 char *end = NULL;
623                 long blocksize;
624
625                 blocksize = strtol(start + 2, &end, 0);
626                 if (end && (*end == 'k' || *end == 'K'))
627                         blocksize *= 1024;
628                 /* EXT4_MIN_BLOCK_SIZE || EXT4_MAX_BLOCK_SIZE */
629                 if (blocksize < 1024 || blocksize > 65536) {
630                         fprintf(stderr,
631                                 "%s: blocksize %lu not in 1024-65536 bytes, normally 4096 bytes\n",
632                                 progname, blocksize);
633                         return EINVAL;
634                 }
635
636                 if ((blocksize & (blocksize - 1)) != 0) {
637                         fprintf(stderr,
638                                 "%s: blocksize %lu not a power-of-two value\n",
639                                 progname, blocksize);
640                         return EINVAL;
641                 }
642                 mop->mo_blocksize_kb = blocksize >> 10;
643         }
644
645         if (!(mop->mo_flags & MO_IS_LOOP)) {
646                 __u64 device_kb = get_device_size(mop->mo_device);
647
648                 if (device_kb == 0)
649                         return ENODEV;
650
651                 /* Compare to real size */
652                 if (mop->mo_device_kb == 0 || device_kb < mop->mo_device_kb)
653                         mop->mo_device_kb = device_kb;
654         }
655
656         if (mop->mo_device_kb != 0) {
657                 __u64 block_count;
658
659                 if (mop->mo_device_kb < 32384) {
660                         fprintf(stderr, "%s: size of filesystem must be larger "
661                                 "than 32MB, but is set to %lldKB\n",
662                                 progname, (long long)mop->mo_device_kb);
663                         return EINVAL;
664                 }
665                 block_count = mop->mo_device_kb / mop->mo_blocksize_kb;
666                 if (block_count > 0xffffffffULL) {
667                         /* If the LUN size is just over 2^32 blocks, limit the
668                          * filesystem size to 2^32-1 blocks to avoid problems
669                          * with ldiskfs/mkfs not handling this well. b=22906
670                          */
671                         if (block_count < 0x100002000ULL)
672                                 mop->mo_device_kb =
673                                         0xffffffffULL * mop->mo_blocksize_kb;
674                         else
675                                 enable_64bit = true;
676                 }
677         }
678
679         if ((mop->mo_ldd.ldd_mount_type != LDD_MT_EXT3) &&
680             (mop->mo_ldd.ldd_mount_type != LDD_MT_LDISKFS) &&
681             (mop->mo_ldd.ldd_mount_type != LDD_MT_LDISKFS2)) {
682                 fprintf(stderr, "%s: unsupported fs type: %d (%s)\n",
683                         progname, mop->mo_ldd.ldd_mount_type,
684                         MT_STR(&mop->mo_ldd));
685
686                 return EINVAL;
687         }
688
689         /* Journal size in MB */
690         if (strstr(mop->mo_mkfsopts, "-J") == NULL &&
691             mop->mo_device_kb > 1024 * 1024) {
692                 /* Choose our own default journal size */
693                 long journal_mb = 0, max_mb;
694
695                 /* cap journal size at 4GB for MDT, leave at 1GB for OSTs */
696                 if (IS_MDT(&mop->mo_ldd))
697                         max_mb = 4096;
698                 else if (IS_OST(&mop->mo_ldd))
699                         max_mb = 1024;
700                 else /* Use mke2fs default size for MGS */
701                         max_mb = 0;
702
703                 /* Use at most 4% of device for journal */
704                 journal_mb = mop->mo_device_kb * 4 / (1024 * 100);
705                 if (journal_mb > max_mb)
706                         journal_mb = max_mb;
707
708                 if (journal_mb) {
709                         snprintf(buf, sizeof(buf), " -J size=%ld", journal_mb);
710                         strscat(mop->mo_mkfsopts, buf,
711                                 sizeof(mop->mo_mkfsopts));
712                 }
713         }
714
715         /*
716          * The inode size is constituted by following elements
717          * (assuming all files are in composite layout and has
718          * 3 components):
719          *
720          *   ldiskfs inode size: 160
721          *   MDT extended attributes size, including:
722          *      ext4_xattr_header: 32
723          *      LOV EA size: 32(lov_comp_md_v1) +
724          *                   3 * 40(lov_comp_md_entry_v1) +
725          *                   3 * 32(lov_mds_md) +
726          *                   stripes * 24(lov_ost_data) +
727          *                   16(xattr_entry) + 4("lov")
728          *      LMA EA size: 24(lustre_mdt_attrs) +
729          *                   16(xattr_entry) + 4("lma")
730          *      SOM EA size: 24(lustre_som_attrs) +
731          *                   16(xattr_entry) + 4("som")
732          *      link EA size: 24(link_ea_header) + 18(link_ea_entry) +
733          *                    16(filename) + 16(xattr_entry) + 4("link")
734          *   and some margin for 4-byte alignment, ACLs and other EAs.
735          *
736          * If we say the average filename length is about 32 bytes,
737          * the calculation looks like:
738          * 160 + 32 + (32+3*(40+32)+24*stripes+20) + (24+20) + (24+20) +
739          *  (24+20) + (~42+16+20) + other <= 512*2^m, {m=0,1,2,3}
740          */
741         if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
742                 if (IS_MDT(&mop->mo_ldd)) {
743                         if (mop->mo_stripe_count > 59)
744                                 inode_size = 512; /* bz 7241 */
745                         /* see also "-i" below for EA blocks */
746                         else if (mop->mo_stripe_count > 16)
747                                 inode_size = 2048;
748                         else
749                                 inode_size = 1024;
750                 } else if (IS_OST(&mop->mo_ldd)) {
751                         /* We store MDS FID and necessary composite
752                          * layout information in the OST object EA:
753                          *   ldiskfs inode size: 160
754                          *   OST extended attributes size, including:
755                          *      ext4_xattr_header: 32
756                          *      LMA EA size: 24(lustre_mdt_attrs) +
757                          *                   16(xattr_entry) + 4("lma")
758                          *      FID EA size: 52(filter_fid) +
759                          *                   16(xattr_entry) + 4("fid")
760                          * 160 + 32 + (24+20) + (52+20) = 308
761                          */
762                         inode_size = 512;
763                 }
764
765                 if (inode_size > 0) {
766                         snprintf(buf, sizeof(buf), " -I %ld", inode_size);
767                         strscat(mop->mo_mkfsopts, buf,
768                                 sizeof(mop->mo_mkfsopts));
769                 }
770         }
771
772         /* Bytes_per_inode: disk size / num inodes */
773         if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
774             strstr(mop->mo_mkfsopts, "-N") == NULL) {
775                 long bytes_per_inode = 0;
776
777                 /* Allocate more inodes on MDT devices.  There is
778                  * no data stored on the MDT, and very little extra
779                  * metadata beyond the inode.  It could go down as
780                  * low as 1024 bytes, but this is conservative.
781                  * Account for external EA blocks for wide striping.
782                  */
783                 if (IS_MDT(&mop->mo_ldd)) {
784                         bytes_per_inode = inode_size + 1536;
785
786                         if (mop->mo_stripe_count > 59) {
787                                 int extra = mop->mo_stripe_count * 24;
788
789                                 extra = ((extra - 1) | 4095) + 1;
790                                 bytes_per_inode += extra;
791                         }
792                 }
793
794                 /* Allocate fewer inodes on large OST devices.  Most
795                  * filesystems can be much more aggressive than even
796                  * this, but it is impossible to know in advance.
797                  */
798                 if (IS_OST(&mop->mo_ldd)) {
799                         /* OST > 16TB assume average file size 1MB */
800                         if (mop->mo_device_kb > (16ULL << 30))
801                                 bytes_per_inode = 1024 * 1024;
802                         /* OST > 4TB assume average file size 512kB */
803                         else if (mop->mo_device_kb > (4ULL << 30))
804                                 bytes_per_inode = 512 * 1024;
805                         /* OST > 1TB assume average file size 256kB */
806                         else if (mop->mo_device_kb > (1ULL << 30))
807                                 bytes_per_inode = 256 * 1024;
808                         /* OST > 10GB assume average file size 64kB,
809                          * plus a bit so that inodes will fit into a
810                          * 256x flex_bg without overflowing.
811                          */
812                         else if (mop->mo_device_kb > (10ULL << 20))
813                                 bytes_per_inode = 69905;
814                 }
815
816                 if (bytes_per_inode > 0) {
817                         snprintf(buf, sizeof(buf), " -i %ld", bytes_per_inode);
818                         strscat(mop->mo_mkfsopts, buf,
819                                 sizeof(mop->mo_mkfsopts));
820                         mop->mo_inode_size = bytes_per_inode;
821                 }
822         }
823
824         if (verbose < 2)
825                 strscat(mop->mo_mkfsopts, " -q", sizeof(mop->mo_mkfsopts));
826
827         /* start handle -O mkfs options */
828         start = strstr(mop->mo_mkfsopts, "-O");
829         if (start) {
830                 if (strstr(start + 2, "-O") != NULL) {
831                         fprintf(stderr,
832                                 "%s: don't specify multiple -O options\n",
833                                 progname);
834                         return EINVAL;
835                 }
836                 start = moveopts_to_end(start);
837                 maxbuflen = sizeof(mop->mo_mkfsopts) -
838                         (start - mop->mo_mkfsopts) - strlen(start);
839                 ret = enable_default_ext4_features(mop, start, maxbuflen, 1);
840         } else {
841                 start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
842                 maxbuflen = sizeof(mop->mo_mkfsopts) - strlen(mop->mo_mkfsopts);
843                 ret = enable_default_ext4_features(mop, start, maxbuflen, 0);
844         }
845         if (ret)
846                 return ret;
847         /* end handle -O mkfs options */
848
849         /* start handle -E mkfs options */
850         start = strstr(mop->mo_mkfsopts, "-E");
851         if (start) {
852                 if (strstr(start + 2, "-E") != NULL) {
853                         fprintf(stderr,
854                                 "%s: don't specify multiple -E options\n",
855                                 progname);
856                         return EINVAL;
857                 }
858                 start = moveopts_to_end(start);
859                 maxbuflen = sizeof(mop->mo_mkfsopts) -
860                         (start - mop->mo_mkfsopts) - strlen(start);
861                 ext_opts = 1;
862         } else {
863                 start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
864                 maxbuflen = sizeof(mop->mo_mkfsopts) - strlen(mop->mo_mkfsopts);
865         }
866
867         /* In order to align the filesystem metadata on 1MB boundaries,
868          * give a resize value that will reserve a power-of-two group
869          * descriptor blocks, but leave one block for the superblock.
870          * Only useful for filesystems with < 2^32 blocks due to resize
871          * limitations.
872          */
873         if (!enable_64bit && strstr(mop->mo_mkfsopts, "meta_bg") == NULL &&
874             IS_OST(&mop->mo_ldd) && mop->mo_device_kb > 100 * 1024) {
875                 unsigned int group_blocks = mop->mo_blocksize_kb * 8192;
876                 unsigned int desc_per_block = mop->mo_blocksize_kb * 1024 / 32;
877                 unsigned int resize_blks;
878
879                 resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
880                 snprintf(buf, sizeof(buf), "%u", resize_blks);
881                 append_unique(start, ext_opts ? "," : " -E ",
882                               "resize", buf, maxbuflen);
883                 ext_opts = 1;
884         }
885
886         /* Avoid zeroing out the full journal - speeds up mkfs */
887         if (is_e2fsprogs_feature_supp("-E lazy_journal_init=0")) {
888                 append_unique(start, ext_opts ? "," : " -E ",
889                               "lazy_journal_init", "0", maxbuflen);
890                 ext_opts = 1;
891         }
892         if (is_e2fsprogs_feature_supp("-E lazy_itable_init=0")) {
893                 append_unique(start, ext_opts ? "," : "-E",
894                             "lazy_itable_init", "0", maxbuflen);
895                 ext_opts = 1;
896         }
897
898         /* end handle -E mkfs options */
899
900         /* Allow reformat of full devices (as opposed to partitions).
901          * We already checked for mounted dev.
902          */
903         strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
904
905         snprintf(mkfs_cmd, sizeof(mkfs_cmd), "%s -j -b %d -L %s ", MKE2FS,
906                  mop->mo_blocksize_kb * 1024, mop->mo_ldd.ldd_svname);
907
908         /* For loop device format the dev, not the filename */
909         dev = mop->mo_device;
910         if (mop->mo_flags & MO_IS_LOOP)
911                 dev = mop->mo_loopdev;
912
913         vprint("formatting backing filesystem %s on %s\n",
914                MT_STR(&mop->mo_ldd), dev);
915         vprint("\ttarget name   %s\n", mop->mo_ldd.ldd_svname);
916         vprint("\tkilobytes     %llu\n", mop->mo_device_kb);
917         vprint("\toptions       %s\n", mop->mo_mkfsopts);
918
919         /* mkfs_cmd's trailing space is important! */
920         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
921         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
922         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
923         if (mop->mo_device_kb != 0) {
924                 snprintf(buf, sizeof(buf), " %lluk",
925                          (unsigned long long)mop->mo_device_kb);
926                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
927         }
928
929         vprint("mkfs_cmd = %s\n", mkfs_cmd);
930         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
931         if (ret) {
932                 fatal();
933                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
934         }
935         return ret;
936 }
937
938 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
939                            char *wanted_mountopts, size_t len)
940 {
941         struct lustre_disk_data *ldd = &mop->mo_ldd;
942         int ret;
943
944         /* Set MO_IS_LOOP to indicate a loopback device is needed */
945         ret = is_block(mop->mo_device);
946         if (ret < 0) {
947                 return errno;
948         } else if (ret == 0) {
949                 mop->mo_flags |= MO_IS_LOOP;
950         }
951
952         if (IS_MDT(ldd) || IS_MGS(ldd))
953                 strscat(wanted_mountopts, ",user_xattr", len);
954
955         return 0;
956 }
957
958 int ldiskfs_fix_mountopts(struct mkfs_opts *mop, char *mountopts, size_t len)
959 {
960         if (strstr(mountopts, "errors=") == NULL)
961                 strscat(mountopts, ",errors=remount-ro", len);
962
963         return 0;
964 }
965
966 static int read_file(const char *path, char *buf, int size)
967 {
968         FILE *fd;
969
970         fd = fopen(path, "r");
971         if (fd == NULL)
972                 return errno;
973
974         if (fgets(buf, size, fd) == NULL) {
975                 fprintf(stderr, "reading from %s: %s", path, strerror(errno));
976                 fclose(fd);
977                 return 1;
978         }
979         fclose(fd);
980
981         /* strip trailing newline */
982         size = strlen(buf);
983         if (buf[size - 1] == '\n')
984                 buf[size - 1] = '\0';
985
986         return 0;
987 }
988
989 static int write_file(const char *path, const char *buf)
990 {
991         int fd, rc;
992
993         fd = open(path, O_WRONLY);
994         if (fd < 0)
995                 return errno;
996
997         rc = write(fd, buf, strlen(buf));
998         close(fd);
999
1000         return rc < 0 ? errno : 0;
1001 }
1002
1003 static int tune_md_stripe_cache_size(const char *sys_path,
1004                                      struct mount_opts *mop)
1005 {
1006         char path[PATH_MAX];
1007         unsigned long old_stripe_cache_size;
1008         unsigned long new_stripe_cache_size;
1009         char buf[3 * sizeof(old_stripe_cache_size) + 2];
1010         int rc;
1011
1012         if (mop->mo_md_stripe_cache_size <= 0)
1013                 return 0;
1014
1015         new_stripe_cache_size = mop->mo_md_stripe_cache_size;
1016
1017         snprintf(path, sizeof(path), "%s/%s", sys_path, STRIPE_CACHE_SIZE);
1018         rc = read_file(path, buf, sizeof(buf));
1019         if (rc != 0) {
1020                 if (verbose)
1021                         fprintf(stderr, "warning: cannot read '%s': %s\n",
1022                                 path, strerror(errno));
1023                 return rc;
1024         }
1025
1026         old_stripe_cache_size = strtoul(buf, NULL, 0);
1027         if (old_stripe_cache_size == 0 || old_stripe_cache_size == ULONG_MAX)
1028                 return EINVAL;
1029
1030         if (new_stripe_cache_size <= old_stripe_cache_size)
1031                 return 0;
1032
1033         snprintf(buf, sizeof(buf), "%lu", new_stripe_cache_size);
1034         rc = write_file(path, buf);
1035         if (rc != 0) {
1036                 if (verbose)
1037                         fprintf(stderr, "warning: cannot write '%s': %s\n",
1038                                 path, strerror(errno));
1039                 return rc;
1040         }
1041
1042         return 0;
1043 }
1044
1045 static int tune_max_sectors_kb(const char *sys_path, struct mount_opts *mop)
1046 {
1047         char path[PATH_MAX];
1048         unsigned long max_hw_sectors_kb;
1049         unsigned long old_max_sectors_kb;
1050         unsigned long new_max_sectors_kb;
1051         char buf[3 * sizeof(old_max_sectors_kb) + 2];
1052         int rc;
1053
1054         if (mop->mo_max_sectors_kb >= 0) {
1055                 new_max_sectors_kb = mop->mo_max_sectors_kb;
1056                 goto have_new_max_sectors_kb;
1057         }
1058
1059         snprintf(path, sizeof(path), "%s/%s", sys_path, MAX_HW_SECTORS_KB_PATH);
1060         rc = read_file(path, buf, sizeof(buf));
1061         if (rc != 0) {
1062                 /* No MAX_HW_SECTORS_KB_PATH isn't necessary an
1063                  * error for some devices. */
1064                 return 0;
1065         }
1066
1067         max_hw_sectors_kb = strtoul(buf, NULL, 0);
1068         if (max_hw_sectors_kb == 0 || max_hw_sectors_kb == ULLONG_MAX) {
1069                 /* No digits at all or something weird. */
1070                 return 0;
1071         }
1072
1073         new_max_sectors_kb = max_hw_sectors_kb;
1074
1075         /* Don't increase IO request size limit past 16MB.  It is
1076          * about PTLRPC_MAX_BRW_SIZE, but that isn't in a public
1077          * header.  Note that even though the block layer allows
1078          * larger values, setting max_sectors_kb = 32768 causes
1079          * crashes (LU-6974). */
1080         if (new_max_sectors_kb > 16 * 1024)
1081                 new_max_sectors_kb = 16 * 1024;
1082
1083 have_new_max_sectors_kb:
1084         snprintf(path, sizeof(path), "%s/%s", sys_path, MAX_SECTORS_KB_PATH);
1085         rc = read_file(path, buf, sizeof(buf));
1086         if (rc != 0) {
1087                 /* No MAX_SECTORS_KB_PATH isn't necessary an error for
1088                  * some devices. */
1089                 return 0;
1090         }
1091
1092         old_max_sectors_kb = strtoul(buf, NULL, 0);
1093         if (old_max_sectors_kb == 0 || old_max_sectors_kb == ULLONG_MAX) {
1094                 /* No digits at all or something weird. */
1095                 return 0;
1096         }
1097
1098         if (new_max_sectors_kb <= old_max_sectors_kb)
1099                 return 0;
1100
1101         snprintf(buf, sizeof(buf), "%lu", new_max_sectors_kb);
1102         rc = write_file(path, buf);
1103         if (rc != 0) {
1104                 if (verbose)
1105                         fprintf(stderr, "warning: cannot write '%s': %s\n",
1106                                 path, strerror(errno));
1107                 return rc;
1108         }
1109
1110         fprintf(stderr, "%s: increased '%s' from %lu to %lu\n",
1111                 progname, path, old_max_sectors_kb, new_max_sectors_kb);
1112
1113         return 0;
1114 }
1115
1116 static int tune_block_dev_scheduler(const char *sys_path, const char *new_sched)
1117 {
1118         char path[PATH_MAX];
1119         char buf[PATH_MAX];
1120         char *s, *e;
1121         char *old_sched;
1122         int rc;
1123
1124         /* Before setting the scheduler, we need to check to see if
1125          * it's already set to "noop". If it is then we don't want to
1126          * override that setting. If it's set to anything other than
1127          * "noop" then set the scheduler to what has been passed
1128          * in. */
1129
1130         snprintf(path, sizeof(path), "%s/%s", sys_path, SCHEDULER_PATH);
1131         rc = read_file(path, buf, sizeof(buf));
1132         if (rc != 0) {
1133                 if (verbose)
1134                         fprintf(stderr, "%s: cannot read '%s': %s\n",
1135                                 progname, path, strerror(errno));
1136
1137                 return rc;
1138         }
1139
1140         /* The expected format of buf: noop anticipatory deadline [cfq] */
1141         s = strchr(buf, '[');
1142         e = strchr(buf, ']');
1143
1144         /* If the format is not what we expect then be safe and error out. */
1145         if (s == NULL || e == NULL || !(s < e)) {
1146                 if (verbose)
1147                         fprintf(stderr,
1148                                 "%s: cannot parse scheduler options for '%s'\n",
1149                                 progname, path);
1150
1151                 return EINVAL;
1152         }
1153
1154         old_sched = s + 1;
1155         *e = '\0';
1156
1157         if (strcmp(old_sched, "noop") == 0 ||
1158             strcmp(old_sched, "deadline") == 0 ||
1159             strcmp(old_sched, "mq-deadline") == 0 ||
1160             strstr(old_sched, new_sched) == 0)
1161                 return 0;
1162
1163         rc = write_file(path, new_sched);
1164         if (rc != 0) {
1165                 if (verbose)
1166                         fprintf(stderr,
1167                                 "%s: cannot set scheduler on '%s': %s\n",
1168                                 progname, path, strerror(errno));
1169                 return rc;
1170         }
1171
1172         fprintf(stderr, "%s: changed scheduler of '%s' from %s to %s\n",
1173                 progname, path, old_sched, new_sched);
1174
1175         return 0;
1176 }
1177
1178 static int tune_block_dev(const char *src, struct mount_opts *mop);
1179
1180 static int tune_block_dev_slaves(const char *sys_path, struct mount_opts *mop)
1181 {
1182         char slaves_path[PATH_MAX];
1183         DIR *slaves_dir;
1184         struct dirent *d;
1185         int rc = 0;
1186
1187         snprintf(slaves_path, sizeof(slaves_path), "%s/slaves", sys_path);
1188         slaves_dir = opendir(slaves_path);
1189         if (slaves_dir == NULL) {
1190                 if (errno == ENOENT)
1191                         return 0;
1192
1193                 return errno;
1194         }
1195
1196         while ((d = readdir(slaves_dir)) != NULL) {
1197                 char path[PATH_MAX * 2];
1198                 int rc2;
1199
1200                 if (d->d_type != DT_LNK)
1201                         continue;
1202
1203                 snprintf(path, sizeof(path), "/dev/%s", d->d_name);
1204                 rc2 = tune_block_dev(path, mop);
1205                 if (rc2 != 0)
1206                         rc = rc2;
1207         }
1208
1209         closedir(slaves_dir);
1210
1211         return rc;
1212 }
1213
1214 /* This is to tune the kernel for good SCSI performance.
1215  * For that we set the value of /sys/block/{dev}/queue/max_sectors_kb
1216  * to the value of /sys/block/{dev}/queue/max_hw_sectors_kb */
1217 static int tune_block_dev(const char *src, struct mount_opts *mop)
1218 {
1219         struct stat st;
1220         char sys_path[PATH_MAX];
1221         char partition_path[PATH_MAX + sizeof("partition")];
1222         char *real_sys_path = NULL;
1223         int rc;
1224
1225         /*
1226          * Don't apply block device tuning for MDT or MGT devices,
1227          * since we don't need huge IO sizes to get good performance
1228          */
1229         if (!IS_OST(&mop->mo_ldd))
1230                 return 0;
1231
1232         if (src == NULL)
1233                 return EINVAL;
1234
1235         rc = stat(src, &st);
1236         if (rc < 0) {
1237                 if (verbose)
1238                         fprintf(stderr, "warning: cannot stat '%s': %s\n",
1239                                 src, strerror(errno));
1240                 return errno;
1241         }
1242
1243         if (!S_ISBLK(st.st_mode))
1244                 return 0;
1245
1246         if (major(st.st_rdev) == LOOP_MAJOR)
1247                 return 0;
1248
1249         snprintf(sys_path, sizeof(sys_path), "/sys/dev/block/%u:%u",
1250                  major(st.st_rdev), minor(st.st_rdev));
1251
1252         snprintf(partition_path, sizeof(partition_path), "%s/partition",
1253                  sys_path);
1254
1255         rc = access(partition_path, F_OK);
1256         if (rc < 0) {
1257                 if (errno == ENOENT)
1258                         goto have_whole_dev;
1259
1260                 if (verbose)
1261                         fprintf(stderr, "warning: cannot access '%s': %s\n",
1262                                 partition_path, strerror(errno));
1263                 rc = errno;
1264                 goto out;
1265         }
1266
1267         snprintf(sys_path, sizeof(sys_path), "/sys/dev/block/%u:%u/..",
1268                  major(st.st_rdev), minor(st.st_rdev));
1269
1270 have_whole_dev:
1271         /* Since we recurse on slave devices we resolve the sys_path to
1272          * avoid path buffer overflows. */
1273         real_sys_path = realpath(sys_path, NULL);
1274         if (real_sys_path == NULL) {
1275                 if (verbose)
1276                         fprintf(stderr,
1277                                 "warning: cannot resolve '%s': %s\n",
1278                                 sys_path, strerror(errno));
1279                 rc = errno;
1280                 goto out;
1281         }
1282
1283         if (major(st.st_rdev) == MD_MAJOR) {
1284                 rc = tune_md_stripe_cache_size(real_sys_path, mop);
1285         } else {
1286                 /* Ignore errors from tune_max_sectors_kb() and
1287                  * tune_scheduler(). The worst that will happen is a block
1288                  * device with an "incorrect" scheduler. */
1289                 tune_max_sectors_kb(real_sys_path, mop);
1290                 tune_block_dev_scheduler(real_sys_path, DEFAULT_SCHEDULER);
1291
1292                 /* If device is multipath device then tune its slave
1293                  * devices. */
1294                 rc = tune_block_dev_slaves(real_sys_path, mop);
1295         }
1296
1297 out:
1298         free(real_sys_path);
1299
1300         return rc;
1301 }
1302
1303 int ldiskfs_tune_lustre(char *dev, struct mount_opts *mop)
1304 {
1305         return tune_block_dev(dev, mop);
1306 }
1307
1308 int ldiskfs_label_lustre(struct mount_opts *mop)
1309 {
1310         char label_cmd[PATH_MAX];
1311         int rc;
1312
1313         snprintf(label_cmd, sizeof(label_cmd),
1314                  TUNE2FS" -f -L '%s' '%s' >/dev/null 2>&1",
1315                  mop->mo_ldd.ldd_svname, mop->mo_source);
1316         rc = run_command(label_cmd, sizeof(label_cmd));
1317
1318         return rc;
1319 }
1320
1321 int ldiskfs_rename_fsname(struct mkfs_opts *mop, const char *oldname)
1322 {
1323         struct mount_opts opts;
1324         struct lustre_disk_data *ldd = &mop->mo_ldd;
1325         char mntpt[] = "/tmp/mntXXXXXX";
1326         char *dev;
1327         int ret;
1328
1329         /* Change the filesystem label. */
1330         opts.mo_ldd = *ldd;
1331         opts.mo_source = mop->mo_device;
1332         ret = ldiskfs_label_lustre(&opts);
1333         if (ret) {
1334                 if (errno != 0)
1335                         ret = errno;
1336                 fprintf(stderr, "Can't change filesystem label: %s\n",
1337                         strerror(ret));
1338                 return ret;
1339         }
1340
1341         /* Mount this device temporarily in order to write these files */
1342         if (mkdtemp(mntpt) == NULL) {
1343                 if (errno != 0)
1344                         ret = errno;
1345                 else
1346                         ret = EINVAL;
1347                 fprintf(stderr, "Can't create temp mount point %s: %s\n",
1348                         mntpt, strerror(ret));
1349                 return ret;
1350         }
1351
1352         if (mop->mo_flags & MO_IS_LOOP)
1353                 dev = mop->mo_loopdev;
1354         else
1355                 dev = mop->mo_device;
1356         ret = mount(dev, mntpt, MT_STR(ldd), 0, ldd->ldd_mount_opts);
1357         if (ret) {
1358                 if (errno != 0)
1359                         ret = errno;
1360                 fprintf(stderr, "Unable to mount %s: %s\n",
1361                         dev, strerror(ret));
1362                 if (ret == ENODEV)
1363                         fprintf(stderr, "Is the %s module available?\n",
1364                                 MT_STR(ldd));
1365                 goto out_rmdir;
1366         }
1367
1368         ret = lustre_rename_fsname(mop, mntpt, oldname);
1369         umount(mntpt);
1370
1371 out_rmdir:
1372         rmdir(mntpt);
1373         return ret;
1374 }
1375
1376 /* Enable quota accounting */
1377 int ldiskfs_enable_quota(struct mkfs_opts *mop)
1378 {
1379         char *dev;
1380         char cmd[512];
1381         int cmdsz = sizeof(cmd), ret;
1382
1383         if (!is_e2fsprogs_feature_supp("-O quota")) {
1384                 fprintf(stderr, "%s: \"-O quota\" is is not supported by "
1385                         "current e2fsprogs\n", progname);
1386                 return EINVAL;
1387         }
1388
1389         dev = mop->mo_device;
1390         if (mop->mo_flags & MO_IS_LOOP)
1391                 dev = mop->mo_loopdev;
1392
1393         /* Quota feature is already enabled? */
1394         if (!backfs)
1395                 ext2fs_open(dev, open_flags, 0, 0, unix_io_manager, &backfs);
1396         if (backfs && ext2fs_has_feature_quota(backfs->super)) {
1397                 vprint("Quota feature is already enabled.\n");
1398                 return 0;
1399         }
1400
1401         /* Turn on quota feature by "tune2fs -O quota" */
1402         snprintf(cmd, cmdsz, "%s -O quota %s", TUNE2FS, dev);
1403         ret = run_command(cmd, cmdsz);
1404         if (ret)
1405                 fprintf(stderr, "command:%s (%d)", cmd, ret);
1406
1407         return ret;
1408 }
1409
1410 int ldiskfs_init(void)
1411 {
1412         /* Required because full path to DEBUGFS is not specified */
1413         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin", 0);
1414
1415         return 0;
1416 }
1417
1418 void ldiskfs_fini(void)
1419 {
1420         if (backfs) {
1421                 ext2fs_close(backfs);
1422                 backfs = NULL;
1423         }
1424 }
1425
1426 #ifndef PLUGIN_DIR
1427 struct module_backfs_ops ldiskfs_ops = {
1428         .init                   = ldiskfs_init,
1429         .fini                   = ldiskfs_fini,
1430         .read_ldd               = ldiskfs_read_ldd,
1431         .write_ldd              = ldiskfs_write_ldd,
1432         .erase_ldd              = ldiskfs_erase_ldd,
1433         .print_ldd_params       = ldiskfs_print_ldd_params,
1434         .is_lustre              = ldiskfs_is_lustre,
1435         .make_lustre            = ldiskfs_make_lustre,
1436         .prepare_lustre         = ldiskfs_prepare_lustre,
1437         .fix_mountopts          = ldiskfs_fix_mountopts,
1438         .tune_lustre            = ldiskfs_tune_lustre,
1439         .label_lustre           = ldiskfs_label_lustre,
1440         .enable_quota           = ldiskfs_enable_quota,
1441         .rename_fsname          = ldiskfs_rename_fsname,
1442 };
1443 #endif /* PLUGIN_DIR */