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