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