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