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