Whamcloud - gitweb
LU-1581 utils: label methods
[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) 2011, Whamcloud, Inc.
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 <stdlib.h>
51 #include <stdio.h>
52 #include <unistd.h>
53 #include <fcntl.h>
54 #include <stdarg.h>
55 #include <mntent.h>
56 #include <glob.h>
57
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <sys/mount.h>
61 #include <sys/utsname.h>
62
63 #include <string.h>
64 #include <getopt.h>
65 #include <limits.h>
66 #include <ctype.h>
67
68 #ifdef __linux__
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 #endif
77 #include <lustre_disk.h>
78 #include <lustre_param.h>
79 #include <lnet/lnetctl.h>
80 #include <lustre_ver.h>
81 #include "mount_utils.h"
82
83 #define MAX_HW_SECTORS_KB_PATH  "queue/max_hw_sectors_kb"
84 #define MAX_SECTORS_KB_PATH     "queue/max_sectors_kb"
85 #define STRIPE_CACHE_SIZE       "md/stripe_cache_size"
86
87 extern char *progname;
88
89 #define L_BLOCK_SIZE 4096
90 /* keep it less than LL_FID_NAMELEN */
91 #define DUMMY_FILE_NAME_LEN             25
92 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
93
94 /* Write the server config files */
95 int ldiskfs_write_ldd(struct mkfs_opts *mop)
96 {
97         char mntpt[] = "/tmp/mntXXXXXX";
98         char filepnm[128];
99         char *dev;
100         FILE *filep;
101         int ret = 0;
102         size_t num;
103
104         /* Mount this device temporarily in order to write these files */
105         if (!mkdtemp(mntpt)) {
106                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
107                         progname, mntpt, strerror(errno));
108                 return errno;
109         }
110
111         dev = mop->mo_device;
112         if (mop->mo_flags & MO_IS_LOOP)
113                 dev = mop->mo_loopdev;
114
115         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
116                     mop->mo_ldd.ldd_mount_opts);
117         if (ret) {
118                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
119                         progname, dev, strerror(errno));
120                 ret = errno;
121                 if (errno == ENODEV) {
122                         fprintf(stderr, "Is the %s module available?\n",
123                                 MT_STR(&mop->mo_ldd));
124                 }
125                 goto out_rmdir;
126         }
127
128         /* Set up initial directories */
129         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
130         ret = mkdir(filepnm, 0777);
131         if ((ret != 0) && (errno != EEXIST)) {
132                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
133                         progname, filepnm, strerror(errno));
134                 goto out_umnt;
135         } else if (errno == EEXIST) {
136                 ret = 0;
137         }
138
139         /* Save the persistent mount data into a file. Lustre must pre-read
140            this file to get the real mount options. */
141         vprint("Writing %s\n", MOUNT_DATA_FILE);
142         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
143         filep = fopen(filepnm, "w");
144         if (!filep) {
145                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
146                         progname, filepnm, strerror(errno));
147                 goto out_umnt;
148         }
149         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
150         if (num < 1 && ferror(filep)) {
151                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
152                         progname, filepnm, strerror(errno));
153                 goto out_umnt;
154         }
155         fclose(filep);
156
157 out_umnt:
158         umount(mntpt);
159 out_rmdir:
160         rmdir(mntpt);
161         return ret;
162 }
163
164 int ldiskfs_read_ldd(char *dev, struct lustre_disk_data *mo_ldd)
165 {
166         char tmpdir[] = "/tmp/dirXXXXXX";
167         char cmd[PATH_MAX];
168         char filepnm[128];
169         FILE *filep;
170         int ret = 0;
171         int cmdsz = sizeof(cmd);
172
173         /* Make a temporary directory to hold Lustre data files. */
174         if (!mkdtemp(tmpdir)) {
175                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
176                         progname, tmpdir, strerror(errno));
177                 return errno;
178         }
179
180         /* TODO: it's worth observing the get_mountdata() function that is
181            in mount_utils.c for getting the mountdata out of the
182            filesystem */
183
184         /* Construct debugfs command line. */
185         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
186                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
187
188         ret = run_command(cmd, cmdsz);
189         if (ret)
190                 verrprint("%s: Unable to dump %s dir (%d)\n",
191                           progname, MOUNT_CONFIGS_DIR, ret);
192
193         sprintf(filepnm, "%s/mountdata", tmpdir);
194         filep = fopen(filepnm, "r");
195         if (filep) {
196                 size_t num_read;
197                 vprint("Reading %s\n", MOUNT_DATA_FILE);
198                 num_read = fread(mo_ldd, sizeof(*mo_ldd), 1, filep);
199                 if (num_read < 1 && ferror(filep)) {
200                         fprintf(stderr, "%s: Unable to read from file %s: %s\n",
201                                 progname, filepnm, strerror(errno));
202                         goto out_close;
203                 }
204         }
205 out_close:
206         fclose(filep);
207
208         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
209         run_command(cmd, cmdsz);
210         if (ret)
211                 verrprint("Failed to read old data (%d)\n", ret);
212         return ret;
213 }
214
215
216 /* Display the need for the latest e2fsprogs to be installed. make_backfs
217  * indicates if the caller is make_lustre_backfs() or not. */
218 void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
219 {
220         static int msg_displayed;
221
222         if (msg_displayed) {
223                 fprintf(stderr, "WARNING: %s does not support %s "
224                         "feature.\n\n", E2FSPROGS, feature);
225                 return;
226         }
227
228         msg_displayed++;
229
230         fprintf(stderr, "WARNING: The %s package currently installed on "
231                 "your system does not support \"%s\" feature.\n",
232                 E2FSPROGS, feature);
233 #if !(HAVE_LDISKFSPROGS)
234         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
235                 "http://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
236                 "to enable this feature.\n");
237 #endif
238         if (make_backfs)
239                 fprintf(stderr, "Feature will not be enabled until %s"
240                         "is updated and '%s -O %s %%{device}' "
241                         "is run.\n\n", E2FSPROGS, TUNE2FS, feature);
242 }
243
244 /* Check whether the file exists in the device */
245 static int file_in_dev(char *file_name, char *dev_name)
246 {
247         FILE *fp;
248         char debugfs_cmd[256];
249         unsigned int inode_num;
250         int i;
251
252         /* Construct debugfs command line. */
253         snprintf(debugfs_cmd, sizeof(debugfs_cmd),
254                  "%s -c -R 'stat %s' '%s' 2>&1 | egrep '(Inode|unsupported)'",
255                  DEBUGFS, file_name, dev_name);
256
257         fp = popen(debugfs_cmd, "r");
258         if (!fp) {
259                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
260                 return 0;
261         }
262
263         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
264                 pclose(fp);
265                 return 1;
266         }
267         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd), fp);
268         if (i) {
269                 debugfs_cmd[i] = 0;
270                 fprintf(stderr, "%s", debugfs_cmd);
271                 if (strstr(debugfs_cmd, "unsupported feature")) {
272                         disp_old_e2fsprogs_msg("an unknown", 0);
273                 }
274                 pclose(fp);
275                 return -1;
276         }
277         pclose(fp);
278         return 0;
279 }
280
281 /* Check whether the device has already been used with lustre */
282 int ldiskfs_is_lustre(char *dev, unsigned *mount_type)
283 {
284         int ret;
285
286         ret = file_in_dev(MOUNT_DATA_FILE, dev);
287         if (ret) {
288                 /* in the -1 case, 'extents' means IS a lustre target */
289                 *mount_type = LDD_MT_LDISKFS;
290                 return 1;
291         }
292
293         ret = file_in_dev(LAST_RCVD, dev);
294         if (ret) {
295                 *mount_type = LDD_MT_LDISKFS;
296                 return 1;
297         }
298
299         return 0;
300 }
301
302 /* Check if a certain feature is supported by e2fsprogs.
303  * Firstly we try to use "debugfs supported_features" command to check if
304  * the feature is supported. If this fails we try to set this feature with
305  * mke2fs to check for its support. */
306 static int is_e2fsprogs_feature_supp(const char *feature)
307 {
308         static char supp_features[4096] = "";
309         FILE *fp;
310         char cmd[PATH_MAX];
311         char imgname[] = "/tmp/test-img-XXXXXX";
312         int fd = -1;
313         int ret = 1;
314
315         if (supp_features[0] == '\0') {
316                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
317                          DEBUGFS);
318
319                 /* Using popen() instead of run_command() since debugfs does
320                  * not return proper error code if command is not supported */
321                 fp = popen(cmd, "r");
322                 if (!fp) {
323                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
324                         return 0;
325                 }
326                 ret = fread(supp_features, 1, sizeof(supp_features), fp);
327                 fclose(fp);
328         }
329         if (ret > 0 && strstr(supp_features,
330                               strncmp(feature, "-O ", 3) ? feature : feature+3))
331                 return 0;
332
333         if ((fd = mkstemp(imgname)) < 0)
334                 return -1;
335         else
336                 close(fd);
337
338         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
339                  MKE2FS, feature, imgname);
340         /* run_command() displays the output of mke2fs when it fails for
341          * some feature, so use system() directly */
342         ret = system(cmd);
343         unlink(imgname);
344
345         return ret;
346 }
347
348
349 /**
350  * append_unique: append @key or @key=@val pair to @buf only if @key does not
351  *                exists
352  *      @buf: buffer to hold @key or @key=@val
353  *      @prefix: prefix string before @key
354  *      @key: key string
355  *      @val: value string if it's a @key=@val pair
356  */
357 static void append_unique(char *buf, char *prefix, char *key, char *val,
358                           size_t maxbuflen)
359 {
360         char *anchor, *end;
361         int  len;
362
363         if (key == NULL)
364                 return;
365
366         anchor = end = strstr(buf, key);
367         /* try to find exact match string in @buf */
368         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
369                 ++end;
370         len = end - anchor;
371         if (anchor == NULL || strlen(key) != len ||
372                         strncmp(anchor, key, len) != 0) {
373                 if (prefix != NULL)
374                         strscat(buf, prefix, maxbuflen);
375
376                 strscat(buf, key, maxbuflen);
377                 if (val != NULL) {
378                         strscat(buf, "=", maxbuflen);
379                         strscat(buf, val, maxbuflen);
380                 }
381         }
382 }
383
384 static void enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
385                                          size_t maxbuflen, int user_spec)
386 {
387         if (IS_OST(&mop->mo_ldd)) {
388                 append_unique(anchor, user_spec ? "," : " -O ",
389                               "extents", NULL, sizeof(mop->mo_mkfsopts));
390                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
391         } else if (IS_MDT(&mop->mo_ldd)) {
392                 append_unique(anchor, user_spec ? "," : " -O ",
393                               "dirdata", NULL, maxbuflen);
394                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
395                 append_unique(anchor, ",", "^extents", NULL, maxbuflen);
396         } else {
397                 append_unique(anchor, user_spec ? "," : " -O ",
398                               "uninit_bg", NULL, maxbuflen);
399         }
400
401         /* Multiple mount protection enabled only if failover node specified */
402         if (mop->mo_flags & MO_FAILOVER) {
403                 if (is_e2fsprogs_feature_supp("-O mmp") == 0)
404                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
405                 else
406                         disp_old_e2fsprogs_msg("mmp", 1);
407         }
408
409         /* Allow more than 65000 subdirectories */
410         if (is_e2fsprogs_feature_supp("-O dir_nlink") == 0)
411                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
412
413         /* The following options are only valid for ext4-based ldiskfs.
414          * If --backfstype=ext3 is specified, do not enable them. */
415         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
416                 return;
417
418         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
419         if (is_e2fsprogs_feature_supp("-O huge_file") == 0)
420                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
421
422         /* Enable large block addresses if the LUN is over 2^32 blocks. */
423         if (mop->mo_device_sz / (L_BLOCK_SIZE >> 10) >= 0x100002000ULL &&
424             is_e2fsprogs_feature_supp("-O 64bit") == 0)
425                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
426
427         /* Cluster inode/block bitmaps and inode table for more efficient IO.
428          * Align the flex groups on a 1MB boundary for better performance. */
429         /* This -O feature needs to go last, since it adds the "-G" option. */
430         if (is_e2fsprogs_feature_supp("-O flex_bg") == 0) {
431                 char tmp_buf[64];
432
433                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
434
435                 if (IS_OST(&mop->mo_ldd)) {
436                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
437                                  (1 << 20) / L_BLOCK_SIZE);
438                         strscat(anchor, tmp_buf, maxbuflen);
439                 }
440         }
441         /* Don't add any more "-O" options here, see last comment above */
442 }
443
444 /**
445  * moveopts_to_end: find the option string, move remaining strings to
446  *                  where option string starts, and append the option
447  *                  string at the end
448  *      @start: where the option string starts before the move
449  *      RETURN: where the option string starts after the move
450  */
451 static char *moveopts_to_end(char *start)
452 {
453         char save[512];
454         char *end, *idx;
455
456         /* skip whitespace before options */
457         end = start + 2;
458         while (*end == ' ')
459                 ++end;
460
461         /* find end of option characters */
462         while (*end != ' ' && *end != '\0')
463                 ++end;
464
465         /* save options */
466         strncpy(save, start, end - start);
467         save[end - start] = '\0';
468
469         /* move remaining options up front */
470         if (*end)
471                 memmove(start, end, strlen(end));
472         *(start + strlen(end)) = '\0';
473
474         /* append the specified options */
475         if (*(start + strlen(start) - 1) != ' ')
476                 strcat(start, " ");
477         idx = start + strlen(start);
478         strcat(start, save);
479
480         return idx;
481 }
482
483 /* Build fs according to type */
484 int ldiskfs_make_lustre(struct mkfs_opts *mop)
485 {
486         __u64 device_sz = mop->mo_device_sz, block_count = 0;
487         char mkfs_cmd[PATH_MAX];
488         char buf[64];
489         char *start;
490         char *dev;
491         int ret = 0, ext_opts = 0;
492         size_t maxbuflen;
493
494         if (!(mop->mo_flags & MO_IS_LOOP)) {
495                 mop->mo_device_sz = get_device_size(mop->mo_device);
496
497                 if (mop->mo_device_sz == 0)
498                         return ENODEV;
499
500                 /* Compare to real size */
501                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
502                         device_sz = mop->mo_device_sz;
503                 else
504                         mop->mo_device_sz = device_sz;
505         }
506
507         if (mop->mo_device_sz != 0) {
508                 if (mop->mo_device_sz < 8096){
509                         fprintf(stderr, "%s: size of filesystem must be larger "
510                                 "than 8MB, but is set to %lldKB\n",
511                                 progname, (long long)mop->mo_device_sz);
512                         return EINVAL;
513                 }
514                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
515                 /* If the LUN size is just over 2^32 blocks, limit the
516                  * filesystem size to 2^32-1 blocks to avoid problems with
517                  * ldiskfs/mkfs not handling this size.  Bug 22906 */
518                 if (block_count > 0xffffffffULL && block_count < 0x100002000ULL)
519                         block_count = 0xffffffffULL;
520         }
521
522         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
523             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
524             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
525                 long inode_size = 0;
526
527                 /* Journal size in MB */
528                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
529                         /* Choose our own default journal size */
530                         long journal_sz = 0, max_sz;
531                         if (device_sz > 1024 * 1024) /* 1GB */
532                                 journal_sz = (device_sz / 102400) * 4;
533                         /* cap journal size at 1GB */
534                         if (journal_sz > 1024L)
535                                 journal_sz = 1024L;
536                         /* man mkfs.ext3 */
537                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
538                         if (journal_sz > max_sz)
539                                 journal_sz = max_sz;
540                         if (journal_sz) {
541                                 sprintf(buf, " -J size=%ld", journal_sz);
542                                 strscat(mop->mo_mkfsopts, buf,
543                                         sizeof(mop->mo_mkfsopts));
544                         }
545                 }
546
547                 /* Inode size (for extended attributes).  The LOV EA size is
548                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
549                  * and we want some margin above that for ACLs, other EAs... */
550                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
551                         if (IS_MDT(&mop->mo_ldd)) {
552                                 if (mop->mo_stripe_count > 72)
553                                         inode_size = 512; /* bz 7241 */
554                                 /* see also "-i" below for EA blocks */
555                                 else if (mop->mo_stripe_count > 32)
556                                         inode_size = 2048;
557                                 else if (mop->mo_stripe_count > 10)
558                                         inode_size = 1024;
559                                 else
560                                         inode_size = 512;
561                         } else if (IS_OST(&mop->mo_ldd)) {
562                                 /* We store MDS FID and OST objid in EA on OST
563                                  * we need to make inode bigger as well. */
564                                 inode_size = 256;
565                         }
566
567                         if (inode_size > 0) {
568                                 sprintf(buf, " -I %ld", inode_size);
569                                 strscat(mop->mo_mkfsopts, buf,
570                                         sizeof(mop->mo_mkfsopts));
571                         }
572                 }
573
574                 /* Bytes_per_inode: disk size / num inodes */
575                 if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
576                     strstr(mop->mo_mkfsopts, "-N") == NULL) {
577                         long bytes_per_inode = 0;
578
579                         /* Allocate more inodes on MDT devices.  There is
580                          * no data stored on the MDT, and very little extra
581                          * metadata beyond the inode.  It could go down as
582                          * low as 1024 bytes, but this is conservative.
583                          * Account for external EA blocks for wide striping. */
584                         if (IS_MDT(&mop->mo_ldd)) {
585                                 bytes_per_inode = inode_size + 1536;
586
587                                 if (mop->mo_stripe_count > 72) {
588                                         int extra = mop->mo_stripe_count * 24;
589                                         extra = ((extra - 1) | 4095) + 1;
590                                         bytes_per_inode += extra;
591                                 }
592                         }
593
594                         /* Allocate fewer inodes on large OST devices.  Most
595                          * filesystems can be much more aggressive than even
596                          * this, but it is impossible to know in advance. */
597                         if (IS_OST(&mop->mo_ldd)) {
598                                 /* OST > 16TB assume average file size 1MB */
599                                 if (device_sz > (16ULL << 30))
600                                         bytes_per_inode = 1024 * 1024;
601                                 /* OST > 4TB assume average file size 512kB */
602                                 else if (device_sz > (4ULL << 30))
603                                         bytes_per_inode = 512 * 1024;
604                                 /* OST > 1TB assume average file size 256kB */
605                                 else if (device_sz > (1ULL << 30))
606                                         bytes_per_inode = 256 * 1024;
607                                 /* OST > 10GB assume average file size 64kB,
608                                  * plus a bit so that inodes will fit into a
609                                  * 256x flex_bg without overflowing */
610                                 else if (device_sz > (10ULL << 20))
611                                         bytes_per_inode = 69905;
612                         }
613
614                         if (bytes_per_inode > 0) {
615                                 sprintf(buf, " -i %ld", bytes_per_inode);
616                                 strscat(mop->mo_mkfsopts, buf,
617                                         sizeof(mop->mo_mkfsopts));
618                         }
619                 }
620
621                 if (verbose < 2) {
622                         strscat(mop->mo_mkfsopts, " -q",
623                                 sizeof(mop->mo_mkfsopts));
624                 }
625
626                 /* start handle -O mkfs options */
627                 if ((start = strstr(mop->mo_mkfsopts, "-O")) != NULL) {
628                         if (strstr(start + 2, "-O") != NULL) {
629                                 fprintf(stderr,
630                                         "%s: don't specify multiple -O options\n",
631                                         progname);
632                                 return EINVAL;
633                         }
634                         start = moveopts_to_end(start);
635                         maxbuflen = sizeof(mop->mo_mkfsopts) -
636                                 (start - mop->mo_mkfsopts) - strlen(start);
637                         enable_default_ext4_features(mop, start, maxbuflen, 1);
638                 } else {
639                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts),
640                               maxbuflen = sizeof(mop->mo_mkfsopts) -
641                                       strlen(mop->mo_mkfsopts);
642                         enable_default_ext4_features(mop, start, maxbuflen, 0);
643                 }
644                 /* end handle -O mkfs options */
645
646                 /* start handle -E mkfs options */
647                 if ((start = strstr(mop->mo_mkfsopts, "-E")) != NULL) {
648                         if (strstr(start + 2, "-E") != NULL) {
649                                 fprintf(stderr,
650                                         "%s: don't specify multiple -E options\n",
651                                         progname);
652                                 return EINVAL;
653                         }
654                         start = moveopts_to_end(start);
655                         maxbuflen = sizeof(mop->mo_mkfsopts) -
656                                 (start - mop->mo_mkfsopts) - strlen(start);
657                         ext_opts = 1;
658                 } else {
659                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
660                         maxbuflen = sizeof(mop->mo_mkfsopts) -
661                                 strlen(mop->mo_mkfsopts);
662                 }
663
664                 /* In order to align the filesystem metadata on 1MB boundaries,
665                  * give a resize value that will reserve a power-of-two group
666                  * descriptor blocks, but leave one block for the superblock.
667                  * Only useful for filesystems with < 2^32 blocks due to resize
668                  * limitations. */
669                 if (IS_OST(&mop->mo_ldd) && mop->mo_device_sz > 100 * 1024 &&
670                     mop->mo_device_sz * 1024 / L_BLOCK_SIZE <= 0xffffffffULL) {
671                         unsigned group_blocks = L_BLOCK_SIZE * 8;
672                         unsigned desc_per_block = L_BLOCK_SIZE / 32;
673                         unsigned resize_blks;
674
675                         resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
676                         snprintf(buf, sizeof(buf), "%u", resize_blks);
677                         append_unique(start, ext_opts ? "," : " -E ",
678                                       "resize", buf, maxbuflen);
679                         ext_opts = 1;
680                 }
681
682                 /* Avoid zeroing out the full journal - speeds up mkfs */
683                 if (is_e2fsprogs_feature_supp("-E lazy_journal_init") == 0)
684                         append_unique(start, ext_opts ? "," : " -E ",
685                                       "lazy_journal_init", NULL, maxbuflen);
686                 /* end handle -E mkfs options */
687
688                 /* Allow reformat of full devices (as opposed to
689                    partitions.)  We already checked for mounted dev. */
690                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
691
692                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
693                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
694                          mop->mo_ldd.ldd_svname);
695         } else {
696                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
697                         progname, mop->mo_ldd.ldd_mount_type,
698                         MT_STR(&mop->mo_ldd));
699                 return EINVAL;
700         }
701
702         /* For loop device format the dev, not the filename */
703         dev = mop->mo_device;
704         if (mop->mo_flags & MO_IS_LOOP)
705                 dev = mop->mo_loopdev;
706
707         vprint("formatting backing filesystem %s on %s\n",
708                MT_STR(&mop->mo_ldd), dev);
709         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
710         vprint("\t4k blocks     "LPU64"\n", block_count);
711         vprint("\toptions       %s\n", mop->mo_mkfsopts);
712
713         /* mkfs_cmd's trailing space is important! */
714         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
715         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
716         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
717         if (block_count != 0) {
718                 sprintf(buf, " "LPU64, block_count);
719                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
720         }
721
722         vprint("mkfs_cmd = %s\n", mkfs_cmd);
723         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
724         if (ret) {
725                 fatal();
726                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
727         }
728         return ret;
729 }
730
731 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
732                            char *default_mountopts, int default_len,
733                            char *always_mountopts, int always_len)
734 {
735         struct lustre_disk_data *ldd = &mop->mo_ldd;
736         int ret;
737
738         /* Set MO_IS_LOOP to indicate a loopback device is needed */
739         ret = is_block(mop->mo_device);
740         if (ret < 0) {
741                 return errno;
742         } else if (ret == 0) {
743                 mop->mo_flags |= MO_IS_LOOP;
744         }
745
746         strscat(default_mountopts, ",errors=remount-ro", default_len);
747         if (IS_MDT(ldd) || IS_MGS(ldd))
748                 strscat(always_mountopts, ",user_xattr", always_len);
749
750         return 0;
751 }
752
753 int read_file(char *path, char *buf, int size)
754 {
755         FILE *fd;
756
757         fd = fopen(path, "r");
758         if (fd == NULL)
759                 return errno;
760
761         /* should not ignore fgets(3)'s return value */
762         if (!fgets(buf, size, fd)) {
763                 fprintf(stderr, "reading from %s: %s", path, strerror(errno));
764                 fclose(fd);
765                 return 1;
766         }
767         fclose(fd);
768         return 0;
769 }
770
771 int write_file(char *path, char *buf)
772 {
773         FILE *fd;
774
775         fd = fopen(path, "w");
776         if (fd == NULL)
777                 return errno;
778
779         fputs(buf, fd);
780         fclose(fd);
781         return 0;
782 }
783
784 /* This is to tune the kernel for good SCSI performance.
785  * For that we set the value of /sys/block/{dev}/queue/max_sectors_kb
786  * to the value of /sys/block/{dev}/queue/max_hw_sectors_kb */
787 int set_blockdev_tunables(char *source, struct mount_opts *mop, int fan_out)
788 {
789         glob_t glob_info = { 0 };
790         struct stat stat_buf;
791         char *chk_major, *chk_minor;
792         char *savept = NULL, *dev;
793         char *ret_path;
794         char buf[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
795         char real_path[PATH_MAX] = {'\0'};
796         int i, rc = 0;
797         int major, minor;
798
799         if (!source)
800                 return -EINVAL;
801
802         ret_path = realpath(source, real_path);
803         if (ret_path == NULL) {
804                 if (verbose)
805                         fprintf(stderr, "warning: %s: cannot resolve: %s\n",
806                                 source, strerror(errno));
807                 return -EINVAL;
808         }
809
810         if (strncmp(real_path, "/dev/loop", 9) == 0)
811                 return 0;
812
813         if ((real_path[0] != '/') && (strpbrk(real_path, ",:") != NULL))
814                 return 0;
815
816         snprintf(path, sizeof(path), "/sys/block%s", real_path + 4);
817         if (access(path, X_OK) == 0)
818                 goto set_params;
819
820         /* The name of the device say 'X' specified in /dev/X may not
821          * match any entry under /sys/block/. In that case we need to
822          * match the major/minor number to find the entry under
823          * sys/block corresponding to /dev/X */
824
825         /* Don't chop tail digit on /dev/mapper/xxx, LU-478 */
826         if (strncmp(real_path, "/dev/mapper", 11) != 0) {
827                 dev = real_path + strlen(real_path);
828                 while (--dev > real_path && isdigit(*dev))
829                         *dev = 0;
830
831                 if (strncmp(real_path, "/dev/md_", 8) == 0)
832                         *dev = 0;
833         }
834
835         rc = stat(real_path, &stat_buf);
836         if (rc) {
837                 if (verbose)
838                         fprintf(stderr, "warning: %s, device %s stat failed\n",
839                                 strerror(errno), real_path);
840                 return rc;
841         }
842
843         major = major(stat_buf.st_rdev);
844         minor = minor(stat_buf.st_rdev);
845         rc = glob("/sys/block/*", GLOB_NOSORT, NULL, &glob_info);
846         if (rc) {
847                 if (verbose)
848                         fprintf(stderr, "warning: failed to read entries under "
849                                 "/sys/block\n");
850                 globfree(&glob_info);
851                 return rc;
852         }
853
854         for (i = 0; i < glob_info.gl_pathc; i++){
855                 snprintf(path, sizeof(path), "%s/dev", glob_info.gl_pathv[i]);
856
857                 rc = read_file(path, buf, sizeof(buf));
858                 if (rc)
859                         continue;
860
861                 if (buf[strlen(buf) - 1] == '\n')
862                         buf[strlen(buf) - 1] = '\0';
863
864                 chk_major = strtok_r(buf, ":", &savept);
865                 chk_minor = savept;
866                 if (major == atoi(chk_major) &&minor == atoi(chk_minor))
867                         break;
868         }
869
870         if (i == glob_info.gl_pathc) {
871                 if (verbose)
872                         fprintf(stderr,"warning: device %s does not match any "
873                                 "entry under /sys/block\n", real_path);
874                 globfree(&glob_info);
875                 return -EINVAL;
876         }
877
878         /* Chop off "/dev" from path we found */
879         path[strlen(glob_info.gl_pathv[i])] = '\0';
880         globfree(&glob_info);
881
882 set_params:
883         if (strncmp(real_path, "/dev/md", 7) == 0) {
884                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
885                          STRIPE_CACHE_SIZE);
886
887                 rc = read_file(real_path, buf, sizeof(buf));
888                 if (rc) {
889                         if (verbose)
890                                 fprintf(stderr, "warning: opening %s: %s\n",
891                                         real_path, strerror(errno));
892                         return 0;
893                 }
894
895                 if (atoi(buf) >= mop->mo_md_stripe_cache_size)
896                         return 0;
897
898                 if (strlen(buf) - 1 > 0) {
899                         snprintf(buf, sizeof(buf), "%d",
900                                  mop->mo_md_stripe_cache_size);
901                         rc = write_file(real_path, buf);
902                         if (rc && verbose)
903                                 fprintf(stderr, "warning: opening %s: %s\n",
904                                         real_path, strerror(errno));
905                 }
906                 /* Return since raid and disk tunables are different */
907                 return rc;
908         }
909
910         snprintf(real_path, sizeof(real_path), "%s/%s", path,
911                  MAX_HW_SECTORS_KB_PATH);
912         rc = read_file(real_path, buf, sizeof(buf));
913         if (rc) {
914                 if (verbose)
915                         fprintf(stderr, "warning: opening %s: %s\n",
916                                 real_path, strerror(errno));
917                 /* No MAX_HW_SECTORS_KB_PATH isn't necessary an
918                  * error for some device. */
919                 rc = 0;
920         }
921
922         if (strlen(buf) - 1 > 0) {
923                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
924                          MAX_SECTORS_KB_PATH);
925                 rc = write_file(real_path, buf);
926                 if (rc) {
927                         if (verbose)
928                                 fprintf(stderr, "warning: writing to %s: %s\n",
929                                         real_path, strerror(errno));
930                         /* No MAX_SECTORS_KB_PATH isn't necessary an
931                          * error for some device. */
932                         rc = 0;
933                 }
934         }
935
936         if (fan_out) {
937                 char *slave = NULL;
938                 glob_info.gl_pathc = 0;
939                 glob_info.gl_offs = 0;
940                 /* if device is multipath device, tune its slave devices */
941                 snprintf(real_path, sizeof(real_path), "%s/slaves/*", path);
942                 rc = glob(real_path, GLOB_NOSORT, NULL, &glob_info);
943
944                 for (i = 0; rc == 0 && i < glob_info.gl_pathc; i++){
945                         slave = basename(glob_info.gl_pathv[i]);
946                         snprintf(real_path, sizeof(real_path), "/dev/%s", slave);
947                         rc = set_blockdev_tunables(real_path, mop, 0);
948                 }
949
950                 if (rc == GLOB_NOMATCH) {
951                         /* no slave device is not an error */
952                         rc = 0;
953                 } else if (rc && verbose) {
954                         if (slave == NULL) {
955                                 fprintf(stderr, "warning: %s, failed to read"
956                                         " entries under %s/slaves\n",
957                                         strerror(errno), path);
958                         } else {
959                                 fprintf(stderr, "unable to set tunables for"
960                                         " slave device %s (slave would be"
961                                         " unable to handle IO request from"
962                                         " master %s)\n",
963                                         real_path, source);
964                         }
965                 }
966                 globfree(&glob_info);
967         }
968
969         return rc;
970 }
971
972 int ldiskfs_tune_lustre(char *dev, struct mount_opts *mop)
973 {
974         return set_blockdev_tunables(dev, mop, 1);
975 }
976
977 int ldiskfs_label_lustre(struct mount_opts *mop)
978 {
979         char label_cmd[PATH_MAX];
980         int rc;
981
982         snprintf(label_cmd, sizeof(label_cmd), E2LABEL" %s %s",
983                  mop->mo_source, mop->mo_ldd.ldd_svname);
984         rc = run_command(label_cmd, sizeof(label_cmd));
985
986         return rc;
987 }
988
989 /* return canonicalized absolute pathname, even if the target file does not
990  * exist, unlike realpath */
991 static char *absolute_path(char *devname)
992 {
993         char  buf[PATH_MAX + 1];
994         char *path;
995         char *ptr;
996
997         path = malloc(PATH_MAX + 1);
998         if (path == NULL)
999                 return NULL;
1000
1001         if (devname[0] != '/') {
1002                 if (getcwd(buf, sizeof(buf) - 1) == NULL)
1003                         return NULL;
1004                 strcat(buf, "/");
1005                 strcat(buf, devname);
1006         } else {
1007                 strcpy(buf, devname);
1008         }
1009         /* truncate filename before calling realpath */
1010         ptr = strrchr(buf, '/');
1011         if (ptr == NULL) {
1012                 free(path);
1013                 return NULL;
1014         }
1015         *ptr = '\0';
1016         if (path != realpath(buf, path)) {
1017                 free(path);
1018                 return NULL;
1019         }
1020         /* add the filename back */
1021         strcat(path, "/");
1022         strcat(path, ptr + 1);
1023         return path;
1024 }
1025
1026 /* Determine if a device is a block device (as opposed to a file) */
1027 int is_block(char* devname)
1028 {
1029         struct stat st;
1030         int     ret = 0;
1031         char    *devpath;
1032
1033         devpath = absolute_path(devname);
1034         if (devpath == NULL) {
1035                 fprintf(stderr, "%s: failed to resolve path to %s\n",
1036                         progname, devname);
1037                 return -1;
1038         }
1039
1040         ret = access(devname, F_OK);
1041         if (ret != 0) {
1042                 if (strncmp(devpath, "/dev/", 5) == 0) {
1043                         /* nobody sane wants to create a loopback file under
1044                          * /dev. Let's just report the device doesn't exist */
1045                         fprintf(stderr, "%s: %s apparently does not exist\n",
1046                                 progname, devpath);
1047                         ret = -1;
1048                         goto out;
1049                 }
1050                 ret = 0;
1051                 goto out;
1052         }
1053         ret = stat(devpath, &st);
1054         if (ret != 0) {
1055                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
1056                 goto out;
1057         }
1058         ret = S_ISBLK(st.st_mode);
1059 out:
1060         free(devpath);
1061         return ret;
1062 }
1063
1064 int ldiskfs_init(void)
1065 {
1066         /* Required because full path to DEBUGFS is not specified */
1067         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin", 0);
1068
1069         return 0;
1070 }
1071
1072 void ldiskfs_fini(void)
1073 {
1074         return;
1075 }
1076