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