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