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