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