Whamcloud - gitweb
4321bcbb02126c0ff2647b0d5f16e90cef9abe04
[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
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/mount.h>
60 #include <sys/utsname.h>
61
62 #include <string.h>
63 #include <getopt.h>
64 #include <limits.h>
65 #include <ctype.h>
66
67 #ifdef __linux__
68 /* libcfs.h is not really needed here, but on SLES10/PPC, fs.h includes idr.h
69  * which requires BITS_PER_LONG to be defined */
70 #include <libcfs/libcfs.h>
71 #ifndef BLKGETSIZE64
72 #include <linux/fs.h> /* for BLKGETSIZE64 */
73 #endif
74 #include <linux/version.h>
75 #endif
76 #include <lustre_disk.h>
77 #include <lustre_param.h>
78 #include <lnet/lnetctl.h>
79 #include <lustre_ver.h>
80 #include "mount_utils.h"
81
82 extern char *progname;
83
84 #define L_BLOCK_SIZE 4096
85 /* keep it less than LL_FID_NAMELEN */
86 #define DUMMY_FILE_NAME_LEN             25
87 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
88
89 /* Write the server config files */
90 int write_local_files(struct mkfs_opts *mop)
91 {
92         char mntpt[] = "/tmp/mntXXXXXX";
93         char filepnm[128];
94         char *dev;
95         FILE *filep;
96         int ret = 0;
97         size_t num;
98
99         /* Mount this device temporarily in order to write these files */
100         if (!mkdtemp(mntpt)) {
101                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
102                         progname, mntpt, strerror(errno));
103                 return errno;
104         }
105
106         dev = mop->mo_device;
107         if (mop->mo_flags & MO_IS_LOOP)
108                 dev = mop->mo_loopdev;
109
110         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
111                     mop->mo_ldd.ldd_mount_opts);
112         if (ret) {
113                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
114                         progname, dev, strerror(errno));
115                 ret = errno;
116                 if (errno == ENODEV) {
117                         fprintf(stderr, "Is the %s module available?\n",
118                                 MT_STR(&mop->mo_ldd));
119                 }
120                 goto out_rmdir;
121         }
122
123         /* Set up initial directories */
124         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
125         ret = mkdir(filepnm, 0777);
126         if ((ret != 0) && (errno != EEXIST)) {
127                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
128                         progname, filepnm, strerror(errno));
129                 goto out_umnt;
130         } else if (errno == EEXIST) {
131                 ret = 0;
132         }
133
134         /* Save the persistent mount data into a file. Lustre must pre-read
135            this file to get the real mount options. */
136         vprint("Writing %s\n", MOUNT_DATA_FILE);
137         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
138         filep = fopen(filepnm, "w");
139         if (!filep) {
140                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
141                         progname, filepnm, strerror(errno));
142                 goto out_umnt;
143         }
144         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
145         if (num < 1 && ferror(filep)) {
146                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
147                         progname, filepnm, strerror(errno));
148                 goto out_umnt;
149         }
150         fclose(filep);
151
152 out_umnt:
153         umount(mntpt);
154 out_rmdir:
155         rmdir(mntpt);
156         return ret;
157 }
158
159 int ldiskfs_read_ldd(char *dev, struct lustre_disk_data *mo_ldd)
160 {
161         char tmpdir[] = "/tmp/dirXXXXXX";
162         char cmd[PATH_MAX];
163         char filepnm[128];
164         FILE *filep;
165         int ret = 0;
166         int cmdsz = sizeof(cmd);
167
168         /* Make a temporary directory to hold Lustre data files. */
169         if (!mkdtemp(tmpdir)) {
170                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
171                         progname, tmpdir, strerror(errno));
172                 return errno;
173         }
174
175         /* TODO: it's worth observing the get_mountdata() function that is
176            in mount_utils.c for getting the mountdata out of the
177            filesystem */
178
179         /* Construct debugfs command line. */
180         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
181                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
182
183         ret = run_command(cmd, cmdsz);
184         if (ret)
185                 verrprint("%s: Unable to dump %s dir (%d)\n",
186                           progname, MOUNT_CONFIGS_DIR, ret);
187
188         sprintf(filepnm, "%s/mountdata", tmpdir);
189         filep = fopen(filepnm, "r");
190         if (filep) {
191                 size_t num_read;
192                 vprint("Reading %s\n", MOUNT_DATA_FILE);
193                 num_read = fread(mo_ldd, sizeof(*mo_ldd), 1, filep);
194                 if (num_read < 1 && ferror(filep)) {
195                         fprintf(stderr, "%s: Unable to read from file %s: %s\n",
196                                 progname, filepnm, strerror(errno));
197                         goto out_close;
198                 }
199         }
200 out_close:
201         fclose(filep);
202
203         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
204         run_command(cmd, cmdsz);
205         if (ret)
206                 verrprint("Failed to read old data (%d)\n", ret);
207         return ret;
208 }
209
210
211 /* Display the need for the latest e2fsprogs to be installed. make_backfs
212  * indicates if the caller is make_lustre_backfs() or not. */
213 void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
214 {
215         static int msg_displayed;
216
217         if (msg_displayed) {
218                 fprintf(stderr, "WARNING: %s does not support %s "
219                         "feature.\n\n", E2FSPROGS, feature);
220                 return;
221         }
222
223         msg_displayed++;
224
225         fprintf(stderr, "WARNING: The %s package currently installed on "
226                 "your system does not support \"%s\" feature.\n",
227                 E2FSPROGS, feature);
228 #if !(HAVE_LDISKFSPROGS)
229         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
230                 "http://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
231                 "to enable this feature.\n");
232 #endif
233         if (make_backfs)
234                 fprintf(stderr, "Feature will not be enabled until %s"
235                         "is updated and '%s -O %s %%{device}' "
236                         "is run.\n\n", E2FSPROGS, TUNE2FS, feature);
237 }
238
239 /* Check whether the file exists in the device */
240 static int file_in_dev(char *file_name, char *dev_name)
241 {
242         FILE *fp;
243         char debugfs_cmd[256];
244         unsigned int inode_num;
245         int i;
246
247         /* Construct debugfs command line. */
248         snprintf(debugfs_cmd, sizeof(debugfs_cmd),
249                  "%s -c -R 'stat %s' '%s' 2>&1 | egrep '(Inode|unsupported)'",
250                  DEBUGFS, file_name, dev_name);
251
252         fp = popen(debugfs_cmd, "r");
253         if (!fp) {
254                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
255                 return 0;
256         }
257
258         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
259                 pclose(fp);
260                 return 1;
261         }
262         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd), fp);
263         if (i) {
264                 debugfs_cmd[i] = 0;
265                 fprintf(stderr, "%s", debugfs_cmd);
266                 if (strstr(debugfs_cmd, "unsupported feature")) {
267                         disp_old_e2fsprogs_msg("an unknown", 0);
268                 }
269                 pclose(fp);
270                 return -1;
271         }
272         pclose(fp);
273         return 0;
274 }
275
276 /* Check whether the device has already been used with lustre */
277 int ldiskfs_is_lustre(char *dev, unsigned *mount_type)
278 {
279         int ret;
280
281         ret = file_in_dev(MOUNT_DATA_FILE, dev);
282         if (ret) {
283                 /* in the -1 case, 'extents' means IS a lustre target */
284                 *mount_type = LDD_MT_LDISKFS;
285                 return 1;
286         }
287
288         ret = file_in_dev(LAST_RCVD, dev);
289         if (ret) {
290                 *mount_type = LDD_MT_LDISKFS;
291                 return 1;
292         }
293
294         return 0;
295 }
296
297 /* Check if a certain feature is supported by e2fsprogs.
298  * Firstly we try to use "debugfs supported_features" command to check if
299  * the feature is supported. If this fails we try to set this feature with
300  * mke2fs to check for its support. */
301 static int is_e2fsprogs_feature_supp(const char *feature)
302 {
303         static char supp_features[4096] = "";
304         FILE *fp;
305         char cmd[PATH_MAX];
306         char imgname[] = "/tmp/test-img-XXXXXX";
307         int fd = -1;
308         int ret = 1;
309
310         if (supp_features[0] == '\0') {
311                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
312                          DEBUGFS);
313
314                 /* Using popen() instead of run_command() since debugfs does
315                  * not return proper error code if command is not supported */
316                 fp = popen(cmd, "r");
317                 if (!fp) {
318                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
319                         return 0;
320                 }
321                 ret = fread(supp_features, 1, sizeof(supp_features), fp);
322                 fclose(fp);
323         }
324         if (ret > 0 && strstr(supp_features,
325                               strncmp(feature, "-O ", 3) ? feature : feature+3))
326                 return 0;
327
328         if ((fd = mkstemp(imgname)) < 0)
329                 return -1;
330         else
331                 close(fd);
332
333         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
334                  MKE2FS, feature, imgname);
335         /* run_command() displays the output of mke2fs when it fails for
336          * some feature, so use system() directly */
337         ret = system(cmd);
338         unlink(imgname);
339
340         return ret;
341 }
342
343
344 /**
345  * append_unique: append @key or @key=@val pair to @buf only if @key does not
346  *                exists
347  *      @buf: buffer to hold @key or @key=@val
348  *      @prefix: prefix string before @key
349  *      @key: key string
350  *      @val: value string if it's a @key=@val pair
351  */
352 static void append_unique(char *buf, char *prefix, char *key, char *val,
353                           size_t maxbuflen)
354 {
355         char *anchor, *end;
356         int  len;
357
358         if (key == NULL)
359                 return;
360
361         anchor = end = strstr(buf, key);
362         /* try to find exact match string in @buf */
363         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
364                 ++end;
365         len = end - anchor;
366         if (anchor == NULL || strlen(key) != len ||
367                         strncmp(anchor, key, len) != 0) {
368                 if (prefix != NULL)
369                         strscat(buf, prefix, maxbuflen);
370
371                 strscat(buf, key, maxbuflen);
372                 if (val != NULL) {
373                         strscat(buf, "=", maxbuflen);
374                         strscat(buf, val, maxbuflen);
375                 }
376         }
377 }
378
379 static void enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
380                                          size_t maxbuflen, int user_spec)
381 {
382         if (IS_OST(&mop->mo_ldd)) {
383                 append_unique(anchor, user_spec ? "," : " -O ",
384                               "extents", NULL, sizeof(mop->mo_mkfsopts));
385                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
386         } else if (IS_MDT(&mop->mo_ldd)) {
387                 append_unique(anchor, user_spec ? "," : " -O ",
388                               "dirdata", NULL, maxbuflen);
389                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
390                 append_unique(anchor, ",", "^extents", NULL, maxbuflen);
391         } else {
392                 append_unique(anchor, user_spec ? "," : " -O ",
393                               "uninit_bg", NULL, maxbuflen);
394         }
395
396         /* Multiple mount protection enabled only if failover node specified */
397         if (mop->mo_flags & MO_FAILOVER) {
398                 if (is_e2fsprogs_feature_supp("-O mmp") == 0)
399                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
400                 else
401                         disp_old_e2fsprogs_msg("mmp", 1);
402         }
403
404         /* Allow more than 65000 subdirectories */
405         if (is_e2fsprogs_feature_supp("-O dir_nlink") == 0)
406                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
407
408         /* The following options are only valid for ext4-based ldiskfs.
409          * If --backfstype=ext3 is specified, do not enable them. */
410         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
411                 return;
412
413         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
414         if (is_e2fsprogs_feature_supp("-O huge_file") == 0)
415                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
416
417         /* Enable large block addresses if the LUN is over 2^32 blocks. */
418         if (mop->mo_device_sz / (L_BLOCK_SIZE >> 10) >= 0x100002000ULL &&
419             is_e2fsprogs_feature_supp("-O 64bit") == 0)
420                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
421
422         /* Cluster inode/block bitmaps and inode table for more efficient IO.
423          * Align the flex groups on a 1MB boundary for better performance. */
424         /* This -O feature needs to go last, since it adds the "-G" option. */
425         if (is_e2fsprogs_feature_supp("-O flex_bg") == 0) {
426                 char tmp_buf[64];
427
428                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
429
430                 if (IS_OST(&mop->mo_ldd)) {
431                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
432                                  (1 << 20) / L_BLOCK_SIZE);
433                         strscat(anchor, tmp_buf, maxbuflen);
434                 }
435         }
436         /* Don't add any more "-O" options here, see last comment above */
437 }
438
439 /**
440  * moveopts_to_end: find the option string, move remaining strings to
441  *                  where option string starts, and append the option
442  *                  string at the end
443  *      @start: where the option string starts before the move
444  *      RETURN: where the option string starts after the move
445  */
446 static char *moveopts_to_end(char *start)
447 {
448         char save[512];
449         char *end, *idx;
450
451         /* skip whitespace before options */
452         end = start + 2;
453         while (*end == ' ')
454                 ++end;
455
456         /* find end of option characters */
457         while (*end != ' ' && *end != '\0')
458                 ++end;
459
460         /* save options */
461         strncpy(save, start, end - start);
462         save[end - start] = '\0';
463
464         /* move remaining options up front */
465         if (*end)
466                 memmove(start, end, strlen(end));
467         *(start + strlen(end)) = '\0';
468
469         /* append the specified options */
470         if (*(start + strlen(start) - 1) != ' ')
471                 strcat(start, " ");
472         idx = start + strlen(start);
473         strcat(start, save);
474
475         return idx;
476 }
477
478 /* Build fs according to type */
479 int make_lustre_backfs(struct mkfs_opts *mop)
480 {
481         __u64 device_sz = mop->mo_device_sz, block_count = 0;
482         char mkfs_cmd[PATH_MAX];
483         char buf[64];
484         char *start;
485         char *dev;
486         int ret = 0, ext_opts = 0;
487         size_t maxbuflen;
488
489         if (!(mop->mo_flags & MO_IS_LOOP)) {
490                 mop->mo_device_sz = get_device_size(mop->mo_device);
491
492                 if (mop->mo_device_sz == 0)
493                         return ENODEV;
494
495                 /* Compare to real size */
496                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
497                         device_sz = mop->mo_device_sz;
498                 else
499                         mop->mo_device_sz = device_sz;
500         }
501
502         if (mop->mo_device_sz != 0) {
503                 if (mop->mo_device_sz < 8096){
504                         fprintf(stderr, "%s: size of filesystem must be larger "
505                                 "than 8MB, but is set to %lldKB\n",
506                                 progname, (long long)mop->mo_device_sz);
507                         return EINVAL;
508                 }
509                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
510                 /* If the LUN size is just over 2^32 blocks, limit the
511                  * filesystem size to 2^32-1 blocks to avoid problems with
512                  * ldiskfs/mkfs not handling this size.  Bug 22906 */
513                 if (block_count > 0xffffffffULL && block_count < 0x100002000ULL)
514                         block_count = 0xffffffffULL;
515         }
516
517         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
518             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
519             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
520                 long inode_size = 0;
521
522                 /* Journal size in MB */
523                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
524                         /* Choose our own default journal size */
525                         long journal_sz = 0, max_sz;
526                         if (device_sz > 1024 * 1024) /* 1GB */
527                                 journal_sz = (device_sz / 102400) * 4;
528                         /* cap journal size at 1GB */
529                         if (journal_sz > 1024L)
530                                 journal_sz = 1024L;
531                         /* man mkfs.ext3 */
532                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
533                         if (journal_sz > max_sz)
534                                 journal_sz = max_sz;
535                         if (journal_sz) {
536                                 sprintf(buf, " -J size=%ld", journal_sz);
537                                 strscat(mop->mo_mkfsopts, buf,
538                                         sizeof(mop->mo_mkfsopts));
539                         }
540                 }
541
542                 /* Inode size (for extended attributes).  The LOV EA size is
543                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
544                  * and we want some margin above that for ACLs, other EAs... */
545                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
546                         if (IS_MDT(&mop->mo_ldd)) {
547                                 if (mop->mo_stripe_count > 72)
548                                         inode_size = 512; /* bz 7241 */
549                                 /* see also "-i" below for EA blocks */
550                                 else if (mop->mo_stripe_count > 32)
551                                         inode_size = 2048;
552                                 else if (mop->mo_stripe_count > 10)
553                                         inode_size = 1024;
554                                 else
555                                         inode_size = 512;
556                         } else if (IS_OST(&mop->mo_ldd)) {
557                                 /* We store MDS FID and OST objid in EA on OST
558                                  * we need to make inode bigger as well. */
559                                 inode_size = 256;
560                         }
561
562                         if (inode_size > 0) {
563                                 sprintf(buf, " -I %ld", inode_size);
564                                 strscat(mop->mo_mkfsopts, buf,
565                                         sizeof(mop->mo_mkfsopts));
566                         }
567                 }
568
569                 /* Bytes_per_inode: disk size / num inodes */
570                 if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
571                     strstr(mop->mo_mkfsopts, "-N") == NULL) {
572                         long bytes_per_inode = 0;
573
574                         /* Allocate more inodes on MDT devices.  There is
575                          * no data stored on the MDT, and very little extra
576                          * metadata beyond the inode.  It could go down as
577                          * low as 1024 bytes, but this is conservative.
578                          * Account for external EA blocks for wide striping. */
579                         if (IS_MDT(&mop->mo_ldd)) {
580                                 bytes_per_inode = inode_size + 1536;
581
582                                 if (mop->mo_stripe_count > 72) {
583                                         int extra = mop->mo_stripe_count * 24;
584                                         extra = ((extra - 1) | 4095) + 1;
585                                         bytes_per_inode += extra;
586                                 }
587                         }
588
589                         /* Allocate fewer inodes on large OST devices.  Most
590                          * filesystems can be much more aggressive than even
591                          * this, but it is impossible to know in advance. */
592                         if (IS_OST(&mop->mo_ldd)) {
593                                 /* OST > 16TB assume average file size 1MB */
594                                 if (device_sz > (16ULL << 30))
595                                         bytes_per_inode = 1024 * 1024;
596                                 /* OST > 4TB assume average file size 512kB */
597                                 else if (device_sz > (4ULL << 30))
598                                         bytes_per_inode = 512 * 1024;
599                                 /* OST > 1TB assume average file size 256kB */
600                                 else if (device_sz > (1ULL << 30))
601                                         bytes_per_inode = 256 * 1024;
602                                 /* OST > 10GB assume average file size 64kB,
603                                  * plus a bit so that inodes will fit into a
604                                  * 256x flex_bg without overflowing */
605                                 else if (device_sz > (10ULL << 20))
606                                         bytes_per_inode = 69905;
607                         }
608
609                         if (bytes_per_inode > 0) {
610                                 sprintf(buf, " -i %ld", bytes_per_inode);
611                                 strscat(mop->mo_mkfsopts, buf,
612                                         sizeof(mop->mo_mkfsopts));
613                         }
614                 }
615
616                 if (verbose < 2) {
617                         strscat(mop->mo_mkfsopts, " -q",
618                                 sizeof(mop->mo_mkfsopts));
619                 }
620
621                 /* start handle -O mkfs options */
622                 if ((start = strstr(mop->mo_mkfsopts, "-O")) != NULL) {
623                         if (strstr(start + 2, "-O") != NULL) {
624                                 fprintf(stderr,
625                                         "%s: don't specify multiple -O options\n",
626                                         progname);
627                                 return EINVAL;
628                         }
629                         start = moveopts_to_end(start);
630                         maxbuflen = sizeof(mop->mo_mkfsopts) -
631                                 (start - mop->mo_mkfsopts) - strlen(start);
632                         enable_default_ext4_features(mop, start, maxbuflen, 1);
633                 } else {
634                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts),
635                               maxbuflen = sizeof(mop->mo_mkfsopts) -
636                                       strlen(mop->mo_mkfsopts);
637                         enable_default_ext4_features(mop, start, maxbuflen, 0);
638                 }
639                 /* end handle -O mkfs options */
640
641                 /* start handle -E mkfs options */
642                 if ((start = strstr(mop->mo_mkfsopts, "-E")) != NULL) {
643                         if (strstr(start + 2, "-E") != NULL) {
644                                 fprintf(stderr,
645                                         "%s: don't specify multiple -E options\n",
646                                         progname);
647                                 return EINVAL;
648                         }
649                         start = moveopts_to_end(start);
650                         maxbuflen = sizeof(mop->mo_mkfsopts) -
651                                 (start - mop->mo_mkfsopts) - strlen(start);
652                         ext_opts = 1;
653                 } else {
654                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
655                         maxbuflen = sizeof(mop->mo_mkfsopts) -
656                                 strlen(mop->mo_mkfsopts);
657                 }
658
659                 /* In order to align the filesystem metadata on 1MB boundaries,
660                  * give a resize value that will reserve a power-of-two group
661                  * descriptor blocks, but leave one block for the superblock.
662                  * Only useful for filesystems with < 2^32 blocks due to resize
663                  * limitations. */
664                 if (IS_OST(&mop->mo_ldd) && mop->mo_device_sz > 100 * 1024 &&
665                     mop->mo_device_sz * 1024 / L_BLOCK_SIZE <= 0xffffffffULL) {
666                         unsigned group_blocks = L_BLOCK_SIZE * 8;
667                         unsigned desc_per_block = L_BLOCK_SIZE / 32;
668                         unsigned resize_blks;
669
670                         resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
671                         snprintf(buf, sizeof(buf), "%u", resize_blks);
672                         append_unique(start, ext_opts ? "," : " -E ",
673                                       "resize", buf, maxbuflen);
674                         ext_opts = 1;
675                 }
676
677                 /* Avoid zeroing out the full journal - speeds up mkfs */
678                 if (is_e2fsprogs_feature_supp("-E lazy_journal_init") == 0)
679                         append_unique(start, ext_opts ? "," : " -E ",
680                                       "lazy_journal_init", NULL, maxbuflen);
681                 /* end handle -E mkfs options */
682
683                 /* Allow reformat of full devices (as opposed to
684                    partitions.)  We already checked for mounted dev. */
685                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
686
687                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
688                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
689                          mop->mo_ldd.ldd_svname);
690         } else {
691                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
692                         progname, mop->mo_ldd.ldd_mount_type,
693                         MT_STR(&mop->mo_ldd));
694                 return EINVAL;
695         }
696
697         /* For loop device format the dev, not the filename */
698         dev = mop->mo_device;
699         if (mop->mo_flags & MO_IS_LOOP)
700                 dev = mop->mo_loopdev;
701
702         vprint("formatting backing filesystem %s on %s\n",
703                MT_STR(&mop->mo_ldd), dev);
704         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
705         vprint("\t4k blocks     "LPU64"\n", block_count);
706         vprint("\toptions       %s\n", mop->mo_mkfsopts);
707
708         /* mkfs_cmd's trailing space is important! */
709         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
710         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
711         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
712         if (block_count != 0) {
713                 sprintf(buf, " "LPU64, block_count);
714                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
715         }
716
717         vprint("mkfs_cmd = %s\n", mkfs_cmd);
718         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
719         if (ret) {
720                 fatal();
721                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
722         }
723         return ret;
724 }
725
726 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
727                            char *default_mountopts, int default_len,
728                            char *always_mountopts, int always_len)
729 {
730         struct lustre_disk_data *ldd = &mop->mo_ldd;
731         int ret;
732
733         /* Set MO_IS_LOOP to indicate a loopback device is needed */
734         ret = is_block(mop->mo_device);
735         if (ret < 0) {
736                 return errno;
737         } else if (ret == 0) {
738                 mop->mo_flags |= MO_IS_LOOP;
739         }
740
741         strscat(default_mountopts, ",errors=remount-ro", default_len);
742         if (IS_MDT(ldd) || IS_MGS(ldd))
743                 strscat(always_mountopts, ",user_xattr", always_len);
744
745         return 0;
746 }
747
748 /* return canonicalized absolute pathname, even if the target file does not
749  * exist, unlike realpath */
750 static char *absolute_path(char *devname)
751 {
752         char  buf[PATH_MAX + 1];
753         char *path;
754         char *ptr;
755
756         path = malloc(PATH_MAX + 1);
757         if (path == NULL)
758                 return NULL;
759
760         if (devname[0] != '/') {
761                 if (getcwd(buf, sizeof(buf) - 1) == NULL)
762                         return NULL;
763                 strcat(buf, "/");
764                 strcat(buf, devname);
765         } else {
766                 strcpy(buf, devname);
767         }
768         /* truncate filename before calling realpath */
769         ptr = strrchr(buf, '/');
770         if (ptr == NULL) {
771                 free(path);
772                 return NULL;
773         }
774         *ptr = '\0';
775         if (path != realpath(buf, path)) {
776                 free(path);
777                 return NULL;
778         }
779         /* add the filename back */
780         strcat(path, "/");
781         strcat(path, ptr + 1);
782         return path;
783 }
784
785 /* Determine if a device is a block device (as opposed to a file) */
786 int is_block(char* devname)
787 {
788         struct stat st;
789         int     ret = 0;
790         char    *devpath;
791
792         devpath = absolute_path(devname);
793         if (devpath == NULL) {
794                 fprintf(stderr, "%s: failed to resolve path to %s\n",
795                         progname, devname);
796                 return -1;
797         }
798
799         ret = access(devname, F_OK);
800         if (ret != 0) {
801                 if (strncmp(devpath, "/dev/", 5) == 0) {
802                         /* nobody sane wants to create a loopback file under
803                          * /dev. Let's just report the device doesn't exist */
804                         fprintf(stderr, "%s: %s apparently does not exist\n",
805                                 progname, devpath);
806                         ret = -1;
807                         goto out;
808                 }
809                 ret = 0;
810                 goto out;
811         }
812         ret = stat(devpath, &st);
813         if (ret != 0) {
814                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
815                 goto out;
816         }
817         ret = S_ISBLK(st.st_mode);
818 out:
819         free(devpath);
820         return ret;
821 }
822