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