Whamcloud - gitweb
LU-6142 tests: Fix style issues for chownmany.c
[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 /* keep it less than LL_FID_NAMELEN */
93 #define DUMMY_FILE_NAME_LEN             25
94 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
95
96 static void append_unique(char *buf, char *prefix, char *key, char *val,
97                           size_t maxbuflen);
98 static bool is_e2fsprogs_feature_supp(const char *feature);
99 static void disp_old_e2fsprogs_msg(const char *feature, int make_backfs);
100
101 /*
102  * Concatenate context of the temporary mount point if selinux is enabled
103  */
104 #ifdef HAVE_SELINUX
105 static void append_context_for_mount(char *mntpt, struct mkfs_opts *mop)
106 {
107         security_context_t fcontext;
108
109         if (getfilecon(mntpt, &fcontext) < 0) {
110                 /* Continuing with default behaviour */
111                 fprintf(stderr, "%s: Get file context failed : %s\n",
112                         progname, strerror(errno));
113                 return;
114         }
115
116         if (fcontext != NULL) {
117                 append_unique(mop->mo_ldd.ldd_mount_opts,
118                               ",", "context", fcontext,
119                               sizeof(mop->mo_ldd.ldd_mount_opts));
120                 freecon(fcontext);
121         }
122 }
123 #endif
124
125 /* Determine if a device is a block device (as opposed to a file) */
126 static int is_block(char *devname)
127 {
128         struct stat st;
129         int     ret = 0;
130         char    *devpath;
131
132         ret = cfs_abs_path(devname, &devpath);
133         if (ret != 0) {
134                 fprintf(stderr, "%s: failed to resolve path '%s': %s\n",
135                         progname, devname, strerror(-ret));
136                 return -1;
137         }
138
139         ret = access(devname, F_OK);
140         if (ret != 0) {
141                 if (strncmp(devpath, "/dev/", 5) == 0) {
142                         /* nobody sane wants to create a loopback file under
143                          * /dev. Let's just report the device doesn't exist */
144                         fprintf(stderr, "%s: %s apparently does not exist\n",
145                                 progname, devpath);
146                         ret = -1;
147                         goto out;
148                 }
149                 ret = 0;
150                 goto out;
151         }
152         ret = stat(devpath, &st);
153         if (ret != 0) {
154                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
155                 goto out;
156         }
157         ret = S_ISBLK(st.st_mode);
158 out:
159         free(devpath);
160         return ret;
161 }
162
163 static int is_feature_enabled(const char *feature, const char *devpath)
164 {
165         char cmd[PATH_MAX];
166         FILE *fp;
167         char enabled_features[4096] = "";
168         int ret = 1;
169
170         snprintf(cmd, sizeof(cmd), "%s -c -R features %s 2>&1",
171                  DEBUGFS, devpath);
172
173         /* Using popen() instead of run_command() since debugfs does
174          * not return proper error code if command is not supported */
175         fp = popen(cmd, "r");
176         if (!fp) {
177                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
178                 return 0;
179         }
180
181         ret = fread(enabled_features, 1, sizeof(enabled_features) - 1, fp);
182         enabled_features[ret] = '\0';
183         pclose(fp);
184
185         if (strstr(enabled_features, feature))
186                 return 1;
187         return 0;
188 }
189
190 /* Write the server config files */
191 int ldiskfs_write_ldd(struct mkfs_opts *mop)
192 {
193         char mntpt[] = "/tmp/mntXXXXXX";
194         char filepnm[192];
195         char *dev;
196         FILE *filep;
197         int ret = 0;
198         size_t num;
199
200         /* Mount this device temporarily in order to write these files */
201         if (!mkdtemp(mntpt)) {
202                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
203                         progname, mntpt, strerror(errno));
204                 return errno;
205         }
206
207         /*
208          * Append file context to mount options if SE Linux is enabled
209          */
210         #ifdef HAVE_SELINUX
211         if (is_selinux_enabled() > 0)
212                 append_context_for_mount(mntpt, mop);
213         #endif
214
215         dev = mop->mo_device;
216         if (mop->mo_flags & MO_IS_LOOP)
217                 dev = mop->mo_loopdev;
218
219         /* Multiple mount protection enabled if failover node specified */
220         if (mop->mo_flags & MO_FAILOVER &&
221             !is_feature_enabled("mmp", dev)) {
222                 if (is_e2fsprogs_feature_supp("-O mmp")) {
223                         char *command = filepnm;
224
225                         snprintf(command, sizeof(filepnm),
226                                  TUNE2FS" -O mmp '%s' >/dev/null 2>&1", dev);
227                         ret = run_command(command, sizeof(filepnm));
228                         if (ret)
229                                 fprintf(stderr,
230                                         "%s: Unable to set 'mmp' on %s: %d\n",
231                                         progname, dev, ret);
232                 } else {
233                         disp_old_e2fsprogs_msg("mmp", 1);
234                 }
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 bool 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;
469         int ret;
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                 } else {
481                         ret = fread(supp_features, 1,
482                                     sizeof(supp_features) - 1, fp);
483                         supp_features[ret] = '\0';
484                         pclose(fp);
485                 }
486         }
487
488         if (strstr(supp_features,
489                    strncmp(feature, "-O ", 3) ? feature : feature + 3))
490                 return true;
491
492         if ((fd = mkstemp(imgname)) < 0)
493                 return false;
494
495         close(fd);
496
497         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
498                  MKE2FS, feature, imgname);
499         /* run_command() displays the output of mke2fs when it fails for
500          * some feature, so use system() directly */
501         ret = system(cmd);
502         unlink(imgname);
503
504         return ret == 0;
505 }
506
507 /**
508  * append_unique: append @key or @key=@val pair to @buf only if @key does not
509  *                exists
510  *      @buf: buffer to hold @key or @key=@val
511  *      @prefix: prefix string before @key
512  *      @key: key string
513  *      @val: value string if it's a @key=@val pair
514  */
515 static void append_unique(char *buf, char *prefix, char *key, char *val,
516                           size_t maxbuflen)
517 {
518         char *anchor, *end;
519         int  len;
520
521         if (key == NULL)
522                 return;
523
524         anchor = end = strstr(buf, key);
525         /* try to find exact match string in @buf */
526         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
527                 ++end;
528         len = end - anchor;
529         if (anchor == NULL || strlen(key) != len ||
530                         strncmp(anchor, key, len) != 0) {
531                 if (prefix != NULL)
532                         strscat(buf, prefix, maxbuflen);
533
534                 strscat(buf, key, maxbuflen);
535                 if (val != NULL) {
536                         strscat(buf, "=\"", maxbuflen);
537                         strscat(buf, val, maxbuflen);
538                         strscat(buf, "\"", maxbuflen);
539                 }
540         }
541 }
542
543 static int enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
544                                         size_t maxbuflen, bool user_spec)
545 {
546         unsigned long long blocks = mop->mo_device_kb / mop->mo_blocksize_kb;
547         bool enable_64bit = false;
548
549         /* Enable large block addresses if the LUN is over 2^32 blocks. */
550         if (blocks > 0xffffffffULL && is_e2fsprogs_feature_supp("-O 64bit"))
551                 enable_64bit = true;
552
553         if (IS_OST(&mop->mo_ldd)) {
554                 append_unique(anchor, user_spec ? "," : " -O ",
555                               "extents", NULL, maxbuflen);
556                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
557         } else if (IS_MDT(&mop->mo_ldd)) {
558                 append_unique(anchor, user_spec ? "," : " -O ",
559                               "dirdata", NULL, maxbuflen);
560                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
561                 if (enable_64bit)
562                         append_unique(anchor, ",", "extents", NULL, maxbuflen);
563                 else
564                         append_unique(anchor, ",", "^extents", NULL, maxbuflen);
565         } else {
566                 append_unique(anchor, user_spec ? "," : " -O ",
567                               "uninit_bg", NULL, maxbuflen);
568         }
569
570         /* Multiple mount protection enabled only if failover node specified */
571         if (mop->mo_flags & MO_FAILOVER) {
572                 if (is_e2fsprogs_feature_supp("-O mmp"))
573                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
574                 else
575                         disp_old_e2fsprogs_msg("mmp", 1);
576         }
577
578         /* Allow more than 65000 subdirectories */
579         if (is_e2fsprogs_feature_supp("-O dir_nlink"))
580                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
581
582         /* The following options are only valid for ext4-based ldiskfs.
583          * If --backfstype=ext3 is specified, do not enable them. */
584         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
585                 return 0;
586
587         /* Enable quota by default */
588         if (is_e2fsprogs_feature_supp("-O quota")) {
589                 append_unique(anchor, ",", "quota", NULL, maxbuflen);
590         } else {
591                 fatal();
592                 fprintf(stderr, "\"-O quota\" must be supported by "
593                         "e2fsprogs, please upgrade your e2fsprogs.\n");
594                 return EINVAL;
595         }
596
597         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
598         if (is_e2fsprogs_feature_supp("-O huge_file"))
599                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
600
601         if (enable_64bit)
602                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
603
604         if (blocks >= 0x1000000000 && is_e2fsprogs_feature_supp("-O meta_bg"))
605                 append_unique(anchor, ",", "meta_bg", NULL, maxbuflen);
606
607         if (enable_64bit || strstr(mop->mo_mkfsopts, "meta_bg"))
608                 append_unique(anchor, ",", "^resize_inode", NULL, maxbuflen);
609
610         /* Allow xattrs larger than one block, stored in a separate inode */
611         if (IS_MDT(&mop->mo_ldd) && is_e2fsprogs_feature_supp("-O ea_inode"))
612                 append_unique(anchor, ",", "ea_inode", NULL, maxbuflen);
613
614         /* Cluster inode/block bitmaps and inode table for more efficient IO.
615          * Align the flex groups on a 1MB boundary for better performance. */
616         /* This -O feature needs to go last, since it adds the "-G" option. */
617         if (is_e2fsprogs_feature_supp("-O flex_bg")) {
618                 char tmp_buf[64];
619
620                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
621
622                 if (IS_OST(&mop->mo_ldd) &&
623                     strstr(mop->mo_mkfsopts, "-G") == NULL) {
624                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
625                                  1024 / mop->mo_blocksize_kb);
626                         strscat(anchor, tmp_buf, maxbuflen);
627                 }
628         }
629         /* Don't add any more "-O" options here, see last comment above */
630         return 0;
631 }
632
633 /**
634  * moveopts_to_end: find the option string, move remaining strings to
635  *                  where option string starts, and append the option
636  *                  string at the end
637  *      @start: where the option string starts before the move
638  *      RETURN: where the option string starts after the move
639  */
640 static char *moveopts_to_end(char *start)
641 {
642         size_t len;
643         char save[512];
644         char *end, *idx;
645
646         /* skip whitespace before options */
647         end = start + 2;
648         while (*end == ' ')
649                 ++end;
650
651         /* find end of option characters */
652         while (*end != ' ' && *end != '\0')
653                 ++end;
654
655         len = end - start;
656         if (len >= sizeof(save))
657                 len = sizeof(save) - 1;
658
659         /* save options */
660         strncpy(save, start, len);
661         save[len] = '\0';
662
663         /* move remaining options up front */
664         if (*end)
665                 memmove(start, end, strlen(end));
666         *(start + strlen(end)) = '\0';
667
668         /* append the specified options */
669         if (*(start + strlen(start) - 1) != ' ')
670                 strcat(start, " ");
671         idx = start + strlen(start);
672         strcat(start, save);
673
674         return idx;
675 }
676
677 /* Build fs according to type */
678 int ldiskfs_make_lustre(struct mkfs_opts *mop)
679 {
680         char mkfs_cmd[PATH_MAX];
681         char buf[64];
682         char *start;
683         char *dev;
684         int ret = 0, ext_opts = 0;
685         bool enable_64bit = false;
686         long inode_size = 0;
687         size_t maxbuflen;
688
689         mop->mo_blocksize_kb = 4;
690
691         start = strstr(mop->mo_mkfsopts, "-b");
692         if (start) {
693                 char *end = NULL;
694                 long blocksize;
695
696                 blocksize = strtol(start + 2, &end, 0);
697                 if (end && (*end == 'k' || *end == 'K'))
698                         blocksize *= 1024;
699                 /* EXT4_MIN_BLOCK_SIZE || EXT4_MAX_BLOCK_SIZE */
700                 if (blocksize < 1024 || blocksize > 65536) {
701                         fprintf(stderr,
702                                 "%s: blocksize %lu not in 1024-65536 bytes, normally 4096 bytes\n",
703                                 progname, blocksize);
704                         return EINVAL;
705                 }
706
707                 if ((blocksize & (blocksize - 1)) != 0) {
708                         fprintf(stderr,
709                                 "%s: blocksize %lu not a power-of-two value\n",
710                                 progname, blocksize);
711                         return EINVAL;
712                 }
713                 mop->mo_blocksize_kb = blocksize >> 10;
714         }
715
716         if (!(mop->mo_flags & MO_IS_LOOP)) {
717                 __u64 device_kb = get_device_size(mop->mo_device);
718
719                 if (device_kb == 0)
720                         return ENODEV;
721
722                 /* Compare to real size */
723                 if (mop->mo_device_kb == 0 || device_kb < mop->mo_device_kb)
724                         mop->mo_device_kb = device_kb;
725         }
726
727         if (mop->mo_device_kb != 0) {
728                 __u64 block_count;
729
730                 if (mop->mo_device_kb < 32384) {
731                         fprintf(stderr, "%s: size of filesystem must be larger "
732                                 "than 32MB, but is set to %lldKB\n",
733                                 progname, (long long)mop->mo_device_kb);
734                         return EINVAL;
735                 }
736                 block_count = mop->mo_device_kb / mop->mo_blocksize_kb;
737                 if (block_count > 0xffffffffULL) {
738                         /* If the LUN size is just over 2^32 blocks, limit the
739                          * filesystem size to 2^32-1 blocks to avoid problems
740                          * with ldiskfs/mkfs not handling this well. b=22906
741                          */
742                         if (block_count < 0x100002000ULL)
743                                 mop->mo_device_kb =
744                                         0xffffffffULL * mop->mo_blocksize_kb;
745                         else
746                                 enable_64bit = true;
747                 }
748         }
749
750         if ((mop->mo_ldd.ldd_mount_type != LDD_MT_EXT3) &&
751             (mop->mo_ldd.ldd_mount_type != LDD_MT_LDISKFS) &&
752             (mop->mo_ldd.ldd_mount_type != LDD_MT_LDISKFS2)) {
753                 fprintf(stderr, "%s: unsupported fs type: %d (%s)\n",
754                         progname, mop->mo_ldd.ldd_mount_type,
755                         MT_STR(&mop->mo_ldd));
756
757                 return EINVAL;
758         }
759
760         /* Journal size in MB */
761         if (strstr(mop->mo_mkfsopts, "-J") == NULL &&
762             mop->mo_device_kb > 1024 * 1024) {
763                 /* Choose our own default journal size */
764                 long journal_mb = 0, max_mb;
765
766                 /* cap journal size at 4GB for MDT, leave at 1GB for OSTs */
767                 if (IS_MDT(&mop->mo_ldd))
768                         max_mb = 4096;
769                 else if (IS_OST(&mop->mo_ldd))
770                         max_mb = 1024;
771                 else /* Use mke2fs default size for MGS */
772                         max_mb = 0;
773
774                 /* Use at most 4% of device for journal */
775                 journal_mb = mop->mo_device_kb * 4 / (1024 * 100);
776                 if (journal_mb > max_mb)
777                         journal_mb = max_mb;
778
779                 if (journal_mb) {
780                         snprintf(buf, sizeof(buf), " -J size=%ld", journal_mb);
781                         strscat(mop->mo_mkfsopts, buf,
782                                 sizeof(mop->mo_mkfsopts));
783                 }
784         }
785
786         /*
787          * The inode size is constituted by following elements
788          * (assuming all files are in composite layout and has
789          * 3 components):
790          *
791          *   ldiskfs inode size: 160
792          *   MDT extended attributes size, including:
793          *      ext4_xattr_header: 32
794          *      LOV EA size: 32(lov_comp_md_v1) +
795          *                   3 * 40(lov_comp_md_entry_v1) +
796          *                   3 * 32(lov_mds_md) +
797          *                   stripes * 24(lov_ost_data) +
798          *                   16(xattr_entry) + 4("lov")
799          *      LMA EA size: 24(lustre_mdt_attrs) +
800          *                   16(xattr_entry) + 4("lma")
801          *      SOM EA size: 24(lustre_som_attrs) +
802          *                   16(xattr_entry) + 4("som")
803          *      link EA size: 24(link_ea_header) + 18(link_ea_entry) +
804          *                    16(filename) + 16(xattr_entry) + 4("link")
805          *   and some margin for 4-byte alignment, ACLs and other EAs.
806          *
807          * If we say the average filename length is about 32 bytes,
808          * the calculation looks like:
809          * 160 + 32 + (32+3*(40+32)+24*stripes+20) + (24+20) + (24+20) +
810          *  (24+20) + (~42+16+20) + other <= 512*2^m, {m=0,1,2,3}
811          */
812         if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
813                 if (IS_MDT(&mop->mo_ldd)) {
814                         if (mop->mo_stripe_count > 59)
815                                 inode_size = 512; /* bz 7241 */
816                         /* see also "-i" below for EA blocks */
817                         else if (mop->mo_stripe_count > 16)
818                                 inode_size = 2048;
819                         else
820                                 inode_size = 1024;
821                 } else if (IS_OST(&mop->mo_ldd)) {
822                         /* We store MDS FID and necessary composite
823                          * layout information in the OST object EA:
824                          *   ldiskfs inode size: 160
825                          *   OST extended attributes size, including:
826                          *      ext4_xattr_header: 32
827                          *      LMA EA size: 24(lustre_mdt_attrs) +
828                          *                   16(xattr_entry) + 4("lma")
829                          *      FID EA size: 52(filter_fid) +
830                          *                   16(xattr_entry) + 4("fid")
831                          * 160 + 32 + (24+20) + (52+20) = 308
832                          */
833                         inode_size = 512;
834                 }
835
836                 if (inode_size > 0) {
837                         snprintf(buf, sizeof(buf), " -I %ld", inode_size);
838                         strscat(mop->mo_mkfsopts, buf,
839                                 sizeof(mop->mo_mkfsopts));
840                 }
841         }
842
843         /* Bytes_per_inode: disk size / num inodes */
844         if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
845             strstr(mop->mo_mkfsopts, "-N") == NULL) {
846                 long bytes_per_inode = 0;
847
848                 /* Allocate more inodes on MDT devices.  There is
849                  * no data stored on the MDT, and very little extra
850                  * metadata beyond the inode.  It could go down as
851                  * low as 1024 bytes, but this is conservative.
852                  * Account for external EA blocks for wide striping.
853                  */
854                 if (IS_MDT(&mop->mo_ldd)) {
855                         bytes_per_inode = inode_size + 1536;
856
857                         if (mop->mo_stripe_count > 59) {
858                                 int extra = mop->mo_stripe_count * 24;
859
860                                 extra = ((extra - 1) | 4095) + 1;
861                                 bytes_per_inode += extra;
862                         }
863                 }
864
865                 /* Allocate fewer inodes on large OST devices.  Most
866                  * filesystems can be much more aggressive than even
867                  * this, but it is impossible to know in advance.
868                  */
869                 if (IS_OST(&mop->mo_ldd)) {
870                         /* OST > 16TB assume average file size 1MB */
871                         if (mop->mo_device_kb > (16ULL << 30))
872                                 bytes_per_inode = 1024 * 1024;
873                         /* OST > 4TB assume average file size 512kB */
874                         else if (mop->mo_device_kb > (4ULL << 30))
875                                 bytes_per_inode = 512 * 1024;
876                         /* OST > 1TB assume average file size 256kB */
877                         else if (mop->mo_device_kb > (1ULL << 30))
878                                 bytes_per_inode = 256 * 1024;
879                         /* OST > 10GB assume average file size 64kB,
880                          * plus a bit so that inodes will fit into a
881                          * 256x flex_bg without overflowing.
882                          */
883                         else if (mop->mo_device_kb > (10ULL << 20))
884                                 bytes_per_inode = 69905;
885                 }
886
887                 if (bytes_per_inode > 0) {
888                         snprintf(buf, sizeof(buf), " -i %ld", bytes_per_inode);
889                         strscat(mop->mo_mkfsopts, buf,
890                                 sizeof(mop->mo_mkfsopts));
891                         mop->mo_inode_size = bytes_per_inode;
892                 }
893         }
894
895         if (verbose < 2)
896                 strscat(mop->mo_mkfsopts, " -q", sizeof(mop->mo_mkfsopts));
897
898         /* start handle -O mkfs options */
899         start = strstr(mop->mo_mkfsopts, "-O");
900         if (start) {
901                 if (strstr(start + 2, "-O") != NULL) {
902                         fprintf(stderr,
903                                 "%s: don't specify multiple -O options\n",
904                                 progname);
905                         return EINVAL;
906                 }
907                 start = moveopts_to_end(start);
908                 maxbuflen = sizeof(mop->mo_mkfsopts) -
909                         (start - mop->mo_mkfsopts) - strlen(start);
910                 ret = enable_default_ext4_features(mop, start, maxbuflen, 1);
911         } else {
912                 start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
913                 maxbuflen = sizeof(mop->mo_mkfsopts) - strlen(mop->mo_mkfsopts);
914                 ret = enable_default_ext4_features(mop, start, maxbuflen, 0);
915         }
916         if (ret)
917                 return ret;
918         /* end handle -O mkfs options */
919
920         /* start handle -E mkfs options */
921         start = strstr(mop->mo_mkfsopts, "-E");
922         if (start) {
923                 if (strstr(start + 2, "-E") != NULL) {
924                         fprintf(stderr,
925                                 "%s: don't specify multiple -E options\n",
926                                 progname);
927                         return EINVAL;
928                 }
929                 start = moveopts_to_end(start);
930                 maxbuflen = sizeof(mop->mo_mkfsopts) -
931                         (start - mop->mo_mkfsopts) - strlen(start);
932                 ext_opts = 1;
933         } else {
934                 start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
935                 maxbuflen = sizeof(mop->mo_mkfsopts) - strlen(mop->mo_mkfsopts);
936         }
937
938         /* In order to align the filesystem metadata on 1MB boundaries,
939          * give a resize value that will reserve a power-of-two group
940          * descriptor blocks, but leave one block for the superblock.
941          * Only useful for filesystems with < 2^32 blocks due to resize
942          * limitations.
943          */
944         if (!enable_64bit && strstr(mop->mo_mkfsopts, "meta_bg") == NULL &&
945             IS_OST(&mop->mo_ldd) && mop->mo_device_kb > 100 * 1024) {
946                 unsigned int group_blocks = mop->mo_blocksize_kb * 8192;
947                 unsigned int desc_per_block = mop->mo_blocksize_kb * 1024 / 32;
948                 unsigned int resize_blks;
949
950                 resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
951                 snprintf(buf, sizeof(buf), "%u", resize_blks);
952                 append_unique(start, ext_opts ? "," : " -E ",
953                               "resize", buf, maxbuflen);
954                 ext_opts = 1;
955         }
956
957         /* Avoid zeroing out the full journal - speeds up mkfs */
958         if (is_e2fsprogs_feature_supp("-E lazy_journal_init"))
959                 append_unique(start, ext_opts ? "," : " -E ",
960                               "lazy_journal_init", NULL, maxbuflen);
961         /* end handle -E mkfs options */
962
963         /* Allow reformat of full devices (as opposed to partitions).
964          * We already checked for mounted dev.
965          */
966         strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
967
968         snprintf(mkfs_cmd, sizeof(mkfs_cmd), "%s -j -b %d -L %s ", MKE2FS,
969                  mop->mo_blocksize_kb * 1024, mop->mo_ldd.ldd_svname);
970
971         /* For loop device format the dev, not the filename */
972         dev = mop->mo_device;
973         if (mop->mo_flags & MO_IS_LOOP)
974                 dev = mop->mo_loopdev;
975
976         vprint("formatting backing filesystem %s on %s\n",
977                MT_STR(&mop->mo_ldd), dev);
978         vprint("\ttarget name   %s\n", mop->mo_ldd.ldd_svname);
979         vprint("\tkilobytes     %llu\n", mop->mo_device_kb);
980         vprint("\toptions       %s\n", mop->mo_mkfsopts);
981
982         /* mkfs_cmd's trailing space is important! */
983         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
984         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
985         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
986         if (mop->mo_device_kb != 0) {
987                 snprintf(buf, sizeof(buf), " %lluk",
988                          (unsigned long long)mop->mo_device_kb);
989                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
990         }
991
992         vprint("mkfs_cmd = %s\n", mkfs_cmd);
993         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
994         if (ret) {
995                 fatal();
996                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
997         }
998         return ret;
999 }
1000
1001 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
1002                            char *wanted_mountopts, size_t len)
1003 {
1004         struct lustre_disk_data *ldd = &mop->mo_ldd;
1005         int ret;
1006
1007         /* Set MO_IS_LOOP to indicate a loopback device is needed */
1008         ret = is_block(mop->mo_device);
1009         if (ret < 0) {
1010                 return errno;
1011         } else if (ret == 0) {
1012                 mop->mo_flags |= MO_IS_LOOP;
1013         }
1014
1015         if (IS_MDT(ldd) || IS_MGS(ldd))
1016                 strscat(wanted_mountopts, ",user_xattr", len);
1017
1018         return 0;
1019 }
1020
1021 int ldiskfs_fix_mountopts(struct mkfs_opts *mop, char *mountopts, size_t len)
1022 {
1023         if (strstr(mountopts, "errors=") == NULL)
1024                 strscat(mountopts, ",errors=remount-ro", len);
1025
1026         return 0;
1027 }
1028
1029 static int read_file(const char *path, char *buf, int size)
1030 {
1031         FILE *fd;
1032
1033         fd = fopen(path, "r");
1034         if (fd == NULL)
1035                 return errno;
1036
1037         if (fgets(buf, size, fd) == NULL) {
1038                 fprintf(stderr, "reading from %s: %s", path, strerror(errno));
1039                 fclose(fd);
1040                 return 1;
1041         }
1042         fclose(fd);
1043
1044         /* strip trailing newline */
1045         size = strlen(buf);
1046         if (buf[size - 1] == '\n')
1047                 buf[size - 1] = '\0';
1048
1049         return 0;
1050 }
1051
1052 static int write_file(const char *path, const char *buf)
1053 {
1054         int fd, rc;
1055
1056         fd = open(path, O_WRONLY);
1057         if (fd < 0)
1058                 return errno;
1059
1060         rc = write(fd, buf, strlen(buf));
1061         close(fd);
1062
1063         return rc < 0 ? errno : 0;
1064 }
1065
1066 static int tune_md_stripe_cache_size(const char *sys_path,
1067                                      struct mount_opts *mop)
1068 {
1069         char path[PATH_MAX];
1070         unsigned long old_stripe_cache_size;
1071         unsigned long new_stripe_cache_size;
1072         char buf[3 * sizeof(old_stripe_cache_size) + 2];
1073         int rc;
1074
1075         if (mop->mo_md_stripe_cache_size <= 0)
1076                 return 0;
1077
1078         new_stripe_cache_size = mop->mo_md_stripe_cache_size;
1079
1080         snprintf(path, sizeof(path), "%s/%s", sys_path, STRIPE_CACHE_SIZE);
1081         rc = read_file(path, buf, sizeof(buf));
1082         if (rc != 0) {
1083                 if (verbose)
1084                         fprintf(stderr, "warning: cannot read '%s': %s\n",
1085                                 path, strerror(errno));
1086                 return rc;
1087         }
1088
1089         old_stripe_cache_size = strtoul(buf, NULL, 0);
1090         if (old_stripe_cache_size == 0 || old_stripe_cache_size == ULONG_MAX)
1091                 return EINVAL;
1092
1093         if (new_stripe_cache_size <= old_stripe_cache_size)
1094                 return 0;
1095
1096         snprintf(buf, sizeof(buf), "%lu", new_stripe_cache_size);
1097         rc = write_file(path, buf);
1098         if (rc != 0) {
1099                 if (verbose)
1100                         fprintf(stderr, "warning: cannot write '%s': %s\n",
1101                                 path, strerror(errno));
1102                 return rc;
1103         }
1104
1105         return 0;
1106 }
1107
1108 static int tune_max_sectors_kb(const char *sys_path, struct mount_opts *mop)
1109 {
1110         char path[PATH_MAX];
1111         unsigned long max_hw_sectors_kb;
1112         unsigned long old_max_sectors_kb;
1113         unsigned long new_max_sectors_kb;
1114         char buf[3 * sizeof(old_max_sectors_kb) + 2];
1115         int rc;
1116
1117         if (mop->mo_max_sectors_kb >= 0) {
1118                 new_max_sectors_kb = mop->mo_max_sectors_kb;
1119                 goto have_new_max_sectors_kb;
1120         }
1121
1122         snprintf(path, sizeof(path), "%s/%s", sys_path, MAX_HW_SECTORS_KB_PATH);
1123         rc = read_file(path, buf, sizeof(buf));
1124         if (rc != 0) {
1125                 /* No MAX_HW_SECTORS_KB_PATH isn't necessary an
1126                  * error for some devices. */
1127                 return 0;
1128         }
1129
1130         max_hw_sectors_kb = strtoul(buf, NULL, 0);
1131         if (max_hw_sectors_kb == 0 || max_hw_sectors_kb == ULLONG_MAX) {
1132                 /* No digits at all or something weird. */
1133                 return 0;
1134         }
1135
1136         new_max_sectors_kb = max_hw_sectors_kb;
1137
1138         /* Don't increase IO request size limit past 16MB.  It is
1139          * about PTLRPC_MAX_BRW_SIZE, but that isn't in a public
1140          * header.  Note that even though the block layer allows
1141          * larger values, setting max_sectors_kb = 32768 causes
1142          * crashes (LU-6974). */
1143         if (new_max_sectors_kb > 16 * 1024)
1144                 new_max_sectors_kb = 16 * 1024;
1145
1146 have_new_max_sectors_kb:
1147         snprintf(path, sizeof(path), "%s/%s", sys_path, MAX_SECTORS_KB_PATH);
1148         rc = read_file(path, buf, sizeof(buf));
1149         if (rc != 0) {
1150                 /* No MAX_SECTORS_KB_PATH isn't necessary an error for
1151                  * some devices. */
1152                 return 0;
1153         }
1154
1155         old_max_sectors_kb = strtoul(buf, NULL, 0);
1156         if (old_max_sectors_kb == 0 || old_max_sectors_kb == ULLONG_MAX) {
1157                 /* No digits at all or something weird. */
1158                 return 0;
1159         }
1160
1161         if (new_max_sectors_kb <= old_max_sectors_kb)
1162                 return 0;
1163
1164         snprintf(buf, sizeof(buf), "%lu", new_max_sectors_kb);
1165         rc = write_file(path, buf);
1166         if (rc != 0) {
1167                 if (verbose)
1168                         fprintf(stderr, "warning: cannot write '%s': %s\n",
1169                                 path, strerror(errno));
1170                 return rc;
1171         }
1172
1173         fprintf(stderr, "%s: increased '%s' from %lu to %lu\n",
1174                 progname, path, old_max_sectors_kb, new_max_sectors_kb);
1175
1176         return 0;
1177 }
1178
1179 static int tune_block_dev_scheduler(const char *sys_path, const char *new_sched)
1180 {
1181         char path[PATH_MAX];
1182         char buf[PATH_MAX];
1183         char *s, *e;
1184         char *old_sched;
1185         int rc;
1186
1187         /* Before setting the scheduler, we need to check to see if
1188          * it's already set to "noop". If it is then we don't want to
1189          * override that setting. If it's set to anything other than
1190          * "noop" then set the scheduler to what has been passed
1191          * in. */
1192
1193         snprintf(path, sizeof(path), "%s/%s", sys_path, SCHEDULER_PATH);
1194         rc = read_file(path, buf, sizeof(buf));
1195         if (rc != 0) {
1196                 if (verbose)
1197                         fprintf(stderr, "%s: cannot read '%s': %s\n",
1198                                 progname, path, strerror(errno));
1199
1200                 return rc;
1201         }
1202
1203         /* The expected format of buf: noop anticipatory deadline [cfq] */
1204         s = strchr(buf, '[');
1205         e = strchr(buf, ']');
1206
1207         /* If the format is not what we expect then be safe and error out. */
1208         if (s == NULL || e == NULL || !(s < e)) {
1209                 if (verbose)
1210                         fprintf(stderr,
1211                                 "%s: cannot parse scheduler options for '%s'\n",
1212                                 progname, path);
1213
1214                 return EINVAL;
1215         }
1216
1217         old_sched = s + 1;
1218         *e = '\0';
1219
1220         if (strcmp(old_sched, "noop") == 0 ||
1221             strcmp(old_sched, "deadline") == 0 ||
1222             strcmp(old_sched, "mq-deadline") == 0 ||
1223             strstr(old_sched, new_sched) == 0)
1224                 return 0;
1225
1226         rc = write_file(path, new_sched);
1227         if (rc != 0) {
1228                 if (verbose)
1229                         fprintf(stderr,
1230                                 "%s: cannot set scheduler on '%s': %s\n",
1231                                 progname, path, strerror(errno));
1232                 return rc;
1233         }
1234
1235         fprintf(stderr, "%s: changed scheduler of '%s' from %s to %s\n",
1236                 progname, path, old_sched, new_sched);
1237
1238         return 0;
1239 }
1240
1241 static int tune_block_dev(const char *src, struct mount_opts *mop);
1242
1243 static int tune_block_dev_slaves(const char *sys_path, struct mount_opts *mop)
1244 {
1245         char slaves_path[PATH_MAX];
1246         DIR *slaves_dir;
1247         struct dirent *d;
1248         int rc = 0;
1249
1250         snprintf(slaves_path, sizeof(slaves_path), "%s/slaves", sys_path);
1251         slaves_dir = opendir(slaves_path);
1252         if (slaves_dir == NULL) {
1253                 if (errno == ENOENT)
1254                         return 0;
1255
1256                 return errno;
1257         }
1258
1259         while ((d = readdir(slaves_dir)) != NULL) {
1260                 char path[PATH_MAX * 2];
1261                 int rc2;
1262
1263                 if (d->d_type != DT_LNK)
1264                         continue;
1265
1266                 snprintf(path, sizeof(path), "/dev/%s", d->d_name);
1267                 rc2 = tune_block_dev(path, mop);
1268                 if (rc2 != 0)
1269                         rc = rc2;
1270         }
1271
1272         closedir(slaves_dir);
1273
1274         return rc;
1275 }
1276
1277 /* This is to tune the kernel for good SCSI performance.
1278  * For that we set the value of /sys/block/{dev}/queue/max_sectors_kb
1279  * to the value of /sys/block/{dev}/queue/max_hw_sectors_kb */
1280 static int tune_block_dev(const char *src, struct mount_opts *mop)
1281 {
1282         struct stat st;
1283         char sys_path[PATH_MAX];
1284         char partition_path[PATH_MAX + sizeof("partition")];
1285         char *real_sys_path = NULL;
1286         int rc;
1287
1288         /*
1289          * Don't apply block device tuning for MDT or MGT devices,
1290          * since we don't need huge IO sizes to get good performance
1291          */
1292         if (!IS_OST(&mop->mo_ldd))
1293                 return 0;
1294
1295         if (src == NULL)
1296                 return EINVAL;
1297
1298         rc = stat(src, &st);
1299         if (rc < 0) {
1300                 if (verbose)
1301                         fprintf(stderr, "warning: cannot stat '%s': %s\n",
1302                                 src, strerror(errno));
1303                 return errno;
1304         }
1305
1306         if (!S_ISBLK(st.st_mode))
1307                 return 0;
1308
1309         if (major(st.st_rdev) == LOOP_MAJOR)
1310                 return 0;
1311
1312         snprintf(sys_path, sizeof(sys_path), "/sys/dev/block/%u:%u",
1313                  major(st.st_rdev), minor(st.st_rdev));
1314
1315         snprintf(partition_path, sizeof(partition_path), "%s/partition",
1316                  sys_path);
1317
1318         rc = access(partition_path, F_OK);
1319         if (rc < 0) {
1320                 if (errno == ENOENT)
1321                         goto have_whole_dev;
1322
1323                 if (verbose)
1324                         fprintf(stderr, "warning: cannot access '%s': %s\n",
1325                                 partition_path, strerror(errno));
1326                 rc = errno;
1327                 goto out;
1328         }
1329
1330         snprintf(sys_path, sizeof(sys_path), "/sys/dev/block/%u:%u/..",
1331                  major(st.st_rdev), minor(st.st_rdev));
1332
1333 have_whole_dev:
1334         /* Since we recurse on slave devices we resolve the sys_path to
1335          * avoid path buffer overflows. */
1336         real_sys_path = realpath(sys_path, NULL);
1337         if (real_sys_path == NULL) {
1338                 if (verbose)
1339                         fprintf(stderr,
1340                                 "warning: cannot resolve '%s': %s\n",
1341                                 sys_path, strerror(errno));
1342                 rc = errno;
1343                 goto out;
1344         }
1345
1346         if (major(st.st_rdev) == MD_MAJOR) {
1347                 rc = tune_md_stripe_cache_size(real_sys_path, mop);
1348         } else {
1349                 /* Ignore errors from tune_max_sectors_kb() and
1350                  * tune_scheduler(). The worst that will happen is a block
1351                  * device with an "incorrect" scheduler. */
1352                 tune_max_sectors_kb(real_sys_path, mop);
1353                 tune_block_dev_scheduler(real_sys_path, DEFAULT_SCHEDULER);
1354
1355                 /* If device is multipath device then tune its slave
1356                  * devices. */
1357                 rc = tune_block_dev_slaves(real_sys_path, mop);
1358         }
1359
1360 out:
1361         free(real_sys_path);
1362
1363         return rc;
1364 }
1365
1366 int ldiskfs_tune_lustre(char *dev, struct mount_opts *mop)
1367 {
1368         return tune_block_dev(dev, mop);
1369 }
1370
1371 int ldiskfs_label_lustre(struct mount_opts *mop)
1372 {
1373         char label_cmd[PATH_MAX];
1374         int rc;
1375
1376         snprintf(label_cmd, sizeof(label_cmd),
1377                  TUNE2FS" -f -L '%s' '%s' >/dev/null 2>&1",
1378                  mop->mo_ldd.ldd_svname, mop->mo_source);
1379         rc = run_command(label_cmd, sizeof(label_cmd));
1380
1381         return rc;
1382 }
1383
1384 int ldiskfs_rename_fsname(struct mkfs_opts *mop, const char *oldname)
1385 {
1386         struct mount_opts opts;
1387         struct lustre_disk_data *ldd = &mop->mo_ldd;
1388         char mntpt[] = "/tmp/mntXXXXXX";
1389         char *dev;
1390         int ret;
1391
1392         /* Change the filesystem label. */
1393         opts.mo_ldd = *ldd;
1394         opts.mo_source = mop->mo_device;
1395         ret = ldiskfs_label_lustre(&opts);
1396         if (ret) {
1397                 if (errno != 0)
1398                         ret = errno;
1399                 fprintf(stderr, "Can't change filesystem label: %s\n",
1400                         strerror(ret));
1401                 return ret;
1402         }
1403
1404         /* Mount this device temporarily in order to write these files */
1405         if (mkdtemp(mntpt) == NULL) {
1406                 if (errno != 0)
1407                         ret = errno;
1408                 else
1409                         ret = EINVAL;
1410                 fprintf(stderr, "Can't create temp mount point %s: %s\n",
1411                         mntpt, strerror(ret));
1412                 return ret;
1413         }
1414
1415 #ifdef HAVE_SELINUX
1416         /*
1417          * Append file context to mount options if SE Linux is enabled
1418          */
1419         if (is_selinux_enabled() > 0)
1420                 append_context_for_mount(mntpt, mop);
1421 #endif
1422
1423         if (mop->mo_flags & MO_IS_LOOP)
1424                 dev = mop->mo_loopdev;
1425         else
1426                 dev = mop->mo_device;
1427         ret = mount(dev, mntpt, MT_STR(ldd), 0, ldd->ldd_mount_opts);
1428         if (ret) {
1429                 if (errno != 0)
1430                         ret = errno;
1431                 fprintf(stderr, "Unable to mount %s: %s\n",
1432                         dev, strerror(ret));
1433                 if (ret == ENODEV)
1434                         fprintf(stderr, "Is the %s module available?\n",
1435                                 MT_STR(ldd));
1436                 goto out_rmdir;
1437         }
1438
1439         ret = lustre_rename_fsname(mop, mntpt, oldname);
1440         umount(mntpt);
1441
1442 out_rmdir:
1443         rmdir(mntpt);
1444         return ret;
1445 }
1446
1447 /* Enable quota accounting */
1448 int ldiskfs_enable_quota(struct mkfs_opts *mop)
1449 {
1450         char *dev;
1451         char cmd[512];
1452         int cmdsz = sizeof(cmd), ret;
1453
1454         if (!is_e2fsprogs_feature_supp("-O quota")) {
1455                 fprintf(stderr, "%s: \"-O quota\" is is not supported by "
1456                         "current e2fsprogs\n", progname);
1457                 return EINVAL;
1458         }
1459
1460         dev = mop->mo_device;
1461         if (mop->mo_flags & MO_IS_LOOP)
1462                 dev = mop->mo_loopdev;
1463
1464         /* Quota feature is already enabled? */
1465         if (is_feature_enabled("quota", dev)) {
1466                 vprint("Quota feature is already enabled.\n");
1467                 return 0;
1468         }
1469
1470         /* Turn on quota feature by "tune2fs -O quota" */
1471         snprintf(cmd, cmdsz, "%s -O quota %s", TUNE2FS, dev);
1472         ret = run_command(cmd, cmdsz);
1473         if (ret)
1474                 fprintf(stderr, "command:%s (%d)", cmd, ret);
1475
1476         return ret;
1477 }
1478
1479 int ldiskfs_init(void)
1480 {
1481         /* Required because full path to DEBUGFS is not specified */
1482         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin", 0);
1483
1484         return 0;
1485 }
1486
1487 void ldiskfs_fini(void)
1488 {
1489         return;
1490 }
1491
1492 #ifndef PLUGIN_DIR
1493 struct module_backfs_ops ldiskfs_ops = {
1494         .init                   = ldiskfs_init,
1495         .fini                   = ldiskfs_fini,
1496         .read_ldd               = ldiskfs_read_ldd,
1497         .write_ldd              = ldiskfs_write_ldd,
1498         .erase_ldd              = ldiskfs_erase_ldd,
1499         .print_ldd_params       = ldiskfs_print_ldd_params,
1500         .is_lustre              = ldiskfs_is_lustre,
1501         .make_lustre            = ldiskfs_make_lustre,
1502         .prepare_lustre         = ldiskfs_prepare_lustre,
1503         .fix_mountopts          = ldiskfs_fix_mountopts,
1504         .tune_lustre            = ldiskfs_tune_lustre,
1505         .label_lustre           = ldiskfs_label_lustre,
1506         .enable_quota           = ldiskfs_enable_quota,
1507         .rename_fsname          = ldiskfs_rename_fsname,
1508 };
1509 #endif /* PLUGIN_DIR */