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