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