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