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