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