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