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