Whamcloud - gitweb
28c3806e6892e3563ccf76a263a1a417b371590e
[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 enable_default_backfs_features(struct mkfs_opts *mop)
521 {
522         struct utsname uts;
523         int ret;
524
525         if (IS_OST(&mop->mo_ldd))
526                 strscat(mop->mo_mkfsopts, " -O dir_index,extents",
527                         sizeof(mop->mo_mkfsopts));
528         else if (IS_MDT(&mop->mo_ldd))
529                 strscat(mop->mo_mkfsopts, " -O dir_index,dirdata",
530                         sizeof(mop->mo_mkfsopts));
531         else
532                 strscat(mop->mo_mkfsopts, " -O dir_index",
533                         sizeof(mop->mo_mkfsopts));
534
535         /* Upstream e2fsprogs called our uninit_groups feature uninit_bg,
536          * check for both of them when testing e2fsprogs features. */
537         if (is_e2fsprogs_feature_supp("uninit_bg") == 0)
538                 strscat(mop->mo_mkfsopts, ",uninit_bg",
539                         sizeof(mop->mo_mkfsopts));
540         else if (is_e2fsprogs_feature_supp("uninit_groups") == 0)
541                 strscat(mop->mo_mkfsopts, ",uninit_groups",
542                         sizeof(mop->mo_mkfsopts));
543         else
544                 disp_old_e2fsprogs_msg("uninit_bg", 1);
545
546         ret = uname(&uts);
547         if (ret)
548                 return;
549
550         /* Multiple mount protection is enabled only if failover node is
551          * specified and if kernel version is higher than 2.6.9 */
552         if (failover) {
553                 if (is_e2fsprogs_feature_supp("mmp") == 0)
554                         strscat(mop->mo_mkfsopts, ",mmp",
555                                 sizeof(mop->mo_mkfsopts));
556                 else
557                         disp_old_e2fsprogs_msg("mmp", 1);
558         }
559 }
560 /* Build fs according to type */
561 int make_lustre_backfs(struct mkfs_opts *mop)
562 {
563         __u64 device_sz = mop->mo_device_sz, block_count = 0;
564         char mkfs_cmd[PATH_MAX];
565         char buf[64];
566         char *dev;
567         int ret = 0;
568
569         if (!(mop->mo_flags & MO_IS_LOOP)) {
570                 mop->mo_device_sz = get_device_size(mop->mo_device);
571
572                 if (mop->mo_device_sz == 0)
573                         return ENODEV;
574
575                 /* Compare to real size */
576                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
577                         device_sz = mop->mo_device_sz;
578                 else
579                         mop->mo_device_sz = device_sz;
580         }
581
582         if (mop->mo_device_sz != 0) {
583                 if (mop->mo_device_sz < 8096){
584                         fprintf(stderr, "%s: size of filesystem must be larger "
585                                 "than 8MB, but is set to %lldKB\n",
586                                 progname, (long long)mop->mo_device_sz);
587                         return EINVAL;
588                 }
589                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
590         }
591
592         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
593             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
594             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
595                 /* Journal size in MB */
596                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
597                         /* Choose our own default journal size */
598                         long journal_sz = 0, max_sz;
599                         if (device_sz > 1024 * 1024) /* 1GB */
600                                 journal_sz = (device_sz / 102400) * 4;
601                         /* cap journal size at 1GB */
602                         if (journal_sz > 1024L)
603                                 journal_sz = 1024L;
604                         /* man mkfs.ext3 */
605                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
606                         if (journal_sz > max_sz)
607                                 journal_sz = max_sz;
608                         if (journal_sz) {
609                                 sprintf(buf, " -J size=%ld", journal_sz);
610                                 strscat(mop->mo_mkfsopts, buf,
611                                         sizeof(mop->mo_mkfsopts));
612                         }
613                 }
614
615                 /* Bytes_per_inode: disk size / num inodes */
616                 if (strstr(mop->mo_mkfsopts, "-i") == NULL) {
617                         long bytes_per_inode = 0;
618
619                         if (IS_MDT(&mop->mo_ldd))
620                                 bytes_per_inode = 4096;
621
622                         /* Allocate fewer inodes on large OST devices.  Most
623                            filesystems can be much more aggressive than even
624                            this. */
625                         if ((IS_OST(&mop->mo_ldd) && (device_sz > 100000000)))
626                                 bytes_per_inode = 16384;  /* > 100 Gb device */
627
628
629                         if (bytes_per_inode > 0) {
630                                 sprintf(buf, " -i %ld", bytes_per_inode);
631                                 strscat(mop->mo_mkfsopts, buf,
632                                         sizeof(mop->mo_mkfsopts));
633                         }
634                 }
635
636                 /* Inode size (for extended attributes).  The LOV EA size is
637                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
638                  * and we want some margin above that for ACLs, other EAs... */
639                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
640                         long inode_size = 0;
641                         if (IS_MDT(&mop->mo_ldd)) {
642                                 if (mop->mo_stripe_count > 72)
643                                         inode_size = 512; /* bz 7241 */
644                                 /* cray stripes across all osts (>60) */
645                                 else if (mop->mo_stripe_count > 32)
646                                         inode_size = 2048;
647                                 else if (mop->mo_stripe_count > 10)
648                                         inode_size = 1024;
649                                 else
650                                         inode_size = 512;
651                         } else if (IS_OST(&mop->mo_ldd)) {
652                                 /* now as we store fids in EA on OST we need
653                                    to make inode bigger */
654                                 inode_size = 256;
655                         }
656
657                         if (inode_size > 0) {
658                                 sprintf(buf, " -I %ld", inode_size);
659                                 strscat(mop->mo_mkfsopts, buf,
660                                         sizeof(mop->mo_mkfsopts));
661                         }
662                 }
663
664                 if (verbose < 2) {
665                         strscat(mop->mo_mkfsopts, " -q",
666                                 sizeof(mop->mo_mkfsopts));
667                 }
668
669                 if (strstr(mop->mo_mkfsopts, "-O") == NULL)
670                         enable_default_backfs_features(mop);
671
672                 /* Allow reformat of full devices (as opposed to
673                    partitions.)  We already checked for mounted dev. */
674                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
675
676                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
677                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
678                          mop->mo_ldd.ldd_svname);
679         } else if (mop->mo_ldd.ldd_mount_type == LDD_MT_REISERFS) {
680                 long journal_sz = 0; /* FIXME default journal size */
681                 if (journal_sz > 0) {
682                         sprintf(buf, " --journal_size %ld", journal_sz);
683                         strscat(mop->mo_mkfsopts, buf,
684                                 sizeof(mop->mo_mkfsopts));
685                 }
686                 snprintf(mkfs_cmd, sizeof(mkfs_cmd), "mkreiserfs -ff ");
687         } else {
688                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
689                         progname, mop->mo_ldd.ldd_mount_type,
690                         MT_STR(&mop->mo_ldd));
691                 return EINVAL;
692         }
693
694         /* For loop device format the dev, not the filename */
695         dev = mop->mo_device;
696         if (mop->mo_flags & MO_IS_LOOP)
697                 dev = mop->mo_loopdev;
698
699         vprint("formatting backing filesystem %s on %s\n",
700                MT_STR(&mop->mo_ldd), dev);
701         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
702         vprint("\t4k blocks     "LPU64"\n", block_count);
703         vprint("\toptions       %s\n", mop->mo_mkfsopts);
704
705         /* mkfs_cmd's trailing space is important! */
706         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
707         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
708         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
709         if (block_count != 0) {
710                 sprintf(buf, " "LPU64, block_count);
711                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
712         }
713
714         vprint("mkfs_cmd = %s\n", mkfs_cmd);
715         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
716         if (ret) {
717                 fatal();
718                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
719         }
720         return ret;
721 }
722
723 /* ==================== Lustre config functions =============*/
724
725 void print_ldd(char *str, struct lustre_disk_data *ldd)
726 {
727         printf("\n   %s:\n", str);
728         printf("Target:     %s\n", ldd->ldd_svname);
729         if (ldd->ldd_svindex == INDEX_UNASSIGNED)
730                 printf("Index:      unassigned\n");
731         else
732                 printf("Index:      %d\n", ldd->ldd_svindex);
733         if (ldd->ldd_uuid[0])
734                 printf("UUID:       %s\n", (char *)ldd->ldd_uuid);
735         printf("Lustre FS:  %s\n", ldd->ldd_fsname);
736         printf("Mount type: %s\n", MT_STR(ldd));
737         printf("Flags:      %#x\n", ldd->ldd_flags);
738         printf("              (%s%s%s%s%s%s%s%s%s)\n",
739                IS_MDT(ldd) ? "MDT ":"",
740                IS_OST(ldd) ? "OST ":"",
741                IS_MGS(ldd) ? "MGS ":"",
742                ldd->ldd_flags & LDD_F_NEED_INDEX ? "needs_index ":"",
743                ldd->ldd_flags & LDD_F_VIRGIN     ? "first_time ":"",
744                ldd->ldd_flags & LDD_F_UPDATE     ? "update ":"",
745                ldd->ldd_flags & LDD_F_WRITECONF  ? "writeconf ":"",
746                ldd->ldd_flags & LDD_F_IAM_DIR  ? "IAM_dir_format ":"",
747                ldd->ldd_flags & LDD_F_UPGRADE14  ? "upgrade1.4 ":"");
748         printf("Persistent mount opts: %s\n", ldd->ldd_mount_opts);
749         printf("Parameters:%s\n", ldd->ldd_params);
750         if (ldd->ldd_userdata[0])
751                 printf("Comment: %s\n", ldd->ldd_userdata);
752         printf("\n");
753 }
754
755 static int touch_file(char *filename)
756 {
757         int fd;
758
759         if (filename == NULL) {
760                 return 1;
761         }
762
763         fd = open(filename, O_CREAT | O_TRUNC, 0600);
764         if (fd < 0) {
765                 return 1;
766         } else {
767                 close(fd);
768                 return 0;
769         }
770 }
771
772 /* keep it less than LL_FID_NAMELEN */
773 #define DUMMY_FILE_NAME_LEN             25
774 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
775
776 /* Need to add these many entries to this directory to make HTREE dir. */
777 #define MIN_ENTRIES_REQ_FOR_HTREE       ((L_BLOCK_SIZE / EXT3_DIRENT_SIZE))
778
779 static int add_dummy_files(char *dir)
780 {
781         char fpname[PATH_MAX];
782         int i;
783         int rc;
784
785         for (i = 0; i < MIN_ENTRIES_REQ_FOR_HTREE; i++) {
786                 snprintf(fpname, PATH_MAX, "%s/%0*d", dir,
787                          DUMMY_FILE_NAME_LEN, i);
788
789                 rc = touch_file(fpname);
790                 if (rc && rc != -EEXIST) {
791                         fprintf(stderr,
792                                 "%s: Can't create dummy file %s: %s\n",
793                                 progname, fpname , strerror(errno));
794                         return rc;
795                 }
796         }
797         return 0;
798 }
799
800 static int __l_mkdir(char * filepnm, int mode , struct mkfs_opts *mop)
801 {
802         int ret;
803
804         ret = mkdir(filepnm, mode);
805         if (ret && ret != -EEXIST)
806                 return ret;
807
808         /* IAM mode supports ext3 directories of HTREE type only. So add dummy
809          * entries to new directory to create htree type of container for
810          * this directory. */
811         if (mop->mo_ldd.ldd_flags & LDD_F_IAM_DIR)
812                 return add_dummy_files(filepnm);
813         return 0;
814 }
815
816 /* Write the server config files */
817 int write_local_files(struct mkfs_opts *mop)
818 {
819         char mntpt[] = "/tmp/mntXXXXXX";
820         char filepnm[128];
821         char *dev;
822         FILE *filep;
823         int ret = 0;
824         size_t num;
825
826         /* Mount this device temporarily in order to write these files */
827         if (!mkdtemp(mntpt)) {
828                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
829                         progname, mntpt, strerror(errno));
830                 return errno;
831         }
832
833         dev = mop->mo_device;
834         if (mop->mo_flags & MO_IS_LOOP)
835                 dev = mop->mo_loopdev;
836
837         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
838                     mop->mo_ldd.ldd_mount_opts);
839         if (ret) {
840                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
841                         progname, dev, strerror(errno));
842                 ret = errno;
843                 if (errno == ENODEV) {
844                         fprintf(stderr, "Is the %s module available?\n",
845                                 MT_STR(&mop->mo_ldd));
846                 }
847                 goto out_rmdir;
848         }
849
850         /* Set up initial directories */
851         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
852         ret = __l_mkdir(filepnm, 0777, mop);
853         if ((ret != 0) && (errno != EEXIST)) {
854                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
855                         progname, filepnm, strerror(errno));
856                 goto out_umnt;
857         } else if (errno == EEXIST) {
858                 ret = 0;
859         }
860
861         /* Save the persistent mount data into a file. Lustre must pre-read
862            this file to get the real mount options. */
863         vprint("Writing %s\n", MOUNT_DATA_FILE);
864         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
865         filep = fopen(filepnm, "w");
866         if (!filep) {
867                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
868                         progname, filepnm, strerror(errno));
869                 goto out_umnt;
870         }
871         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
872         if (num < 1 && ferror(filep)) {
873                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
874                         progname, filepnm, strerror(errno));
875                 goto out_umnt;
876         }
877         fclose(filep);
878         /* COMPAT_146 */
879 #ifdef TUNEFS
880         /* Check for upgrade */
881         if ((mop->mo_ldd.ldd_flags & (LDD_F_UPGRADE14 | SVTYPE_MGS))
882             == (LDD_F_UPGRADE14 | SVTYPE_MGS)) {
883                 char cmd[128];
884                 char *term;
885                 int cmdsz = sizeof(cmd);
886                 vprint("Copying old logs\n");
887
888                 /* Copy the old client log to fsname-client */
889                 sprintf(filepnm, "%s/%s/%s-client",
890                         mntpt, MOUNT_CONFIGS_DIR, mop->mo_ldd.ldd_fsname);
891                 snprintf(cmd, cmdsz, "cp %s/%s/client %s", mntpt, MDT_LOGS_DIR,
892                          filepnm);
893                 ret = run_command(cmd, cmdsz);
894                 if (ret) {
895                         fprintf(stderr, "%s: Can't copy 1.4 config %s/client "
896                                 "(%d)\n", progname, MDT_LOGS_DIR, ret);
897                         fprintf(stderr, "mount -t ldiskfs %s somewhere, "
898                                 "find the client log for fs %s and "
899                                 "copy it manually into %s/%s-client, "
900                                 "then umount.\n",
901                                 mop->mo_device,
902                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
903                                 mop->mo_ldd.ldd_fsname);
904                         goto out_umnt;
905                 }
906
907                 /* We need to use the old mdt log because otherwise mdt won't
908                    have complete lov if old clients connect before all
909                    servers upgrade. */
910                 /* Copy the old mdt log to fsname-MDT0000 (get old
911                    name from mdt_UUID) */
912                 ret = 1;
913                 strscpy(filepnm, (char *)mop->mo_ldd.ldd_uuid, sizeof(filepnm));
914                 term = strstr(filepnm, "_UUID");
915                 if (term) {
916                         *term = '\0';
917                         snprintf(cmd, cmdsz, "cp %s/%s/%s %s/%s/%s",
918                                  mntpt, MDT_LOGS_DIR, filepnm,
919                                  mntpt, MOUNT_CONFIGS_DIR,
920                                  mop->mo_ldd.ldd_svname);
921                         ret = run_command(cmd, cmdsz);
922                 }
923                 if (ret) {
924                         fprintf(stderr, "%s: Can't copy 1.4 config %s/%s "
925                                 "(%d)\n", progname, MDT_LOGS_DIR, filepnm, ret);
926                         fprintf(stderr, "mount -t ext3 %s somewhere, "
927                                 "find the MDT log for fs %s and "
928                                 "copy it manually into %s/%s, "
929                                 "then umount.\n",
930                                 mop->mo_device,
931                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
932                                 mop->mo_ldd.ldd_svname);
933                         goto out_umnt;
934                 }
935         }
936 #endif
937         /* end COMPAT_146 */
938
939 out_umnt:
940         umount(mntpt);
941 out_rmdir:
942         rmdir(mntpt);
943         return ret;
944 }
945
946 int read_local_files(struct mkfs_opts *mop)
947 {
948         char tmpdir[] = "/tmp/dirXXXXXX";
949         char cmd[PATH_MAX];
950         char filepnm[128];
951         char *dev;
952         FILE *filep;
953         int ret = 0;
954         int cmdsz = sizeof(cmd);
955
956         /* Make a temporary directory to hold Lustre data files. */
957         if (!mkdtemp(tmpdir)) {
958                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
959                         progname, tmpdir, strerror(errno));
960                 return errno;
961         }
962
963         dev = mop->mo_device;
964
965         /* TODO: it's worth observing the get_mountdata() function that is
966                  in mount_utils.c for getting the mountdata out of the
967                  filesystem */
968
969         /* Construct debugfs command line. */
970         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
971                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
972
973         ret = run_command(cmd, cmdsz);
974         if (ret)
975                 verrprint("%s: Unable to dump %s dir (%d)\n",
976                           progname, MOUNT_CONFIGS_DIR, ret);
977
978         sprintf(filepnm, "%s/mountdata", tmpdir);
979         filep = fopen(filepnm, "r");
980         if (filep) {
981                 size_t num_read;
982                 vprint("Reading %s\n", MOUNT_DATA_FILE);
983                 num_read = fread(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
984                 if (num_read < 1 && ferror(filep)) {
985                         fprintf(stderr, "%s: Unable to read from file (%s): %s\n",
986                                 progname, filepnm, strerror(errno));
987                         goto out_close;
988                 }
989         } else {
990                 /* COMPAT_146 */
991                 /* Try to read pre-1.6 config from last_rcvd */
992                 struct lr_server_data lsd;
993                 verrprint("%s: Unable to read %d.%d config %s.\n",
994                           progname, LUSTRE_MAJOR, LUSTRE_MINOR, filepnm);
995
996                 verrprint("Trying 1.4 config from last_rcvd\n");
997                 sprintf(filepnm, "%s/%s", tmpdir, LAST_RCVD);
998
999                 /* Construct debugfs command line. */
1000                 snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s' %s",
1001                          DEBUGFS, LAST_RCVD, filepnm, dev);
1002
1003                 ret = run_command(cmd, cmdsz);
1004                 if (ret) {
1005                         fprintf(stderr, "%s: Unable to dump %s file (%d)\n",
1006                                 progname, LAST_RCVD, ret);
1007                         goto out_rmdir;
1008                 }
1009
1010                 filep = fopen(filepnm, "r");
1011                 if (!filep) {
1012                         fprintf(stderr, "%s: Unable to open %s: %s\n",
1013                                 progname, filepnm, strerror(errno));
1014                         ret = errno;
1015                         verrprint("Contents of %s:\n", tmpdir);
1016                         verbose+=2;
1017                         snprintf(cmd, cmdsz, "ls -l %s/", tmpdir);
1018                         run_command(cmd, cmdsz);
1019                         verrprint("Contents of disk:\n");
1020                         snprintf(cmd, cmdsz, "%s -c -R 'ls -l /' %s",
1021                                  DEBUGFS, dev);
1022                         run_command(cmd, cmdsz);
1023
1024                         goto out_rmdir;
1025                 }
1026                 vprint("Reading %s\n", LAST_RCVD);
1027                 ret = fread(&lsd, 1, sizeof(lsd), filep);
1028                 if (ret < sizeof(lsd)) {
1029                         fprintf(stderr, "%s: Short read (%d of %d)\n",
1030                                 progname, ret, (int)sizeof(lsd));
1031                         ret = ferror(filep);
1032                         if (ret)
1033                                 goto out_close;
1034                 }
1035                 vprint("Feature compat=%x, incompat=%x\n",
1036                        lsd.lsd_feature_compat, lsd.lsd_feature_incompat);
1037
1038                 if ((lsd.lsd_feature_compat & OBD_COMPAT_OST) ||
1039                     (lsd.lsd_feature_incompat & OBD_INCOMPAT_OST)) {
1040                         mop->mo_ldd.ldd_flags = SVTYPE_OST;
1041                         mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
1042                 } else if ((lsd.lsd_feature_compat & OBD_COMPAT_MDT) ||
1043                            (lsd.lsd_feature_incompat & OBD_INCOMPAT_MDT)) {
1044                         /* We must co-locate so mgs can see old logs.
1045                            If user doesn't want this, they can copy the old
1046                            logs manually and re-tunefs. */
1047                         mop->mo_ldd.ldd_flags =
1048                                 SVTYPE_MDT | SVTYPE_MGS;
1049                         mop->mo_ldd.ldd_svindex = lsd.lsd_mdt_index;
1050                 } else  {
1051                         /* If neither is set, we're pre-1.4.6, make a guess. */
1052                         /* Construct debugfs command line. */
1053                         snprintf(cmd, cmdsz, "%s -c -R 'rdump /%s %s' %s",
1054                                  DEBUGFS, MDT_LOGS_DIR, tmpdir, dev);
1055                         run_command(cmd, cmdsz);
1056
1057                         sprintf(filepnm, "%s/%s", tmpdir, MDT_LOGS_DIR);
1058                         if (lsd.lsd_ost_index > 0) {
1059                                 mop->mo_ldd.ldd_flags = SVTYPE_OST;
1060                                 mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
1061                         } else {
1062                                 /* If there's a LOGS dir, it's an MDT */
1063                                 if ((ret = access(filepnm, F_OK)) == 0) {
1064                                         mop->mo_ldd.ldd_flags =
1065                                         SVTYPE_MDT |
1066                                         SVTYPE_MGS;
1067                                         /* Old MDT's are always index 0
1068                                            (pre CMD) */
1069                                         mop->mo_ldd.ldd_svindex = 0;
1070                                 } else {
1071                                         /* The index may not be correct */
1072                                         mop->mo_ldd.ldd_flags =
1073                                         SVTYPE_OST | LDD_F_NEED_INDEX;
1074                                         verrprint("OST with unknown index\n");
1075                                 }
1076                         }
1077                 }
1078
1079                 ret = 0;
1080                 memcpy(mop->mo_ldd.ldd_uuid, lsd.lsd_uuid,
1081                        sizeof(mop->mo_ldd.ldd_uuid));
1082                 mop->mo_ldd.ldd_flags |= LDD_F_UPGRADE14;
1083         }
1084         /* end COMPAT_146 */
1085 out_close:
1086         fclose(filep);
1087
1088 out_rmdir:
1089         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
1090         run_command(cmd, cmdsz);
1091         if (ret)
1092                 verrprint("Failed to read old data (%d)\n", ret);
1093         return ret;
1094 }
1095
1096
1097 void set_defaults(struct mkfs_opts *mop)
1098 {
1099         mop->mo_ldd.ldd_magic = LDD_MAGIC;
1100         mop->mo_ldd.ldd_config_ver = 1;
1101         mop->mo_ldd.ldd_flags = LDD_F_NEED_INDEX | LDD_F_UPDATE | LDD_F_VIRGIN;
1102         mop->mo_mgs_failnodes = 0;
1103         strcpy(mop->mo_ldd.ldd_fsname, "lustre");
1104         if (get_os_version() == 24)
1105                 mop->mo_ldd.ldd_mount_type = LDD_MT_EXT3;
1106         else
1107                 mop->mo_ldd.ldd_mount_type = LDD_MT_LDISKFS;
1108
1109         mop->mo_ldd.ldd_svindex = INDEX_UNASSIGNED;
1110         mop->mo_stripe_count = 1;
1111 }
1112
1113 static inline void badopt(const char *opt, char *type)
1114 {
1115         fprintf(stderr, "%s: '--%s' only valid for %s\n",
1116                 progname, opt, type);
1117         usage(stderr);
1118 }
1119
1120 static int add_param(char *buf, char *key, char *val)
1121 {
1122         int end = sizeof(((struct lustre_disk_data *)0)->ldd_params);
1123         int start = strlen(buf);
1124         int keylen = 0;
1125
1126         if (key)
1127                 keylen = strlen(key);
1128         if (start + 1 + keylen + strlen(val) >= end) {
1129                 fprintf(stderr, "%s: params are too long-\n%s %s%s\n",
1130                         progname, buf, key ? key : "", val);
1131                 return 1;
1132         }
1133
1134         sprintf(buf + start, " %s%s", key ? key : "", val);
1135         return 0;
1136 }
1137
1138 /* from mount_lustre */
1139 /* Get rid of symbolic hostnames for tcp, since kernel can't do lookups */
1140 #define MAXNIDSTR 1024
1141 static char *convert_hostnames(char *s1)
1142 {
1143         char *converted, *s2 = 0, *c, *end, sep;
1144         int left = MAXNIDSTR;
1145         lnet_nid_t nid;
1146
1147         converted = malloc(left);
1148         if (converted == NULL) {
1149                 return NULL;
1150         }
1151
1152         end = s1 + strlen(s1);
1153         c = converted;
1154         while ((left > 0) && (s1 < end)) {
1155                 s2 = strpbrk(s1, ",:");
1156                 if (!s2)
1157                         s2 = end;
1158                 sep = *s2;
1159                 *s2 = '\0';
1160                 nid = libcfs_str2nid(s1);
1161
1162                 if (nid == LNET_NID_ANY) {
1163                         fprintf(stderr, "%s: Can't parse NID '%s'\n", progname, s1);
1164                         free(converted);
1165                         return NULL;
1166                 }
1167                 if (strncmp(libcfs_nid2str(nid), "127.0.0.1",
1168                             strlen("127.0.0.1")) == 0) {
1169                         fprintf(stderr, "%s: The NID '%s' resolves to the "
1170                                 "loopback address '%s'.  Lustre requires a "
1171                                 "non-loopback address.\n",
1172                                 progname, s1, libcfs_nid2str(nid));
1173                         free(converted);
1174                         return NULL;
1175                 }
1176
1177                 c += snprintf(c, left, "%s%c", libcfs_nid2str(nid), sep);
1178                 left = converted + MAXNIDSTR - c;
1179                 s1 = s2 + 1;
1180         }
1181         return converted;
1182 }
1183
1184 int parse_opts(int argc, char *const argv[], struct mkfs_opts *mop,
1185                char **mountopts)
1186 {
1187         static struct option long_opt[] = {
1188                 {"iam-dir", 0, 0, 'a'},
1189                 {"backfstype", 1, 0, 'b'},
1190                 {"stripe-count-hint", 1, 0, 'c'},
1191                 {"comment", 1, 0, 'u'},
1192                 {"configdev", 1, 0, 'C'},
1193                 {"device-size", 1, 0, 'd'},
1194                 {"dryrun", 0, 0, 'n'},
1195                 {"erase-params", 0, 0, 'e'},
1196                 {"failnode", 1, 0, 'f'},
1197                 {"failover", 1, 0, 'f'},
1198                 {"mgs", 0, 0, 'G'},
1199                 {"help", 0, 0, 'h'},
1200                 {"index", 1, 0, 'i'},
1201                 {"mkfsoptions", 1, 0, 'k'},
1202                 {"mgsnode", 1, 0, 'm'},
1203                 {"mgsnid", 1, 0, 'm'},
1204                 {"mdt", 0, 0, 'M'},
1205                 {"fsname",1, 0, 'L'},
1206                 {"noformat", 0, 0, 'n'},
1207                 {"nomgs", 0, 0, 'N'},
1208                 {"mountfsoptions", 1, 0, 'o'},
1209                 {"ost", 0, 0, 'O'},
1210                 {"param", 1, 0, 'p'},
1211                 {"print", 0, 0, 'n'},
1212                 {"quiet", 0, 0, 'q'},
1213                 {"reformat", 0, 0, 'r'},
1214                 {"verbose", 0, 0, 'v'},
1215                 {"writeconf", 0, 0, 'w'},
1216                 {"upgrade_to_18", 0, 0, 'U'},
1217                 {"network", 1, 0, 't'},
1218                 {0, 0, 0, 0}
1219         };
1220         char *optstring = "b:c:C:d:ef:Ghi:k:L:m:MnNo:Op:Pqru:vw";
1221         int opt;
1222         int rc, longidx;
1223
1224         while ((opt = getopt_long(argc, argv, optstring, long_opt, &longidx)) !=
1225                EOF) {
1226                 switch (opt) {
1227                 case 'a': {
1228                         if (IS_MDT(&mop->mo_ldd))
1229                                 mop->mo_ldd.ldd_flags |= LDD_F_IAM_DIR;
1230                         break;
1231                 }
1232                 case 'b': {
1233                         int i = 0;
1234                         while (i < LDD_MT_LAST) {
1235                                 if (strcmp(optarg, mt_str(i)) == 0) {
1236                                         mop->mo_ldd.ldd_mount_type = i;
1237                                         break;
1238                                 }
1239                                 i++;
1240                         }
1241                         break;
1242                 }
1243                 case 'c':
1244                         if (IS_MDT(&mop->mo_ldd)) {
1245                                 int stripe_count = atol(optarg);
1246                                 if (stripe_count <= 0) {
1247                                         fprintf(stderr, "%s: bad stripe count "
1248                                                 "%d\n", progname, stripe_count);
1249                                         return 1;
1250                                 }
1251                                 mop->mo_stripe_count = stripe_count;
1252                         } else {
1253                                 badopt(long_opt[longidx].name, "MDT");
1254                                 return 1;
1255                         }
1256                         break;
1257                 case 'C': /* Configdev */
1258                         //FIXME
1259                         printf("Configdev not implemented\n");
1260                         return 1;
1261                 case 'd':
1262                         mop->mo_device_sz = atol(optarg);
1263                         break;
1264                 case 'e':
1265                         mop->mo_ldd.ldd_params[0] = '\0';
1266                         /* Must update the mgs logs */
1267                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1268                         break;
1269                 case 'f': {
1270                         char *nids = convert_hostnames(optarg);
1271                         if (!nids)
1272                                 return 1;
1273                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_FAILNODE,
1274                                        nids);
1275                         free(nids);
1276                         if (rc)
1277                                 return rc;
1278                         /* Must update the mgs logs */
1279                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1280                         failover = 1;
1281                         break;
1282                 }
1283                 case 'G':
1284                         mop->mo_ldd.ldd_flags |= SVTYPE_MGS;
1285                         break;
1286                 case 'h':
1287                         usage(stdout);
1288                         return 1;
1289                 case 'i':
1290                         if (!(mop->mo_ldd.ldd_flags &
1291                               (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1292                                LDD_F_WRITECONF))) {
1293                                 fprintf(stderr, "%s: cannot change the index of"
1294                                         " a registered target\n", progname);
1295                                 return 1;
1296                         }
1297                         if (IS_MDT(&mop->mo_ldd) || IS_OST(&mop->mo_ldd)) {
1298                                 mop->mo_ldd.ldd_svindex = atol(optarg);
1299                                 mop->mo_ldd.ldd_flags &= ~LDD_F_NEED_INDEX;
1300                         } else {
1301                                 badopt(long_opt[longidx].name, "MDT,OST");
1302                                 return 1;
1303                         }
1304                         break;
1305                 case 'k':
1306                         strscpy(mop->mo_mkfsopts, optarg,
1307                                 sizeof(mop->mo_mkfsopts));
1308                         break;
1309                 case 'L': {
1310                         char *tmp;
1311                         if (!(mop->mo_flags & MO_FORCEFORMAT) &&
1312                             (!(mop->mo_ldd.ldd_flags &
1313                                (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1314                                 LDD_F_WRITECONF)))) {
1315                                 fprintf(stderr, "%s: cannot change the name of"
1316                                         " a registered target\n", progname);
1317                                 return 1;
1318                         }
1319                         if ((strlen(optarg) < 1) || (strlen(optarg) > 8)) {
1320                                 fprintf(stderr, "%s: filesystem name must be "
1321                                         "1-8 chars\n", progname);
1322                                 return 1;
1323                         }
1324                         if ((tmp = strpbrk(optarg, "/:"))) {
1325                                 fprintf(stderr, "%s: char '%c' not allowed in "
1326                                         "filesystem name\n", progname, *tmp);
1327                                 return 1;
1328                         }
1329                         strscpy(mop->mo_ldd.ldd_fsname, optarg,
1330                                 sizeof(mop->mo_ldd.ldd_fsname));
1331                         break;
1332                 }
1333                 case 'm': {
1334                         char *nids = convert_hostnames(optarg);
1335                         if (!nids)
1336                                 return 1;
1337                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_MGSNODE,
1338                                        nids);
1339                         free(nids);
1340                         if (rc)
1341                                 return rc;
1342                         mop->mo_mgs_failnodes++;
1343                         break;
1344                 }
1345                 case 'M':
1346                         mop->mo_ldd.ldd_flags |= SVTYPE_MDT;
1347                         break;
1348                 case 'n':
1349                         print_only++;
1350                         break;
1351                 case 'N':
1352                         mop->mo_ldd.ldd_flags &= ~SVTYPE_MGS;
1353                         break;
1354                 case 'o':
1355                         *mountopts = optarg;
1356                         break;
1357                 case 'O':
1358                         mop->mo_ldd.ldd_flags |= SVTYPE_OST;
1359                         break;
1360                 case 'p':
1361                         rc = add_param(mop->mo_ldd.ldd_params, NULL, optarg);
1362                         if (rc)
1363                                 return rc;
1364                         /* Must update the mgs logs */
1365                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1366                         break;
1367                 case 'q':
1368                         verbose--;
1369                         break;
1370                 case 'r':
1371                         mop->mo_flags |= MO_FORCEFORMAT;
1372                         break;
1373                 case 't':
1374                         if (!IS_MDT(&mop->mo_ldd) && !IS_OST(&mop->mo_ldd)) {
1375                                 badopt(long_opt[longidx].name, "MDT,OST");
1376                                 return 1;
1377                         }
1378
1379                         if (!optarg)
1380                                 return 1;
1381
1382                         rc = add_param(mop->mo_ldd.ldd_params,
1383                                        PARAM_NETWORK, optarg);
1384                         if (rc != 0)
1385                                 return rc;
1386                         /* Must update the mgs logs */
1387                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1388                         break;
1389                 case 'u':
1390                         strscpy(mop->mo_ldd.ldd_userdata, optarg,
1391                                 sizeof(mop->mo_ldd.ldd_userdata));
1392                         break;
1393                 case 'v':
1394                         verbose++;
1395                         break;
1396                 case 'w':
1397                         mop->mo_ldd.ldd_flags |= LDD_F_WRITECONF;
1398                         break;
1399                 case 'U':
1400                         upgrade_to_18 = 1;
1401                         break;
1402                 default:
1403                         if (opt != '?') {
1404                                 fatal();
1405                                 fprintf(stderr, "Unknown option '%c'\n", opt);
1406                         }
1407                         return EINVAL;
1408                 }
1409         }//while
1410
1411         /* Last arg is device */
1412         if (optind != argc - 1) {
1413                 fatal();
1414                 fprintf(stderr, "Bad argument: %s\n", argv[optind]);
1415                 return EINVAL;
1416         }
1417
1418         /* single argument: <device> */
1419         if (argc == 2)
1420                 ++print_only;
1421
1422         return 0;
1423 }
1424
1425 /* Search for opt in mntlist, returning true if found.
1426  */
1427 static int in_mntlist(char *opt, char *mntlist)
1428 {
1429         char *ml, *mlp, *item, *ctx = NULL;
1430
1431         if (!(ml = strdup(mntlist))) {
1432                 fprintf(stderr, "%s: out of memory\n", progname);
1433                 exit(1);
1434         }
1435         mlp = ml;
1436         while ((item = strtok_r(mlp, ",", &ctx))) {
1437                 if (!strcmp(opt, item))
1438                         break;
1439                 mlp = NULL;
1440         }
1441         free(ml);
1442         return (item != NULL);
1443 }
1444
1445 /* Issue a message on stderr for every item in wanted_mountopts that is not
1446  * present in mountopts.  The justwarn boolean toggles between error and
1447  * warning message.  Return an error count.
1448  */
1449 static int check_mountfsoptions(char *mountopts, char *wanted_mountopts,
1450                                 int justwarn)
1451 {
1452         char *ml, *mlp, *item, *ctx = NULL;
1453         int errors = 0;
1454
1455         if (!(ml = strdup(wanted_mountopts))) {
1456                 fprintf(stderr, "%s: out of memory\n", progname);
1457                 exit(1);
1458         }
1459         mlp = ml;
1460         while ((item = strtok_r(mlp, ",", &ctx))) {
1461                 if (!in_mntlist(item, mountopts)) {
1462                         fprintf(stderr, "%s: %s mount option `%s' is missing\n",
1463                                 progname, justwarn ? "Warning: default"
1464                                 : "Error: mandatory", item);
1465                         errors++;
1466                 }
1467                 mlp = NULL;
1468         }
1469         free(ml);
1470         return errors;
1471 }
1472
1473 /* Trim embedded white space, leading and trailing commas from string s.
1474  */
1475 static void trim_mountfsoptions(char *s)
1476 {
1477         char *p;
1478
1479         for (p = s; *p; ) {
1480                 if (isspace(*p)) {
1481                         memmove(p, p + 1, strlen(p + 1) + 1);
1482                         continue;
1483                 }
1484                 p++;
1485         }
1486
1487         while (s[0] == ',')
1488                 memmove(&s[0], &s[1], strlen(&s[1]) + 1);
1489
1490         p = s + strlen(s) - 1;
1491         while (p >= s && *p == ',')
1492                 *p-- = '\0';
1493 }
1494
1495 int main(int argc, char *const argv[])
1496 {
1497         struct mkfs_opts mop;
1498         struct lustre_disk_data *ldd;
1499         char *mountopts = NULL;
1500         char always_mountopts[512] = "";
1501         char default_mountopts[512] = "";
1502         int ret = 0;
1503
1504         if ((progname = strrchr(argv[0], '/')) != NULL)
1505                 progname++;
1506         else
1507                 progname = argv[0];
1508
1509         if ((argc < 2) || (argv[argc - 1][0] == '-')) {
1510                 usage(stderr);
1511                 return(EINVAL);
1512         }
1513
1514         memset(&mop, 0, sizeof(mop));
1515         set_defaults(&mop);
1516
1517         /* device is last arg */
1518         strscpy(mop.mo_device, argv[argc - 1], sizeof(mop.mo_device));
1519
1520         /* Are we using a loop device? */
1521         ret = is_block(mop.mo_device);
1522         if (ret < 0)
1523                 goto out;
1524         if (ret == 0)
1525                 mop.mo_flags |= MO_IS_LOOP;
1526
1527 #ifdef TUNEFS
1528         /* For tunefs, we must read in the old values before parsing any
1529            new ones. */
1530
1531         /* Check whether the disk has already been formatted by mkfs.lustre */
1532         ret = is_lustre_target(&mop);
1533         if (ret == 0) {
1534                 fatal();
1535                 fprintf(stderr, "Device %s has not been formatted with "
1536                         "mkfs.lustre\n", mop.mo_device);
1537                 ret = ENODEV;
1538                 goto out;
1539         }
1540
1541         ret = read_local_files(&mop);
1542         if (ret) {
1543                 fatal();
1544                 fprintf(stderr, "Failed to read previous Lustre data from %s "
1545                         "(%d)\n", mop.mo_device, ret);
1546                 goto out;
1547         }
1548         if (strstr(mop.mo_ldd.ldd_params, PARAM_MGSNODE))
1549             mop.mo_mgs_failnodes++;
1550
1551         if (verbose > 0)
1552                 print_ldd("Read previous values", &(mop.mo_ldd));
1553 #endif
1554
1555         ret = parse_opts(argc, argv, &mop, &mountopts);
1556         if (ret)
1557                 goto out;
1558
1559         ldd = &mop.mo_ldd;
1560
1561         if (!(IS_MDT(ldd) || IS_OST(ldd) || IS_MGS(ldd))) {
1562                 fatal();
1563                 fprintf(stderr, "must set target type: MDT,OST,MGS\n");
1564                 ret = EINVAL;
1565                 goto out;
1566         }
1567
1568         if (((IS_MDT(ldd) || IS_MGS(ldd))) && IS_OST(ldd)) {
1569                 fatal();
1570                 fprintf(stderr, "OST type is exclusive with MDT,MGS\n");
1571                 ret = EINVAL;
1572                 goto out;
1573         }
1574
1575         if ((mop.mo_ldd.ldd_flags & (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) ==
1576             (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) {
1577                 fatal();
1578                 fprintf(stderr, "Can't find the target index, "
1579                         "specify with --index\n");
1580                 ret = EINVAL;
1581                 goto out;
1582         }
1583 #if 0
1584         /*
1585          * Comment out these 2 checks temporarily, since for multi-MDSes
1586          * in single node only 1 mds node could have mgs service
1587          */
1588         if (IS_MDT(ldd) && !IS_MGS(ldd) && (mop.mo_mgs_failnodes == 0)) {
1589                 verrprint("No management node specified, adding MGS to this "
1590                           "MDT\n");
1591                 ldd->ldd_flags |= SVTYPE_MGS;
1592         }
1593         if (!IS_MGS(ldd) && (mop.mo_mgs_failnodes == 0)) {
1594                 fatal();
1595                 if (IS_MDT(ldd))
1596                         fprintf(stderr, "Must specify --mgs or --mgsnode=\n");
1597                 else
1598                         fprintf(stderr, "Must specify --mgsnode=\n");
1599                 ret = EINVAL;
1600                 goto out;
1601         }
1602 #endif
1603
1604         /* These are the permanent mount options (always included) */
1605         switch (ldd->ldd_mount_type) {
1606         case LDD_MT_EXT3:
1607         case LDD_MT_LDISKFS:
1608         case LDD_MT_LDISKFS2: {
1609                 strscat(default_mountopts, ",errors=remount-ro",
1610                         sizeof(default_mountopts));
1611                 if (IS_MDT(ldd) || IS_MGS(ldd))
1612                         strscat(always_mountopts, ",iopen_nopriv,user_xattr",
1613                                 sizeof(always_mountopts));
1614                 if ((get_os_version() == 24) && IS_OST(ldd))
1615                         strscat(always_mountopts, ",asyncdel",
1616                                 sizeof(always_mountopts));
1617                 /* NB: Files created while extents are enabled cannot be read
1618                    if mounted with a kernel that doesn't include the Lustre ldiskfs
1619                    patches! */
1620                 if (IS_OST(ldd) &&
1621                     (ldd->ldd_mount_type == LDD_MT_LDISKFS ||
1622                      ldd->ldd_mount_type == LDD_MT_LDISKFS2)) {
1623                         strscat(default_mountopts, ",extents,mballoc",
1624                                 sizeof(default_mountopts));
1625                 }
1626                 break;
1627         }
1628         case LDD_MT_SMFS: {
1629                 mop.mo_flags |= MO_IS_LOOP;
1630                 sprintf(always_mountopts, ",type=ext3,dev=%s",
1631                         mop.mo_device);
1632                 break;
1633         }
1634         default: {
1635                 fatal();
1636                 fprintf(stderr, "unknown fs type %d '%s'\n",
1637                         ldd->ldd_mount_type,
1638                         MT_STR(ldd));
1639                 ret = EINVAL;
1640                 goto out;
1641         }
1642         }
1643
1644         if (mountopts) {
1645                 trim_mountfsoptions(mountopts);
1646                 (void)check_mountfsoptions(mountopts, default_mountopts, 1);
1647                 if (check_mountfsoptions(mountopts, always_mountopts, 0)) {
1648                         ret = EINVAL;
1649                         goto out;
1650                 }
1651                 sprintf(ldd->ldd_mount_opts, "%s", mountopts);
1652         } else {
1653 #ifdef TUNEFS
1654                 if (ldd->ldd_mount_opts[0] == 0)
1655                         /* use the defaults unless old opts exist */
1656 #endif
1657                 {
1658                         sprintf(ldd->ldd_mount_opts, "%s%s",
1659                                 always_mountopts, default_mountopts);
1660                         trim_mountfsoptions(ldd->ldd_mount_opts);
1661                 }
1662         }
1663
1664         server_make_name(ldd->ldd_flags, ldd->ldd_svindex,
1665                          ldd->ldd_fsname, ldd->ldd_svname);
1666
1667         if (verbose >= 0)
1668                 print_ldd("Permanent disk data", ldd);
1669
1670         if (print_only) {
1671                 printf("exiting before disk write.\n");
1672                 goto out;
1673         }
1674
1675         if (check_mtab_entry(mop.mo_device))
1676                 return(EEXIST);
1677
1678         /* Create the loopback file */
1679         if (mop.mo_flags & MO_IS_LOOP) {
1680                 ret = access(mop.mo_device, F_OK);
1681                 if (ret)
1682                         ret = errno;
1683 #ifndef TUNEFS /* mkfs.lustre */
1684                 /* Reformat the loopback file */
1685                 if (ret || (mop.mo_flags & MO_FORCEFORMAT))
1686                         ret = loop_format(&mop);
1687 #endif
1688                 if (ret == 0)
1689                         ret = loop_setup(&mop);
1690                 if (ret) {
1691                         fatal();
1692                         fprintf(stderr, "Loop device setup for %s failed: %s\n",
1693                                 mop.mo_device, strerror(ret));
1694                         goto out;
1695                 }
1696         }
1697
1698 #ifndef TUNEFS /* mkfs.lustre */
1699         /* Check whether the disk has already been formatted by mkfs.lustre */
1700         if (!(mop.mo_flags & MO_FORCEFORMAT)) {
1701                 ret = is_lustre_target(&mop);
1702                 if (ret) {
1703                         fatal();
1704                         fprintf(stderr, "Device %s was previously formatted "
1705                                 "for lustre. Use --reformat to reformat it, "
1706                                 "or tunefs.lustre to modify.\n",
1707                                 mop.mo_device);
1708                         goto out;
1709                 }
1710         }
1711
1712         /* Format the backing filesystem */
1713         ret = make_lustre_backfs(&mop);
1714         if (ret != 0) {
1715                 fatal();
1716                 fprintf(stderr, "mkfs failed %d\n", ret);
1717                 goto out;
1718         }
1719 #endif
1720
1721         /* Write our config files */
1722         ret = write_local_files(&mop);
1723         if (ret != 0) {
1724                 fatal();
1725                 fprintf(stderr, "failed to write local files\n");
1726                 goto out;
1727         }
1728
1729 out:
1730         loop_cleanup(&mop);
1731
1732         /* Fix any crazy return values from system() */
1733         if (ret && ((ret & 255) == 0))
1734                 return (1);
1735         if (ret)
1736                 verrprint("%s: exiting with %d (%s)\n",
1737                           progname, ret, strerror(ret));
1738         return (ret);
1739 }