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