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