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