Whamcloud - gitweb
LU-1146 build: batch update copyright messages
[fs/lustre-release.git] / lustre / utils / mkfs_lustre.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011, Whamcloud, Inc.
33  */
34 /*
35  * This file is part of Lustre, http://www.lustre.org/
36  * Lustre is a trademark of Sun Microsystems, Inc.
37  *
38  * lustre/utils/mkfs_lustre.c
39  *
40  * Author: Nathan Rutman <nathan@clusterfs.com>
41 */
42
43 /* This source file is compiled into both mkfs.lustre and tunefs.lustre */
44
45 #if HAVE_CONFIG_H
46 #  include "config.h"
47 #endif /* HAVE_CONFIG_H */
48
49 #ifndef _GNU_SOURCE
50 #define _GNU_SOURCE
51 #endif
52 #include <stdlib.h>
53 #include <stdio.h>
54 #include <unistd.h>
55 #include <fcntl.h>
56 #include <stdarg.h>
57 #include <mntent.h>
58
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 #include <sys/mount.h>
62 #include <sys/utsname.h>
63
64 #include <string.h>
65 #include <getopt.h>
66 #include <limits.h>
67 #include <ctype.h>
68
69 #ifdef __linux__
70 /* libcfs.h is not really needed here, but on SLES10/PPC, fs.h includes idr.h
71  * which requires BITS_PER_LONG to be defined */
72 #include <libcfs/libcfs.h>
73 #ifndef BLKGETSIZE64
74 #include <linux/fs.h> /* for BLKGETSIZE64 */
75 #endif
76 #include <linux/version.h>
77 #endif
78 #include <lustre_disk.h>
79 #include <lustre_param.h>
80 #include <lnet/lnetctl.h>
81 #include <lustre_ver.h>
82 #include "mount_utils.h"
83
84 #ifndef PATH_MAX
85 #define PATH_MAX 4096
86 #endif
87
88 #define MAX_LOOP_DEVICES 16
89 #define L_BLOCK_SIZE 4096
90 #define INDEX_UNASSIGNED 0xFFFF
91 #define MO_IS_LOOP     0x01
92 #define MO_FORCEFORMAT 0x02
93
94 /* used to describe the options to format the lustre disk, not persistent */
95 struct mkfs_opts {
96         struct lustre_disk_data mo_ldd; /* to be written in MOUNT_DATA_FILE */
97         char  mo_device[128];           /* disk device name */
98         char  mo_loopdev[128];          /* in case a loop dev is needed */
99         char  mo_mkfsopts[512];         /* options to the backing-store mkfs */
100         __u64 mo_device_sz;             /* in KB */
101         int   mo_stripe_count;
102         int   mo_flags;
103         int   mo_mgs_failnodes;
104 };
105
106 char *progname;
107 int verbose = 1;
108 static int print_only = 0;
109 static int failover = 0;
110 static int upgrade_to_18 = 0;
111
112 void usage(FILE *out)
113 {
114         fprintf(out, "%s v"LUSTRE_VERSION_STRING"\n", progname);
115         fprintf(out, "usage: %s <target types> [options] <device>\n", progname);
116         fprintf(out,
117                 "\t<device>:block device or file (e.g /dev/sda or /tmp/ost1)\n"
118                 "\ttarget types:\n"
119                 "\t\t--ost: object storage, mutually exclusive with mdt,mgs\n"
120                 "\t\t--mdt: metadata storage, mutually exclusive with ost\n"
121                 "\t\t--mgs: configuration management service - one per site\n"
122                 "\toptions (in order of popularity):\n"
123                 "\t\t--mgsnode=<nid>[,<...>] : NID(s) of a remote mgs node\n"
124                 "\t\t\trequired for all targets other than the mgs node\n"
125                 "\t\t--fsname=<filesystem_name> : default is 'lustre'\n"
126                 "\t\t--failnode=<nid>[,<...>] : NID(s) of a failover partner\n"
127                 "\t\t\tcannot be used with --servicenode\n"
128                 "\t\t--servicenode=<nid>[,<...>] : NID(s) of all service partners\n"
129                 "\t\t\ttreat all nodes as equal service node, cannot be used with --failnode\n"
130                 "\t\t--param <key>=<value> : set a permanent parameter\n"
131                 "\t\t\te.g. --param sys.timeout=40\n"
132                 "\t\t\t     --param lov.stripesize=2M\n"
133                 "\t\t--index=#N : target index (i.e. ost index within lov)\n"
134                 "\t\t--comment=<user comment>: arbitrary string (%d bytes)\n"
135                 "\t\t--mountfsoptions=<opts> : permanent mount options\n"
136                 "\t\t--network=<net>[,<...>] : restrict OST/MDT to network(s)\n"
137 #ifndef TUNEFS
138                 "\t\t--backfstype=<fstype> : backing fs type (ext3, ldiskfs)\n"
139                 "\t\t--device-size=#N(KB) : device size for loop devices\n"
140                 "\t\t--mkfsoptions=<opts> : format options\n"
141                 "\t\t--reformat: overwrite an existing disk\n"
142                 "\t\t--stripe-count-hint=#N : for optimizing MDT inode size\n"
143                 "\t\t--iam-dir: use IAM directory format, not ext3 compatible\n"
144 #else
145                 "\t\t--erase-params : erase all old parameter settings\n"
146                 "\t\t--nomgs: turn off MGS service on this MDT\n"
147                 "\t\t--writeconf: erase all config logs for this fs.\n"
148 #endif
149                 "\t\t--dryrun: just report what we would do; "
150                 "don't write to disk\n"
151                 "\t\t--verbose : e.g. show mkfs progress\n"
152                 "\t\t--quiet\n",
153                 (int)sizeof(((struct lustre_disk_data *)0)->ldd_userdata));
154         return;
155 }
156
157 #define vprint if (verbose > 0) printf
158 #define verrprint if (verbose >= 0) printf
159
160 /*================ utility functions =====================*/
161
162 char *strscat(char *dst, char *src, int buflen) {
163         dst[buflen - 1] = 0;
164         if (strlen(dst) + strlen(src) >= buflen) {
165                 fprintf(stderr, "string buffer overflow (max %d): '%s' + '%s'"
166                         "\n", buflen, dst, src);
167                 exit(EOVERFLOW);
168         }
169         return strcat(dst, src);
170
171 }
172
173 char *strscpy(char *dst, char *src, int buflen) {
174         dst[0] = 0;
175         return strscat(dst, src, buflen);
176 }
177
178 inline unsigned int
179 dev_major (unsigned long long int __dev)
180 {
181         return ((__dev >> 8) & 0xfff) | ((unsigned int) (__dev >> 32) & ~0xfff);
182 }
183
184 inline unsigned int
185 dev_minor (unsigned long long int __dev)
186 {
187         return (__dev & 0xff) | ((unsigned int) (__dev >> 12) & ~0xff);
188 }
189
190 int get_os_version()
191 {
192         static int version = 0;
193
194         if (!version) {
195                 int fd;
196                 char release[4] = "";
197
198                 fd = open("/proc/sys/kernel/osrelease", O_RDONLY);
199                 if (fd < 0) {
200                         fprintf(stderr, "%s: Warning: Can't resolve kernel "
201                                 "version, assuming 2.6\n", progname);
202                 } else {
203                         if (read(fd, release, 4) < 0) {
204                                 fprintf(stderr, "reading from /proc/sys/kernel"
205                                         "/osrelease: %s\n", strerror(errno));
206                                 close(fd);
207                                 exit(-1);
208                         }
209                         close(fd);
210                 }
211                 if (strncmp(release, "2.4.", 4) == 0)
212                         version = 24;
213                 else
214                         version = 26;
215         }
216         return version;
217 }
218
219 static int check_mtab_entry(char *spec)
220 {
221         FILE *fp;
222         struct mntent *mnt;
223
224         fp = setmntent(MOUNTED, "r");
225         if (fp == NULL)
226                 return(0);
227
228         while ((mnt = getmntent(fp)) != NULL) {
229                 if (strcmp(mnt->mnt_fsname, spec) == 0) {
230                         endmntent(fp);
231                         fprintf(stderr, "%s: according to %s %s is "
232                                 "already mounted on %s\n",
233                                 progname, MOUNTED, spec, mnt->mnt_dir);
234                         return(EEXIST);
235                 }
236         }
237         endmntent(fp);
238
239         return(0);
240 }
241
242 /*============ disk dev functions ===================*/
243
244 /* Setup a file in the first unused loop_device */
245 int loop_setup(struct mkfs_opts *mop)
246 {
247         char loop_base[20];
248         char l_device[64];
249         int i, ret = 0;
250
251         /* Figure out the loop device names */
252         if (!access("/dev/loop0", F_OK | R_OK)) {
253                 strcpy(loop_base, "/dev/loop\0");
254         } else if (!access("/dev/loop/0", F_OK | R_OK)) {
255                 strcpy(loop_base, "/dev/loop/\0");
256         } else {
257                 fprintf(stderr, "%s: can't access loop devices\n", progname);
258                 return EACCES;
259         }
260
261         /* Find unused loop device */
262         for (i = 0; i < MAX_LOOP_DEVICES; i++) {
263                 char cmd[PATH_MAX];
264                 int cmdsz = sizeof(cmd);
265
266                 sprintf(l_device, "%s%d", loop_base, i);
267                 if (access(l_device, F_OK | R_OK))
268                         break;
269                 snprintf(cmd, cmdsz, "losetup %s > /dev/null 2>&1", l_device);
270                 ret = system(cmd);
271
272                 /* losetup gets 1 (ret=256) for non-set-up device */
273                 if (ret) {
274                         /* Set up a loopback device to our file */
275                         snprintf(cmd, cmdsz, "losetup %s %s", l_device,
276                                  mop->mo_device);
277                         ret = run_command(cmd, cmdsz);
278                         if (ret == 256)
279                                 /* someone else picked up this loop device
280                                  * behind our back */
281                                 continue;
282                         if (ret) {
283                                 fprintf(stderr, "%s: error %d on losetup: %s\n",
284                                         progname, ret, strerror(ret));
285                                 return ret;
286                         }
287                         strscpy(mop->mo_loopdev, l_device,
288                                 sizeof(mop->mo_loopdev));
289                         return ret;
290                 }
291         }
292
293         fprintf(stderr, "%s: out of loop devices!\n", progname);
294         return EMFILE;
295 }
296
297 int loop_cleanup(struct mkfs_opts *mop)
298 {
299         char cmd[150];
300         int ret = 1;
301         if ((mop->mo_flags & MO_IS_LOOP) && *mop->mo_loopdev) {
302                 sprintf(cmd, "losetup -d %s", mop->mo_loopdev);
303                 ret = run_command(cmd, sizeof(cmd));
304         }
305         return ret;
306 }
307
308 /* Determine if a device is a block device (as opposed to a file) */
309 int is_block(char* devname)
310 {
311         struct stat st;
312         int ret = 0;
313
314         ret = access(devname, F_OK);
315         if (ret != 0)
316                 return 0;
317         ret = stat(devname, &st);
318         if (ret != 0) {
319                 fprintf(stderr, "%s: cannot stat %s\n", progname, devname);
320                 return -1;
321         }
322         return S_ISBLK(st.st_mode);
323 }
324
325 __u64 get_device_size(char* device)
326 {
327         int ret, fd;
328         __u64 size = 0;
329
330         fd = open(device, O_RDONLY);
331         if (fd < 0) {
332                 fprintf(stderr, "%s: cannot open %s: %s\n",
333                         progname, device, strerror(errno));
334                 return 0;
335         }
336
337 #ifdef BLKGETSIZE64
338         /* size in bytes. bz5831 */
339         ret = ioctl(fd, BLKGETSIZE64, (void*)&size);
340 #else
341         {
342                 __u32 lsize = 0;
343                 /* size in blocks */
344                 ret = ioctl(fd, BLKGETSIZE, (void*)&lsize);
345                 size = (__u64)lsize * 512;
346         }
347 #endif
348         close(fd);
349         if (ret < 0) {
350                 fprintf(stderr, "%s: size ioctl failed: %s\n",
351                         progname, strerror(errno));
352                 return 0;
353         }
354
355         vprint("device size = "LPU64"MB\n", size >> 20);
356         /* return value in KB */
357         return size >> 10;
358 }
359
360 int loop_format(struct mkfs_opts *mop)
361 {
362         int ret = 0;
363
364         if (mop->mo_device_sz == 0) {
365                 fatal();
366                 fprintf(stderr, "loop device requires a --device-size= "
367                         "param\n");
368                 return EINVAL;
369         }
370
371         ret = creat(mop->mo_device, S_IRUSR|S_IWUSR);
372         if (ret < 0) {
373                 ret = errno;
374                 fprintf(stderr, "%s: Unable to create backing store: %d\n",
375                         progname, ret);
376         } else {
377                 close(ret);
378         }
379
380         ret = truncate(mop->mo_device, mop->mo_device_sz * 1024);
381         if (ret != 0) {
382                 ret = errno;
383                 fprintf(stderr, "%s: Unable to truncate backing store: %d\n",
384                         progname, ret);
385         }
386
387         return ret;
388 }
389
390 /* Display the need for the latest e2fsprogs to be installed. make_backfs
391  * indicates if the caller is make_lustre_backfs() or not. */
392 static void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
393 {
394         static int msg_displayed;
395
396         if (msg_displayed) {
397                 fprintf(stderr, "WARNING: %s does not support %s "
398                         "feature.\n\n", E2FSPROGS, feature);
399                 return;
400         }
401
402         msg_displayed++;
403
404         fprintf(stderr, "WARNING: The %s package currently installed on "
405                 "your system does not support \"%s\" feature.\n",
406                 E2FSPROGS, feature);
407 #if !(HAVE_LDISKFSPROGS)
408         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
409                 "http://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
410                 "to enable this feature.\n");
411 #endif
412         if (make_backfs)
413                 fprintf(stderr, "Feature will not be enabled until %s"
414                         "is updated and '%s -O %s %%{device}' "
415                         "is run.\n\n", E2FSPROGS, TUNE2FS, feature);
416 }
417
418 /* Check whether the file exists in the device */
419 static int file_in_dev(char *file_name, char *dev_name)
420 {
421         FILE *fp;
422         char debugfs_cmd[256];
423         unsigned int inode_num;
424         int i;
425
426         /* Construct debugfs command line. */
427         snprintf(debugfs_cmd, sizeof(debugfs_cmd),
428                 "%s -c -R 'stat %s' '%s' 2>&1 | egrep '(Inode|unsupported)'",
429                 DEBUGFS, file_name, dev_name);
430
431         fp = popen(debugfs_cmd, "r");
432         if (!fp) {
433                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
434                 return 0;
435         }
436
437         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
438                 pclose(fp);
439                 return 1;
440         }
441         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd), fp);
442         if (i) {
443                 debugfs_cmd[i] = 0;
444                 fprintf(stderr, "%s", debugfs_cmd);
445                 if (strstr(debugfs_cmd, "unsupported feature")) {
446                           disp_old_e2fsprogs_msg("an unknown", 0);
447                 }
448                 pclose(fp);
449                 return -1;
450         }
451         pclose(fp);
452         return 0;
453 }
454
455 /* Check whether the device has already been used with lustre */
456 static int is_lustre_target(struct mkfs_opts *mop)
457 {
458         int rc;
459
460         vprint("checking for existing Lustre data: ");
461
462         if ((rc = file_in_dev(MOUNT_DATA_FILE, mop->mo_device))) {
463                 vprint("found %s\n",
464                        (rc == 1) ? MOUNT_DATA_FILE : "extents");
465                  /* in the -1 case, 'extents' means this really IS a lustre
466                     target */
467                 return rc;
468         }
469
470         if ((rc = file_in_dev(LAST_RCVD, mop->mo_device))) {
471                 vprint("found %s\n", LAST_RCVD);
472                 return rc;
473         }
474
475         vprint("not found\n");
476         return 0; /* The device is not a lustre target. */
477 }
478
479 /* Check if a certain feature is supported by e2fsprogs.
480  * Firstly we try to use "debugfs supported_features" command to check if
481  * the feature is supported. If this fails we try to set this feature with
482  * mke2fs to check for its support. */
483 static int is_e2fsprogs_feature_supp(const char *feature)
484 {
485         static char supp_features[4096] = "";
486         FILE *fp;
487         char cmd[PATH_MAX];
488         char imgname[] = "/tmp/test-img-XXXXXX";
489         int fd = -1;
490         int ret = 1;
491
492         if (supp_features[0] == '\0') {
493                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
494                          DEBUGFS);
495
496                 /* Using popen() instead of run_command() since debugfs does
497                  * not return proper error code if command is not supported */
498                 fp = popen(cmd, "r");
499                 if (!fp) {
500                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
501                         return 0;
502                 }
503                 ret = fread(supp_features, 1, sizeof(supp_features), fp);
504                 fclose(fp);
505         }
506         if (ret > 0 && strstr(supp_features,
507                               strncmp(feature, "-O ", 3) ? feature : feature+3))
508                 return 0;
509
510         if ((fd = mkstemp(imgname)) < 0)
511                 return -1;
512         else
513                 close(fd);
514
515         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
516                  MKE2FS, feature, imgname);
517         /* run_command() displays the output of mke2fs when it fails for
518          * some feature, so use system() directly */
519         ret = system(cmd);
520         unlink(imgname);
521
522         return ret;
523 }
524
525 /**
526  * append_unique: append @key or @key=@val pair to @buf only if @key does not
527  *                exists
528  *      @buf: buffer to hold @key or @key=@val
529  *      @prefix: prefix string before @key
530  *      @key: key string
531  *      @val: value string if it's a @key=@val pair
532  */
533 static void append_unique(char *buf, char *prefix, char *key, char *val,
534                           size_t maxbuflen)
535 {
536         char *anchor, *end;
537         int  len;
538
539         if (key == NULL)
540                 return;
541
542         anchor = end = strstr(buf, key);
543         /* try to find exact match string in @buf */
544         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
545                 ++end;
546         len = end - anchor;
547         if (anchor == NULL || strlen(key) != len ||
548             strncmp(anchor, key, len) != 0) {
549                 if (prefix != NULL)
550                         strscat(buf, prefix, maxbuflen);
551
552                 strscat(buf, key, maxbuflen);
553                 if (val != NULL) {
554                         strscat(buf, "=", maxbuflen);
555                         strscat(buf, val, maxbuflen);
556                 }
557         }
558 }
559
560 static void enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
561                                          size_t maxbuflen, int user_spec)
562 {
563         if (IS_OST(&mop->mo_ldd)) {
564                 append_unique(anchor, user_spec ? "," : " -O ",
565                               "extents", NULL, sizeof(mop->mo_mkfsopts));
566                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
567         } else if (IS_MDT(&mop->mo_ldd)) {
568                 append_unique(anchor, user_spec ? "," : " -O ",
569                               "dirdata", NULL, maxbuflen);
570                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
571         } else {
572                 append_unique(anchor, user_spec ? "," : " -O ",
573                               "uninit_bg", NULL, maxbuflen);
574         }
575
576         /* Multiple mount protection enabled only if failover node specified */
577         if (failover) {
578                 if (is_e2fsprogs_feature_supp("-O mmp") == 0)
579                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
580                 else
581                         disp_old_e2fsprogs_msg("mmp", 1);
582         }
583
584         /* Allow more than 65000 subdirectories */
585         if (is_e2fsprogs_feature_supp("-O dir_nlink") == 0)
586                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
587
588 #ifdef HAVE_EXT4_LDISKFS
589         /* The following options are only valid for ext4-based ldiskfs.
590          * If --backfstype=ext3 is specified, do not enable them. */
591         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
592                 return;
593
594         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
595         if (is_e2fsprogs_feature_supp("-O huge_file") == 0)
596                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
597
598         /* Enable large block addresses if the LUN is over 2^32 blocks. */
599         if (mop->mo_device_sz / (L_BLOCK_SIZE >> 10) >= 0x100002000ULL &&
600                     is_e2fsprogs_feature_supp("-O 64bit") == 0)
601                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
602
603         /* Cluster inode/block bitmaps and inode table for more efficient IO.
604          * Align the flex groups on a 1MB boundary for better performance. */
605         /* This -O feature needs to go last, since it adds the "-G" option. */
606         if (is_e2fsprogs_feature_supp("-O flex_bg") == 0) {
607                 char tmp_buf[64];
608
609                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
610
611                 if (IS_OST(&mop->mo_ldd)) {
612                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
613                                  (1 << 20) / L_BLOCK_SIZE);
614                         strscat(anchor, tmp_buf, maxbuflen);
615                 }
616         }
617         /* Don't add any more "-O" options here, see last comment above */
618 #endif
619 }
620
621 /**
622  * moveopts_to_end: find the option string, move remaining strings to
623  *                  where option string starts, and append the option
624  *                  string at the end
625  *      @start: where the option string starts before the move
626  *      RETURN: where the option string starts after the move
627  */
628 static char *moveopts_to_end(char *start)
629 {
630         char save[512];
631         char *end, *idx;
632
633         /* skip whitespace before options */
634         end = start + 2;
635         while (*end == ' ')
636                 ++end;
637
638         /* find end of option characters */
639         while (*end != ' ' && *end != '\0')
640                 ++end;
641
642         /* save options */
643         strncpy(save, start, end - start);
644         save[end - start] = '\0';
645
646         /* move remaining options up front */
647         if (*end)
648                 memmove(start, end, strlen(end));
649         *(start + strlen(end)) = '\0';
650
651         /* append the specified options */
652         if (*(start + strlen(start) - 1) != ' ')
653                 strcat(start, " ");
654         idx = start + strlen(start);
655         strcat(start, save);
656
657         return idx;
658 }
659
660 /* Build fs according to type */
661 int make_lustre_backfs(struct mkfs_opts *mop)
662 {
663         __u64 device_sz = mop->mo_device_sz, block_count = 0;
664         char mkfs_cmd[PATH_MAX];
665         char buf[64];
666         char *start;
667         char *dev;
668         int ret = 0, ext_opts = 0;
669         size_t maxbuflen;
670
671         if (!(mop->mo_flags & MO_IS_LOOP)) {
672                 mop->mo_device_sz = get_device_size(mop->mo_device);
673
674                 if (mop->mo_device_sz == 0)
675                         return ENODEV;
676
677                 /* Compare to real size */
678                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
679                         device_sz = mop->mo_device_sz;
680                 else
681                         mop->mo_device_sz = device_sz;
682         }
683
684         if (mop->mo_device_sz != 0) {
685                 if (mop->mo_device_sz < 8096){
686                         fprintf(stderr, "%s: size of filesystem must be larger "
687                                 "than 8MB, but is set to %lldKB\n",
688                                 progname, (long long)mop->mo_device_sz);
689                         return EINVAL;
690                 }
691                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
692                 /* If the LUN size is just over 2^32 blocks, limit the
693                  * filesystem size to 2^32-1 blocks to avoid problems with
694                  * ldiskfs/mkfs not handling this size.  Bug 22906 */
695                 if (block_count > 0xffffffffULL && block_count < 0x100002000ULL)
696                         block_count = 0xffffffffULL;
697         }
698
699         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
700             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
701             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
702                 long inode_size = 0;
703
704                 /* Journal size in MB */
705                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
706                         /* Choose our own default journal size */
707                         long journal_sz = 0, max_sz;
708                         if (device_sz > 1024 * 1024) /* 1GB */
709                                 journal_sz = (device_sz / 102400) * 4;
710                         /* cap journal size at 1GB */
711                         if (journal_sz > 1024L)
712                                 journal_sz = 1024L;
713                         /* man mkfs.ext3 */
714                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
715                         if (journal_sz > max_sz)
716                                 journal_sz = max_sz;
717                         if (journal_sz) {
718                                 sprintf(buf, " -J size=%ld", journal_sz);
719                                 strscat(mop->mo_mkfsopts, buf,
720                                         sizeof(mop->mo_mkfsopts));
721                         }
722                 }
723
724                 /* Inode size (for extended attributes).  The LOV EA size is
725                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
726                  * and we want some margin above that for ACLs, other EAs... */
727                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
728                         if (IS_MDT(&mop->mo_ldd)) {
729                                 if (mop->mo_stripe_count > 72)
730                                         inode_size = 512; /* bz 7241 */
731                                         /* see also "-i" below for EA blocks */
732                                 else if (mop->mo_stripe_count > 32)
733                                         inode_size = 2048;
734                                 else if (mop->mo_stripe_count > 10)
735                                         inode_size = 1024;
736                                 else
737                                         inode_size = 512;
738                         } else if (IS_OST(&mop->mo_ldd)) {
739                                 /* We store MDS FID and OST objid in EA on OST
740                                  * we need to make inode bigger as well. */
741                                 inode_size = 256;
742                         }
743
744                         if (inode_size > 0) {
745                                 sprintf(buf, " -I %ld", inode_size);
746                                 strscat(mop->mo_mkfsopts, buf,
747                                         sizeof(mop->mo_mkfsopts));
748                         }
749                 }
750
751                 /* Bytes_per_inode: disk size / num inodes */
752                 if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
753                     strstr(mop->mo_mkfsopts, "-N") == NULL) {
754                         long bytes_per_inode = 0;
755
756                         /* Allocate more inodes on MDT devices.  There is
757                          * no data stored on the MDT, and very little extra
758                          * metadata beyond the inode.  It could go down as
759                          * low as 1024 bytes, but this is conservative.
760                          * Account for external EA blocks for wide striping. */
761                         if (IS_MDT(&mop->mo_ldd)) {
762                                 bytes_per_inode = inode_size + 1536;
763
764                                 if (mop->mo_stripe_count > 72) {
765                                         int extra = mop->mo_stripe_count * 24;
766                                         extra = ((extra - 1) | 4095) + 1;
767                                         bytes_per_inode += extra;
768                                 }
769                         }
770
771                         /* Allocate fewer inodes on large OST devices.  Most
772                          * filesystems can be much more aggressive than even
773                          * this, but it is impossible to know in advance. */
774                         if (IS_OST(&mop->mo_ldd)) {
775                                 /* OST > 16TB assume average file size 1MB */
776                                 if (device_sz > (16ULL << 30))
777                                         bytes_per_inode = 1024 * 1024;
778                                 /* OST > 4TB assume average file size 512kB */
779                                 else if (device_sz > (4ULL << 30))
780                                         bytes_per_inode = 512 * 1024;
781                                 /* OST > 1TB assume average file size 256kB */
782                                 else if (device_sz > (1ULL << 30))
783                                         bytes_per_inode = 256 * 1024;
784                                 /* OST > 10GB assume average file size 64kB,
785                                  * plus a bit so that inodes will fit into a
786                                  * 256x flex_bg without overflowing */
787                                 else if (device_sz > (10ULL << 20))
788                                         bytes_per_inode = 69905;
789                         }
790
791                         if (bytes_per_inode > 0) {
792                                 sprintf(buf, " -i %ld", bytes_per_inode);
793                                 strscat(mop->mo_mkfsopts, buf,
794                                         sizeof(mop->mo_mkfsopts));
795                         }
796                 }
797
798                 if (verbose < 2) {
799                         strscat(mop->mo_mkfsopts, " -q",
800                                 sizeof(mop->mo_mkfsopts));
801                 }
802
803                 /* start handle -O mkfs options */
804                 if ((start = strstr(mop->mo_mkfsopts, "-O")) != NULL) {
805                         if (strstr(start + 2, "-O") != NULL) {
806                                 fprintf(stderr,
807                                         "%s: don't specify multiple -O options\n",
808                                         progname);
809                                 return EINVAL;
810                         }
811                         start = moveopts_to_end(start);
812                         maxbuflen = sizeof(mop->mo_mkfsopts) -
813                                     (start - mop->mo_mkfsopts) - strlen(start);
814                         enable_default_ext4_features(mop, start, maxbuflen, 1);
815                 } else {
816                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts),
817                         maxbuflen = sizeof(mop->mo_mkfsopts) -
818                                     strlen(mop->mo_mkfsopts);
819                         enable_default_ext4_features(mop, start, maxbuflen, 0);
820                 }
821                 /* end handle -O mkfs options */
822
823                 /* start handle -E mkfs options */
824                 if ((start = strstr(mop->mo_mkfsopts, "-E")) != NULL) {
825                         if (strstr(start + 2, "-E") != NULL) {
826                                 fprintf(stderr,
827                                         "%s: don't specify multiple -E options\n",
828                                         progname);
829                                 return EINVAL;
830                         }
831                         start = moveopts_to_end(start);
832                         maxbuflen = sizeof(mop->mo_mkfsopts) -
833                                     (start - mop->mo_mkfsopts) - strlen(start);
834                         ext_opts = 1;
835                 } else {
836                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
837                         maxbuflen = sizeof(mop->mo_mkfsopts) -
838                                     strlen(mop->mo_mkfsopts);
839                 }
840
841                 /* In order to align the filesystem metadata on 1MB boundaries,
842                  * give a resize value that will reserve a power-of-two group
843                  * descriptor blocks, but leave one block for the superblock.
844                  * Only useful for filesystems with < 2^32 blocks due to resize
845                  * limitations. */
846                 if (IS_OST(&mop->mo_ldd) && mop->mo_device_sz > 100 * 1024 &&
847                     mop->mo_device_sz * 1024 / L_BLOCK_SIZE <= 0xffffffffULL) {
848                         unsigned group_blocks = L_BLOCK_SIZE * 8;
849                         unsigned desc_per_block = L_BLOCK_SIZE / 32;
850                         unsigned resize_blks;
851
852                         resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
853                         snprintf(buf, sizeof(buf), "%u", resize_blks);
854                         append_unique(start, ext_opts ? "," : " -E ",
855                                       "resize", buf, maxbuflen);
856                         ext_opts = 1;
857                 }
858
859                 /* Avoid zeroing out the full journal - speeds up mkfs */
860                 if (is_e2fsprogs_feature_supp("-E lazy_journal_init") == 0)
861                         append_unique(start, ext_opts ? "," : " -E ",
862                                       "lazy_journal_init", NULL, maxbuflen);
863                 /* end handle -E mkfs options */
864
865                 /* Allow reformat of full devices (as opposed to
866                    partitions.)  We already checked for mounted dev. */
867                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
868
869                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
870                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
871                          mop->mo_ldd.ldd_svname);
872         } else {
873                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
874                         progname, mop->mo_ldd.ldd_mount_type,
875                         MT_STR(&mop->mo_ldd));
876                 return EINVAL;
877         }
878
879         /* For loop device format the dev, not the filename */
880         dev = mop->mo_device;
881         if (mop->mo_flags & MO_IS_LOOP)
882                 dev = mop->mo_loopdev;
883
884         vprint("formatting backing filesystem %s on %s\n",
885                MT_STR(&mop->mo_ldd), dev);
886         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
887         vprint("\t4k blocks     "LPU64"\n", block_count);
888         vprint("\toptions       %s\n", mop->mo_mkfsopts);
889
890         /* mkfs_cmd's trailing space is important! */
891         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
892         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
893         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
894         if (block_count != 0) {
895                 sprintf(buf, " "LPU64, block_count);
896                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
897         }
898
899         vprint("mkfs_cmd = %s\n", mkfs_cmd);
900         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
901         if (ret) {
902                 fatal();
903                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
904         }
905         return ret;
906 }
907
908 /* ==================== Lustre config functions =============*/
909
910 void print_ldd(char *str, struct lustre_disk_data *ldd)
911 {
912         printf("\n   %s:\n", str);
913         printf("Target:     %s\n", ldd->ldd_svname);
914         if (ldd->ldd_svindex == INDEX_UNASSIGNED)
915                 printf("Index:      unassigned\n");
916         else
917                 printf("Index:      %d\n", ldd->ldd_svindex);
918         if (ldd->ldd_uuid[0])
919                 printf("UUID:       %s\n", (char *)ldd->ldd_uuid);
920         printf("Lustre FS:  %s\n", ldd->ldd_fsname);
921         printf("Mount type: %s\n", MT_STR(ldd));
922         printf("Flags:      %#x\n", ldd->ldd_flags);
923         printf("              (%s%s%s%s%s%s%s%s%s%s)\n",
924                IS_MDT(ldd) ? "MDT ":"",
925                IS_OST(ldd) ? "OST ":"",
926                IS_MGS(ldd) ? "MGS ":"",
927                ldd->ldd_flags & LDD_F_NEED_INDEX ? "needs_index ":"",
928                ldd->ldd_flags & LDD_F_VIRGIN     ? "first_time ":"",
929                ldd->ldd_flags & LDD_F_UPDATE     ? "update ":"",
930                ldd->ldd_flags & LDD_F_WRITECONF  ? "writeconf ":"",
931                ldd->ldd_flags & LDD_F_IAM_DIR  ? "IAM_dir_format ":"",
932                ldd->ldd_flags & LDD_F_NO_PRIMNODE? "no_primnode ":"",
933                ldd->ldd_flags & LDD_F_UPGRADE14  ? "upgrade1.4 ":"");
934         printf("Persistent mount opts: %s\n", ldd->ldd_mount_opts);
935         printf("Parameters:%s\n", ldd->ldd_params);
936         if (ldd->ldd_userdata[0])
937                 printf("Comment: %s\n", ldd->ldd_userdata);
938         printf("\n");
939 }
940
941 static int touch_file(char *filename)
942 {
943         int fd;
944
945         if (filename == NULL) {
946                 return 1;
947         }
948
949         fd = open(filename, O_CREAT | O_TRUNC, 0600);
950         if (fd < 0) {
951                 return 1;
952         } else {
953                 close(fd);
954                 return 0;
955         }
956 }
957
958 /* keep it less than LL_FID_NAMELEN */
959 #define DUMMY_FILE_NAME_LEN             25
960 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
961
962 /* Need to add these many entries to this directory to make HTREE dir. */
963 #define MIN_ENTRIES_REQ_FOR_HTREE       ((L_BLOCK_SIZE / EXT3_DIRENT_SIZE))
964
965 static int add_dummy_files(char *dir)
966 {
967         char fpname[PATH_MAX];
968         int i;
969         int rc;
970
971         for (i = 0; i < MIN_ENTRIES_REQ_FOR_HTREE; i++) {
972                 snprintf(fpname, PATH_MAX, "%s/%0*d", dir,
973                          DUMMY_FILE_NAME_LEN, i);
974
975                 rc = touch_file(fpname);
976                 if (rc && rc != -EEXIST) {
977                         fprintf(stderr,
978                                 "%s: Can't create dummy file %s: %s\n",
979                                 progname, fpname , strerror(errno));
980                         return rc;
981                 }
982         }
983         return 0;
984 }
985
986 static int __l_mkdir(char * filepnm, int mode , struct mkfs_opts *mop)
987 {
988         int ret;
989
990         ret = mkdir(filepnm, mode);
991         if (ret && ret != -EEXIST)
992                 return ret;
993
994         /* IAM mode supports ext3 directories of HTREE type only. So add dummy
995          * entries to new directory to create htree type of container for
996          * this directory. */
997         if (mop->mo_ldd.ldd_flags & LDD_F_IAM_DIR)
998                 return add_dummy_files(filepnm);
999         return 0;
1000 }
1001
1002 /* Write the server config files */
1003 int write_local_files(struct mkfs_opts *mop)
1004 {
1005         char mntpt[] = "/tmp/mntXXXXXX";
1006         char filepnm[128];
1007         char *dev;
1008         FILE *filep;
1009         int ret = 0;
1010         size_t num;
1011
1012         /* Mount this device temporarily in order to write these files */
1013         if (!mkdtemp(mntpt)) {
1014                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
1015                         progname, mntpt, strerror(errno));
1016                 return errno;
1017         }
1018
1019         dev = mop->mo_device;
1020         if (mop->mo_flags & MO_IS_LOOP)
1021                 dev = mop->mo_loopdev;
1022
1023         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
1024                     mop->mo_ldd.ldd_mount_opts);
1025         if (ret) {
1026                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
1027                         progname, dev, strerror(errno));
1028                 ret = errno;
1029                 if (errno == ENODEV) {
1030                         fprintf(stderr, "Is the %s module available?\n",
1031                                 MT_STR(&mop->mo_ldd));
1032                 }
1033                 goto out_rmdir;
1034         }
1035
1036         /* Set up initial directories */
1037         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
1038         ret = __l_mkdir(filepnm, 0777, mop);
1039         if ((ret != 0) && (errno != EEXIST)) {
1040                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
1041                         progname, filepnm, strerror(errno));
1042                 goto out_umnt;
1043         } else if (errno == EEXIST) {
1044                 ret = 0;
1045         }
1046
1047         /* Save the persistent mount data into a file. Lustre must pre-read
1048            this file to get the real mount options. */
1049         vprint("Writing %s\n", MOUNT_DATA_FILE);
1050         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
1051         filep = fopen(filepnm, "w");
1052         if (!filep) {
1053                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
1054                         progname, filepnm, strerror(errno));
1055                 goto out_umnt;
1056         }
1057         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
1058         if (num < 1 && ferror(filep)) {
1059                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
1060                         progname, filepnm, strerror(errno));
1061                 goto out_umnt;
1062         }
1063         fclose(filep);
1064         /* COMPAT_146 */
1065 #ifdef TUNEFS
1066         /* Check for upgrade */
1067         if ((mop->mo_ldd.ldd_flags & (LDD_F_UPGRADE14 | LDD_F_SV_TYPE_MGS))
1068             == (LDD_F_UPGRADE14 | LDD_F_SV_TYPE_MGS)) {
1069                 char cmd[128];
1070                 char *term;
1071                 int cmdsz = sizeof(cmd);
1072                 vprint("Copying old logs\n");
1073
1074                 /* Copy the old client log to fsname-client */
1075                 sprintf(filepnm, "%s/%s/%s-client",
1076                         mntpt, MOUNT_CONFIGS_DIR, mop->mo_ldd.ldd_fsname);
1077                 snprintf(cmd, cmdsz, "cp %s/%s/client %s", mntpt, MDT_LOGS_DIR,
1078                          filepnm);
1079                 ret = run_command(cmd, cmdsz);
1080                 if (ret) {
1081                         fprintf(stderr, "%s: Can't copy 1.4 config %s/client "
1082                                 "(%d)\n", progname, MDT_LOGS_DIR, ret);
1083                         fprintf(stderr, "mount -t ldiskfs %s somewhere, "
1084                                 "find the client log for fs %s and "
1085                                 "copy it manually into %s/%s-client, "
1086                                 "then umount.\n",
1087                                 mop->mo_device,
1088                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
1089                                 mop->mo_ldd.ldd_fsname);
1090                         goto out_umnt;
1091                 }
1092
1093                 /* We need to use the old mdt log because otherwise mdt won't
1094                    have complete lov if old clients connect before all
1095                    servers upgrade. */
1096                 /* Copy the old mdt log to fsname-MDT0000 (get old
1097                    name from mdt_UUID) */
1098                 ret = 1;
1099                 strscpy(filepnm, (char *)mop->mo_ldd.ldd_uuid, sizeof(filepnm));
1100                 term = strstr(filepnm, "_UUID");
1101                 if (term) {
1102                         *term = '\0';
1103                         snprintf(cmd, cmdsz, "cp %s/%s/%s %s/%s/%s",
1104                                  mntpt, MDT_LOGS_DIR, filepnm,
1105                                  mntpt, MOUNT_CONFIGS_DIR,
1106                                  mop->mo_ldd.ldd_svname);
1107                         ret = run_command(cmd, cmdsz);
1108                 }
1109                 if (ret) {
1110                         fprintf(stderr, "%s: Can't copy 1.4 config %s/%s "
1111                                 "(%d)\n", progname, MDT_LOGS_DIR, filepnm, ret);
1112                         fprintf(stderr, "mount -t ext3 %s somewhere, "
1113                                 "find the MDT log for fs %s and "
1114                                 "copy it manually into %s/%s, "
1115                                 "then umount.\n",
1116                                 mop->mo_device,
1117                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
1118                                 mop->mo_ldd.ldd_svname);
1119                         goto out_umnt;
1120                 }
1121         }
1122 #endif
1123         /* end COMPAT_146 */
1124
1125 out_umnt:
1126         umount(mntpt);
1127 out_rmdir:
1128         rmdir(mntpt);
1129         return ret;
1130 }
1131
1132 int read_local_files(struct mkfs_opts *mop)
1133 {
1134         char tmpdir[] = "/tmp/dirXXXXXX";
1135         char cmd[PATH_MAX];
1136         char filepnm[128];
1137         char *dev;
1138         FILE *filep;
1139         int ret = 0;
1140         int cmdsz = sizeof(cmd);
1141
1142         /* Make a temporary directory to hold Lustre data files. */
1143         if (!mkdtemp(tmpdir)) {
1144                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
1145                         progname, tmpdir, strerror(errno));
1146                 return errno;
1147         }
1148
1149         dev = mop->mo_device;
1150
1151         /* TODO: it's worth observing the get_mountdata() function that is
1152                  in mount_utils.c for getting the mountdata out of the
1153                  filesystem */
1154
1155         /* Construct debugfs command line. */
1156         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
1157                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
1158
1159         ret = run_command(cmd, cmdsz);
1160         if (ret)
1161                 verrprint("%s: Unable to dump %s dir (%d)\n",
1162                           progname, MOUNT_CONFIGS_DIR, ret);
1163
1164         sprintf(filepnm, "%s/mountdata", tmpdir);
1165         filep = fopen(filepnm, "r");
1166         if (filep) {
1167                 size_t num_read;
1168                 vprint("Reading %s\n", MOUNT_DATA_FILE);
1169                 num_read = fread(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
1170                 if (num_read < 1 && ferror(filep)) {
1171                         fprintf(stderr, "%s: Unable to read from file %s: %s\n",
1172                                 progname, filepnm, strerror(errno));
1173                         goto out_close;
1174                 }
1175         } else {
1176                 /* COMPAT_146 */
1177                 /* Try to read pre-1.6 config from last_rcvd */
1178                 struct lr_server_data lsd;
1179                 verrprint("%s: Unable to read %d.%d config %s.\n",
1180                           progname, LUSTRE_MAJOR, LUSTRE_MINOR, filepnm);
1181
1182                 verrprint("Trying 1.4 config from last_rcvd\n");
1183                 sprintf(filepnm, "%s/%s", tmpdir, LAST_RCVD);
1184
1185                 /* Construct debugfs command line. */
1186                 snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s' %s",
1187                          DEBUGFS, LAST_RCVD, filepnm, dev);
1188
1189                 ret = run_command(cmd, cmdsz);
1190                 if (ret) {
1191                         fprintf(stderr, "%s: Unable to dump %s file (%d)\n",
1192                                 progname, LAST_RCVD, ret);
1193                         goto out_rmdir;
1194                 }
1195
1196                 filep = fopen(filepnm, "r");
1197                 if (!filep) {
1198                         fprintf(stderr, "%s: Unable to open %s: %s\n",
1199                                 progname, filepnm, strerror(errno));
1200                         ret = errno;
1201                         verrprint("Contents of %s:\n", tmpdir);
1202                         verbose+=2;
1203                         snprintf(cmd, cmdsz, "ls -l %s/", tmpdir);
1204                         run_command(cmd, cmdsz);
1205                         verrprint("Contents of disk:\n");
1206                         snprintf(cmd, cmdsz, "%s -c -R 'ls -l /' %s",
1207                                  DEBUGFS, dev);
1208                         run_command(cmd, cmdsz);
1209
1210                         goto out_rmdir;
1211                 }
1212                 vprint("Reading %s\n", LAST_RCVD);
1213                 ret = fread(&lsd, 1, sizeof(lsd), filep);
1214                 if (ret < sizeof(lsd)) {
1215                         fprintf(stderr, "%s: Short read (%d of %d)\n",
1216                                 progname, ret, (int)sizeof(lsd));
1217                         ret = ferror(filep);
1218                         if (ret)
1219                                 goto out_close;
1220                 }
1221                 vprint("Feature compat=%x, incompat=%x\n",
1222                        lsd.lsd_feature_compat, lsd.lsd_feature_incompat);
1223
1224                 if ((lsd.lsd_feature_compat & OBD_COMPAT_OST) ||
1225                     (lsd.lsd_feature_incompat & OBD_INCOMPAT_OST)) {
1226                         mop->mo_ldd.ldd_flags = LDD_F_SV_TYPE_OST;
1227                         mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
1228                 } else if ((lsd.lsd_feature_compat & OBD_COMPAT_MDT) ||
1229                            (lsd.lsd_feature_incompat & OBD_INCOMPAT_MDT)) {
1230                         /* We must co-locate so mgs can see old logs.
1231                            If user doesn't want this, they can copy the old
1232                            logs manually and re-tunefs. */
1233                         mop->mo_ldd.ldd_flags =
1234                                 LDD_F_SV_TYPE_MDT | LDD_F_SV_TYPE_MGS;
1235                         mop->mo_ldd.ldd_svindex = lsd.lsd_mdt_index;
1236                 } else  {
1237                         /* If neither is set, we're pre-1.4.6, make a guess. */
1238                         /* Construct debugfs command line. */
1239                         snprintf(cmd, cmdsz, "%s -c -R 'rdump /%s %s' %s",
1240                                  DEBUGFS, MDT_LOGS_DIR, tmpdir, dev);
1241                         run_command(cmd, cmdsz);
1242
1243                         sprintf(filepnm, "%s/%s", tmpdir, MDT_LOGS_DIR);
1244                         if (lsd.lsd_ost_index > 0) {
1245                                 mop->mo_ldd.ldd_flags = LDD_F_SV_TYPE_OST;
1246                                 mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
1247                         } else {
1248                                 /* If there's a LOGS dir, it's an MDT */
1249                                 if ((ret = access(filepnm, F_OK)) == 0) {
1250                                         mop->mo_ldd.ldd_flags =
1251                                         LDD_F_SV_TYPE_MDT |
1252                                         LDD_F_SV_TYPE_MGS;
1253                                         /* Old MDT's are always index 0
1254                                            (pre CMD) */
1255                                         mop->mo_ldd.ldd_svindex = 0;
1256                                 } else {
1257                                         /* The index may not be correct */
1258                                         mop->mo_ldd.ldd_flags =
1259                                         LDD_F_SV_TYPE_OST | LDD_F_NEED_INDEX;
1260                                         verrprint("OST with unknown index\n");
1261                                 }
1262                         }
1263                 }
1264
1265                 ret = 0;
1266                 memcpy(mop->mo_ldd.ldd_uuid, lsd.lsd_uuid,
1267                        sizeof(mop->mo_ldd.ldd_uuid));
1268                 mop->mo_ldd.ldd_flags |= LDD_F_UPGRADE14;
1269         }
1270         /* end COMPAT_146 */
1271 out_close:
1272         fclose(filep);
1273
1274 out_rmdir:
1275         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
1276         run_command(cmd, cmdsz);
1277         if (ret)
1278                 verrprint("Failed to read old data (%d)\n", ret);
1279         return ret;
1280 }
1281
1282
1283 void set_defaults(struct mkfs_opts *mop)
1284 {
1285         mop->mo_ldd.ldd_magic = LDD_MAGIC;
1286         mop->mo_ldd.ldd_config_ver = 1;
1287         mop->mo_ldd.ldd_flags = LDD_F_NEED_INDEX | LDD_F_UPDATE | LDD_F_VIRGIN;
1288         mop->mo_mgs_failnodes = 0;
1289         strcpy(mop->mo_ldd.ldd_fsname, "lustre");
1290         mop->mo_ldd.ldd_mount_type = LDD_MT_LDISKFS;
1291
1292         mop->mo_ldd.ldd_svindex = INDEX_UNASSIGNED;
1293         mop->mo_stripe_count = 1;
1294 }
1295
1296 static inline void badopt(const char *opt, char *type)
1297 {
1298         fprintf(stderr, "%s: '--%s' only valid for %s\n",
1299                 progname, opt, type);
1300         usage(stderr);
1301 }
1302
1303 static int add_param(char *buf, char *key, char *val)
1304 {
1305         int end = sizeof(((struct lustre_disk_data *)0)->ldd_params);
1306         int start = strlen(buf);
1307         int keylen = 0;
1308
1309         if (key)
1310                 keylen = strlen(key);
1311         if (start + 1 + keylen + strlen(val) >= end) {
1312                 fprintf(stderr, "%s: params are too long-\n%s %s%s\n",
1313                         progname, buf, key ? key : "", val);
1314                 return 1;
1315         }
1316
1317         sprintf(buf + start, " %s%s", key ? key : "", val);
1318         return 0;
1319 }
1320
1321 /* from mount_lustre */
1322 /* Get rid of symbolic hostnames for tcp, since kernel can't do lookups */
1323 #define MAXNIDSTR 1024
1324 static char *convert_hostnames(char *s1)
1325 {
1326         char *converted, *s2 = 0, *c, *end, sep;
1327         int left = MAXNIDSTR;
1328         lnet_nid_t nid;
1329
1330         converted = malloc(left);
1331         if (converted == NULL) {
1332                 return NULL;
1333         }
1334
1335         end = s1 + strlen(s1);
1336         c = converted;
1337         while ((left > 0) && (s1 < end)) {
1338                 s2 = strpbrk(s1, ",:");
1339                 if (!s2)
1340                         s2 = end;
1341                 sep = *s2;
1342                 *s2 = '\0';
1343                 nid = libcfs_str2nid(s1);
1344
1345                 if (nid == LNET_NID_ANY) {
1346                         fprintf(stderr, "%s: Can't parse NID '%s'\n",
1347                                 progname, s1);
1348                         free(converted);
1349                         return NULL;
1350                 }
1351                 if (strncmp(libcfs_nid2str(nid), "127.0.0.1",
1352                             strlen("127.0.0.1")) == 0) {
1353                         fprintf(stderr, "%s: The NID '%s' resolves to the "
1354                                 "loopback address '%s'.  Lustre requires a "
1355                                 "non-loopback address.\n",
1356                                 progname, s1, libcfs_nid2str(nid));
1357                         free(converted);
1358                         return NULL;
1359                 }
1360
1361                 c += snprintf(c, left, "%s%c", libcfs_nid2str(nid), sep);
1362                 left = converted + MAXNIDSTR - c;
1363                 s1 = s2 + 1;
1364         }
1365         return converted;
1366 }
1367
1368 int parse_opts(int argc, char *const argv[], struct mkfs_opts *mop,
1369                char **mountopts)
1370 {
1371         static struct option long_opt[] = {
1372                 {"iam-dir", 0, 0, 'a'},
1373                 {"backfstype", 1, 0, 'b'},
1374                 {"stripe-count-hint", 1, 0, 'c'},
1375                 {"comment", 1, 0, 'u'},
1376                 {"configdev", 1, 0, 'C'},
1377                 {"device-size", 1, 0, 'd'},
1378                 {"dryrun", 0, 0, 'n'},
1379                 {"erase-params", 0, 0, 'e'},
1380                 {"failnode", 1, 0, 'f'},
1381                 {"failover", 1, 0, 'f'},
1382                 {"mgs", 0, 0, 'G'},
1383                 {"help", 0, 0, 'h'},
1384                 {"index", 1, 0, 'i'},
1385                 {"mkfsoptions", 1, 0, 'k'},
1386                 {"mgsnode", 1, 0, 'm'},
1387                 {"mgsnid", 1, 0, 'm'},
1388                 {"mdt", 0, 0, 'M'},
1389                 {"fsname",1, 0, 'L'},
1390                 {"noformat", 0, 0, 'n'},
1391                 {"nomgs", 0, 0, 'N'},
1392                 {"mountfsoptions", 1, 0, 'o'},
1393                 {"ost", 0, 0, 'O'},
1394                 {"param", 1, 0, 'p'},
1395                 {"print", 0, 0, 'n'},
1396                 {"quiet", 0, 0, 'q'},
1397                 {"reformat", 0, 0, 'r'},
1398                 {"servicenode", 1, 0, 's'},
1399                 {"verbose", 0, 0, 'v'},
1400                 {"writeconf", 0, 0, 'w'},
1401                 {"upgrade_to_18", 0, 0, 'U'},
1402                 {"network", 1, 0, 't'},
1403                 {0, 0, 0, 0}
1404         };
1405         char *optstring = "b:c:C:d:ef:Ghi:k:L:m:MnNo:Op:Pqrs:t:Uu:vw";
1406         int opt;
1407         int rc, longidx;
1408         int failnode_set = 0, servicenode_set = 0;
1409
1410         while ((opt = getopt_long(argc, argv, optstring, long_opt, &longidx)) !=
1411                EOF) {
1412                 switch (opt) {
1413                 case 'a': {
1414                         if (IS_MDT(&mop->mo_ldd))
1415                                 mop->mo_ldd.ldd_flags |= LDD_F_IAM_DIR;
1416                         break;
1417                 }
1418                 case 'b': {
1419                         int i = 0;
1420                         while (i < LDD_MT_LAST) {
1421                                 if (strcmp(optarg, mt_str(i)) == 0) {
1422                                         mop->mo_ldd.ldd_mount_type = i;
1423                                         break;
1424                                 }
1425                                 i++;
1426                         }
1427                         break;
1428                 }
1429                 case 'c':
1430                         if (IS_MDT(&mop->mo_ldd)) {
1431                                 int stripe_count = atol(optarg);
1432                                 if (stripe_count <= 0) {
1433                                         fprintf(stderr, "%s: bad stripe count "
1434                                                 "%d\n", progname, stripe_count);
1435                                         return 1;
1436                                 }
1437                                 mop->mo_stripe_count = stripe_count;
1438                         } else {
1439                                 badopt(long_opt[longidx].name, "MDT");
1440                                 return 1;
1441                         }
1442                         break;
1443                 case 'C': /* Configdev */
1444                         //FIXME
1445                         printf("Configdev not implemented\n");
1446                         return 1;
1447                 case 'd':
1448                         mop->mo_device_sz = atol(optarg);
1449                         break;
1450                 case 'e':
1451                         mop->mo_ldd.ldd_params[0] = '\0';
1452                         /* Must update the mgs logs */
1453                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1454                         break;
1455                 case 'f':
1456                 case 's': {
1457                         char *nids;
1458
1459                         if ((opt == 'f' && servicenode_set)
1460                             || (opt == 's' && failnode_set)) {
1461                                 fprintf(stderr, "%s: %s cannot use with --%s\n",
1462                                         progname, long_opt[longidx].name,
1463                                         opt == 'f' ? "servicenode" : "failnode");
1464                                 return 1;
1465                         }
1466
1467                         nids = convert_hostnames(optarg);
1468                         if (!nids)
1469                                 return 1;
1470                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_FAILNODE,
1471                                        nids);
1472                         free(nids);
1473                         if (rc)
1474                                 return rc;
1475                         /* Must update the mgs logs */
1476                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1477                         if (opt == 'f') {
1478                                 failnode_set = 1;
1479                         } else {
1480                                 mop->mo_ldd.ldd_flags |= LDD_F_NO_PRIMNODE;
1481                                 servicenode_set = 1;
1482                         }
1483                         failover = 1;
1484                         break;
1485                 }
1486                 case 'G':
1487                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_MGS;
1488                         break;
1489                 case 'h':
1490                         usage(stdout);
1491                         return 1;
1492                 case 'i':
1493                         if (!(mop->mo_ldd.ldd_flags &
1494                               (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1495                                LDD_F_WRITECONF))) {
1496                                 fprintf(stderr, "%s: cannot change the index of"
1497                                         " a registered target\n", progname);
1498                                 return 1;
1499                         }
1500                         if (IS_MDT(&mop->mo_ldd) || IS_OST(&mop->mo_ldd)) {
1501                                 mop->mo_ldd.ldd_svindex = atol(optarg);
1502                                 mop->mo_ldd.ldd_flags &= ~LDD_F_NEED_INDEX;
1503                         } else {
1504                                 badopt(long_opt[longidx].name, "MDT,OST");
1505                                 return 1;
1506                         }
1507                         break;
1508                 case 'k':
1509                         strscpy(mop->mo_mkfsopts, optarg,
1510                                 sizeof(mop->mo_mkfsopts));
1511                         break;
1512                 case 'L': {
1513                         char *tmp;
1514                         if (!(mop->mo_flags & MO_FORCEFORMAT) &&
1515                             (!(mop->mo_ldd.ldd_flags &
1516                                (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1517                                 LDD_F_WRITECONF)))) {
1518                                 fprintf(stderr, "%s: cannot change the name of"
1519                                         " a registered target\n", progname);
1520                                 return 1;
1521                         }
1522                         if ((strlen(optarg) < 1) || (strlen(optarg) > 8)) {
1523                                 fprintf(stderr, "%s: filesystem name must be "
1524                                         "1-8 chars\n", progname);
1525                                 return 1;
1526                         }
1527                         if ((tmp = strpbrk(optarg, "/:"))) {
1528                                 fprintf(stderr, "%s: char '%c' not allowed in "
1529                                         "filesystem name\n", progname, *tmp);
1530                                 return 1;
1531                         }
1532                         strscpy(mop->mo_ldd.ldd_fsname, optarg,
1533                                 sizeof(mop->mo_ldd.ldd_fsname));
1534                         break;
1535                 }
1536                 case 'm': {
1537                         char *nids = convert_hostnames(optarg);
1538                         if (!nids)
1539                                 return 1;
1540                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_MGSNODE,
1541                                        nids);
1542                         free(nids);
1543                         if (rc)
1544                                 return rc;
1545                         mop->mo_mgs_failnodes++;
1546                         break;
1547                 }
1548                 case 'M':
1549                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_MDT;
1550                         break;
1551                 case 'n':
1552                         print_only++;
1553                         break;
1554                 case 'N':
1555                         mop->mo_ldd.ldd_flags &= ~LDD_F_SV_TYPE_MGS;
1556                         break;
1557                 case 'o':
1558                         *mountopts = optarg;
1559                         break;
1560                 case 'O':
1561                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_OST;
1562                         break;
1563                 case 'p':
1564                         rc = add_param(mop->mo_ldd.ldd_params, NULL, optarg);
1565                         if (rc)
1566                                 return rc;
1567                         /* Must update the mgs logs */
1568                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1569                         break;
1570                 case 'q':
1571                         verbose--;
1572                         break;
1573                 case 'r':
1574                         mop->mo_flags |= MO_FORCEFORMAT;
1575                         break;
1576                 case 't':
1577                         if (!IS_MDT(&mop->mo_ldd) && !IS_OST(&mop->mo_ldd)) {
1578                                 badopt(long_opt[longidx].name, "MDT,OST");
1579                                 return 1;
1580                         }
1581
1582                         if (!optarg)
1583                                 return 1;
1584
1585                         rc = add_param(mop->mo_ldd.ldd_params,
1586                                        PARAM_NETWORK, optarg);
1587                         if (rc != 0)
1588                                 return rc;
1589                         /* Must update the mgs logs */
1590                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1591                         break;
1592                 case 'u':
1593                         strscpy(mop->mo_ldd.ldd_userdata, optarg,
1594                                 sizeof(mop->mo_ldd.ldd_userdata));
1595                         break;
1596                 case 'v':
1597                         verbose++;
1598                         break;
1599                 case 'w':
1600                         mop->mo_ldd.ldd_flags |= LDD_F_WRITECONF;
1601                         break;
1602                 case 'U':
1603                         upgrade_to_18 = 1;
1604                         break;
1605                 default:
1606                         if (opt != '?') {
1607                                 fatal();
1608                                 fprintf(stderr, "Unknown option '%c'\n", opt);
1609                         }
1610                         return EINVAL;
1611                 }
1612         }//while
1613
1614         /* Last arg is device */
1615         if (optind != argc - 1) {
1616                 fatal();
1617                 fprintf(stderr, "Bad argument: %s\n", argv[optind]);
1618                 return EINVAL;
1619         }
1620
1621         /* single argument: <device> */
1622         if (argc == 2)
1623                 ++print_only;
1624
1625         return 0;
1626 }
1627
1628 /* Search for opt in mntlist, returning true if found.
1629  */
1630 static int in_mntlist(char *opt, char *mntlist)
1631 {
1632         char *ml, *mlp, *item, *ctx = NULL;
1633
1634         if (!(ml = strdup(mntlist))) {
1635                 fprintf(stderr, "%s: out of memory\n", progname);
1636                 exit(1);
1637         }
1638         mlp = ml;
1639         while ((item = strtok_r(mlp, ",", &ctx))) {
1640                 if (!strcmp(opt, item))
1641                         break;
1642                 mlp = NULL;
1643         }
1644         free(ml);
1645         return (item != NULL);
1646 }
1647
1648 /* Issue a message on stderr for every item in wanted_mountopts that is not
1649  * present in mountopts.  The justwarn boolean toggles between error and
1650  * warning message.  Return an error count.
1651  */
1652 static int check_mountfsoptions(char *mountopts, char *wanted_mountopts,
1653                                 int justwarn)
1654 {
1655         char *ml, *mlp, *item, *ctx = NULL;
1656         int errors = 0;
1657
1658         if (!(ml = strdup(wanted_mountopts))) {
1659                 fprintf(stderr, "%s: out of memory\n", progname);
1660                 exit(1);
1661         }
1662         mlp = ml;
1663         while ((item = strtok_r(mlp, ",", &ctx))) {
1664                 if (!in_mntlist(item, mountopts)) {
1665                         fprintf(stderr, "%s: %s mount option `%s' is missing\n",
1666                                 progname, justwarn ? "Warning: default"
1667                                 : "Error: mandatory", item);
1668                         errors++;
1669                 }
1670                 mlp = NULL;
1671         }
1672         free(ml);
1673         return errors;
1674 }
1675
1676 /* Trim embedded white space, leading and trailing commas from string s.
1677  */
1678 static void trim_mountfsoptions(char *s)
1679 {
1680         char *p;
1681
1682         for (p = s; *p; ) {
1683                 if (isspace(*p)) {
1684                         memmove(p, p + 1, strlen(p + 1) + 1);
1685                         continue;
1686                 }
1687                 p++;
1688         }
1689
1690         while (s[0] == ',')
1691                 memmove(&s[0], &s[1], strlen(&s[1]) + 1);
1692
1693         p = s + strlen(s) - 1;
1694         while (p >= s && *p == ',')
1695                 *p-- = '\0';
1696 }
1697
1698 int main(int argc, char *const argv[])
1699 {
1700         struct mkfs_opts mop;
1701         struct lustre_disk_data *ldd;
1702         char *mountopts = NULL;
1703         char always_mountopts[512] = "";
1704         char default_mountopts[512] = "";
1705         int ret = 0;
1706
1707         if ((progname = strrchr(argv[0], '/')) != NULL)
1708                 progname++;
1709         else
1710                 progname = argv[0];
1711
1712         if ((argc < 2) || (argv[argc - 1][0] == '-')) {
1713                 usage(stderr);
1714                 return(EINVAL);
1715         }
1716
1717         memset(&mop, 0, sizeof(mop));
1718         set_defaults(&mop);
1719
1720         /* device is last arg */
1721         strscpy(mop.mo_device, argv[argc - 1], sizeof(mop.mo_device));
1722
1723         /* Are we using a loop device? */
1724         ret = is_block(mop.mo_device);
1725         if (ret < 0)
1726                 goto out;
1727         if (ret == 0)
1728                 mop.mo_flags |= MO_IS_LOOP;
1729
1730 #ifdef TUNEFS
1731         /* For tunefs, we must read in the old values before parsing any
1732            new ones. */
1733
1734         /* Check whether the disk has already been formatted by mkfs.lustre */
1735         ret = is_lustre_target(&mop);
1736         if (ret == 0) {
1737                 fatal();
1738                 fprintf(stderr, "Device %s has not been formatted with "
1739                         "mkfs.lustre\n", mop.mo_device);
1740                 ret = ENODEV;
1741                 goto out;
1742         }
1743
1744         ret = read_local_files(&mop);
1745         if (ret) {
1746                 fatal();
1747                 fprintf(stderr, "Failed to read previous Lustre data from %s "
1748                         "(%d)\n", mop.mo_device, ret);
1749                 goto out;
1750         }
1751         if (strstr(mop.mo_ldd.ldd_params, PARAM_MGSNODE))
1752             mop.mo_mgs_failnodes++;
1753
1754         if (verbose > 0)
1755                 print_ldd("Read previous values", &(mop.mo_ldd));
1756 #endif
1757
1758         ret = parse_opts(argc, argv, &mop, &mountopts);
1759         if (ret)
1760                 goto out;
1761
1762         ldd = &mop.mo_ldd;
1763
1764         if (!(IS_MDT(ldd) || IS_OST(ldd) || IS_MGS(ldd))) {
1765                 fatal();
1766                 fprintf(stderr, "must set target type: MDT,OST,MGS\n");
1767                 ret = EINVAL;
1768                 goto out;
1769         }
1770
1771         if (((IS_MDT(ldd) || IS_MGS(ldd))) && IS_OST(ldd)) {
1772                 fatal();
1773                 fprintf(stderr, "OST type is exclusive with MDT,MGS\n");
1774                 ret = EINVAL;
1775                 goto out;
1776         }
1777
1778         if ((mop.mo_ldd.ldd_flags & (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) ==
1779             (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) {
1780                 fatal();
1781                 fprintf(stderr, "Can't find the target index, "
1782                         "specify with --index\n");
1783                 ret = EINVAL;
1784                 goto out;
1785         }
1786 #if 0
1787         /*
1788          * Comment out these 2 checks temporarily, since for multi-MDSes
1789          * in single node only 1 mds node could have mgs service
1790          */
1791         if (IS_MDT(ldd) && !IS_MGS(ldd) && (mop.mo_mgs_failnodes == 0)) {
1792                 verrprint("No management node specified, adding MGS to this "
1793                           "MDT\n");
1794                 ldd->ldd_flags |= LDD_F_SV_TYPE_MGS;
1795         }
1796         if (!IS_MGS(ldd) && (mop.mo_mgs_failnodes == 0)) {
1797                 fatal();
1798                 if (IS_MDT(ldd))
1799                         fprintf(stderr, "Must specify --mgs or --mgsnode=\n");
1800                 else
1801                         fprintf(stderr, "Must specify --mgsnode=\n");
1802                 ret = EINVAL;
1803                 goto out;
1804         }
1805 #endif
1806
1807         /* These are the permanent mount options (always included) */
1808         switch (ldd->ldd_mount_type) {
1809         case LDD_MT_EXT3:
1810         case LDD_MT_LDISKFS:
1811         case LDD_MT_LDISKFS2:
1812                 strscat(default_mountopts, ",errors=remount-ro",
1813                         sizeof(default_mountopts));
1814                 if (IS_MDT(ldd) || IS_MGS(ldd))
1815                         strscat(always_mountopts, ",user_xattr",
1816                                 sizeof(always_mountopts));
1817                 /* NB: Files created while extents are enabled can only be read
1818                  * if mounted using the ext4 or ldiskfs filesystem type. */
1819                 if (IS_OST(ldd) &&
1820                     (ldd->ldd_mount_type == LDD_MT_LDISKFS ||
1821                      ldd->ldd_mount_type == LDD_MT_LDISKFS2)) {
1822                         strscat(default_mountopts, ",extents,mballoc",
1823                                 sizeof(default_mountopts));
1824                 }
1825                 break;
1826         default:
1827                 fatal();
1828                 fprintf(stderr, "unknown fs type %d '%s'\n",
1829                         ldd->ldd_mount_type,
1830                         MT_STR(ldd));
1831                 ret = EINVAL;
1832                 goto out;
1833         }
1834
1835         if (mountopts) {
1836                 trim_mountfsoptions(mountopts);
1837                 (void)check_mountfsoptions(mountopts, default_mountopts, 1);
1838                 if (check_mountfsoptions(mountopts, always_mountopts, 0)) {
1839                         ret = EINVAL;
1840                         goto out;
1841                 }
1842                 sprintf(ldd->ldd_mount_opts, "%s", mountopts);
1843         } else {
1844 #ifdef TUNEFS
1845                 if (ldd->ldd_mount_opts[0] == 0)
1846                         /* use the defaults unless old opts exist */
1847 #endif
1848                 {
1849                         sprintf(ldd->ldd_mount_opts, "%s%s",
1850                                 always_mountopts, default_mountopts);
1851                         trim_mountfsoptions(ldd->ldd_mount_opts);
1852                 }
1853         }
1854
1855         server_make_name(ldd->ldd_flags, ldd->ldd_svindex,
1856                          ldd->ldd_fsname, ldd->ldd_svname);
1857
1858         if (verbose >= 0)
1859                 print_ldd("Permanent disk data", ldd);
1860
1861         if (print_only) {
1862                 printf("exiting before disk write.\n");
1863                 goto out;
1864         }
1865
1866         if (check_mtab_entry(mop.mo_device))
1867                 return(EEXIST);
1868
1869         /* Create the loopback file */
1870         if (mop.mo_flags & MO_IS_LOOP) {
1871                 ret = access(mop.mo_device, F_OK);
1872                 if (ret)
1873                         ret = errno;
1874 #ifndef TUNEFS /* mkfs.lustre */
1875                 /* Reformat the loopback file */
1876                 if (ret || (mop.mo_flags & MO_FORCEFORMAT))
1877                         ret = loop_format(&mop);
1878 #endif
1879                 if (ret == 0)
1880                         ret = loop_setup(&mop);
1881                 if (ret) {
1882                         fatal();
1883                         fprintf(stderr, "Loop device setup for %s failed: %s\n",
1884                                 mop.mo_device, strerror(ret));
1885                         goto out;
1886                 }
1887         }
1888
1889 #ifndef TUNEFS /* mkfs.lustre */
1890         /* Check whether the disk has already been formatted by mkfs.lustre */
1891         if (!(mop.mo_flags & MO_FORCEFORMAT)) {
1892                 ret = is_lustre_target(&mop);
1893                 if (ret) {
1894                         fatal();
1895                         fprintf(stderr, "Device %s was previously formatted "
1896                                 "for lustre. Use --reformat to reformat it, "
1897                                 "or tunefs.lustre to modify.\n",
1898                                 mop.mo_device);
1899                         goto out;
1900                 }
1901         }
1902
1903         /* Format the backing filesystem */
1904         ret = make_lustre_backfs(&mop);
1905         if (ret != 0) {
1906                 fatal();
1907                 fprintf(stderr, "mkfs failed %d\n", ret);
1908                 goto out;
1909         }
1910 #endif
1911
1912         /* Write our config files */
1913         ret = write_local_files(&mop);
1914         if (ret != 0) {
1915                 fatal();
1916                 fprintf(stderr, "failed to write local files\n");
1917                 goto out;
1918         }
1919
1920 out:
1921         loop_cleanup(&mop);
1922
1923         /* Fix any crazy return values from system() */
1924         if (ret && ((ret & 255) == 0))
1925                 return (1);
1926         if (ret)
1927                 verrprint("%s: exiting with %d (%s)\n",
1928                           progname, ret, strerror(ret));
1929         return (ret);
1930 }