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