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