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