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