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