Whamcloud - gitweb
b=12054
[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
37 #include <string.h>
38 #include <getopt.h>
39 #include <limits.h>
40
41 #ifdef __linux__
42 # include <linux/fs.h> /* for BLKGETSIZE64 */
43 #endif
44 #include <lustre_disk.h>
45 #include <lustre_param.h>
46 #include <lnet/lnetctl.h>
47 #include <lustre_ver.h>
48
49 #ifndef PATH_MAX
50 #define PATH_MAX 4096
51 #endif
52
53 #define MAX_LOOP_DEVICES 16
54 #define L_BLOCK_SIZE 4096
55 #define INDEX_UNASSIGNED 0xFFFF
56 #define MO_IS_LOOP     0x01
57 #define MO_FORCEFORMAT 0x02
58
59 /* used to describe the options to format the lustre disk, not persistent */
60 struct mkfs_opts {
61         struct lustre_disk_data mo_ldd; /* to be written in MOUNT_DATA_FILE */
62         char  mo_device[128];           /* disk device name */
63         char  mo_mkfsopts[128];         /* options to the backing-store mkfs */
64         char  mo_loopdev[128];          /* in case a loop dev is needed */
65         __u64 mo_device_sz;             /* in KB */
66         int   mo_stripe_count;
67         int   mo_flags; 
68         int   mo_mgs_failnodes;
69 };
70
71 static char *progname;
72 static int verbose = 1;
73 static int print_only = 0;
74
75
76 void usage(FILE *out)
77 {
78         fprintf(out, "%s v"LUSTRE_VERSION_STRING"\n", progname);
79         fprintf(out, "usage: %s <target types> [options] <device>\n", progname);
80         fprintf(out, 
81                 "\t<device>:block device or file (e.g /dev/sda or /tmp/ost1)\n"
82                 "\ttarget types:\n"
83                 "\t\t--ost: object storage, mutually exclusive with mdt,mgs\n"
84                 "\t\t--mdt: metadata storage, mutually exclusive with ost\n"
85                 "\t\t--mgs: configuration management service - one per site\n"
86                 "\toptions (in order of popularity):\n"
87                 "\t\t--mgsnode=<nid>[,<...>] : NID(s) of a remote mgs node\n"
88                 "\t\t\trequired for all targets other than the mgs node\n"
89                 "\t\t--fsname=<filesystem_name> : default is 'lustre'\n"
90                 "\t\t--failnode=<nid>[,<...>] : NID(s) of a failover partner\n"
91                 "\t\t--param <key>=<value> : set a permanent parameter\n"
92                 "\t\t\te.g. --param sys.timeout=40\n"
93                 "\t\t\t     --param lov.stripesize=2M\n"
94                 "\t\t--index=#N : target index (i.e. ost index within the lov)\n"
95                 /* FIXME implement 1.6.x
96                 "\t\t--configdev=<altdevice|file>: store configuration info\n"
97                 "\t\t\tfor this device on an alternate device\n"
98                 */
99                 "\t\t--comment=<user comment>: arbitrary user string (%d bytes)\n"
100                 "\t\t--mountfsoptions=<opts> : permanent mount options\n"
101 #ifndef TUNEFS
102                 "\t\t--backfstype=<fstype> : backing fs type (ext3, ldiskfs)\n"
103                 "\t\t--device-size=#N(KB) : device size for loop devices\n"
104                 "\t\t--mkfsoptions=<opts> : format options\n"
105                 "\t\t--reformat: overwrite an existing disk\n"
106                 "\t\t--stripe-count-hint=#N : used for optimizing MDT inode size\n"
107 #else
108                 "\t\t--erase-params : erase all old parameter settings\n"
109                 "\t\t--nomgs: turn off MGS service on this MDT\n"
110                 "\t\t--writeconf: erase all config logs for this fs.\n"
111 #endif
112                 "\t\t--dryrun: just report what we would do; "
113                 "don't write to disk\n"
114                 "\t\t--verbose : e.g. show mkfs progress\n"
115                 "\t\t--quiet\n",
116                 (int)sizeof(((struct lustre_disk_data *)0)->ldd_userdata));
117         return;
118 }
119
120 #define vprint if (verbose > 0) printf
121 #define verrprint if (verbose >= 0) printf
122
123 static void fatal(void)
124 {
125         verbose = 0;
126         fprintf(stderr, "\n%s FATAL: ", progname);
127 }
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 int run_command(char *cmd, int cmdsz)
184 {
185         char log[] = "/tmp/mkfs_logXXXXXX";
186         int fd = -1, rc;
187         
188         if ((cmdsz - strlen(cmd)) < 6) {
189                 fatal();
190                 fprintf(stderr, "Command buffer overflow: %.*s...\n",
191                         cmdsz, cmd);
192                 return ENOMEM;
193         }
194
195         if (verbose > 1) {
196                 printf("cmd: %s\n", cmd);
197         } else {
198                 if ((fd = mkstemp(log)) >= 0) {
199                         close(fd);
200                         strcat(cmd, " >");
201                         strcat(cmd, log);
202                 }
203         }
204         strcat(cmd, " 2>&1");
205
206         /* Can't use popen because we need the rv of the command */
207         rc = system(cmd);
208         if (rc && (fd >= 0)) {
209                 char buf[128];
210                 FILE *fp;
211                 fp = fopen(log, "r");
212                 if (fp) {
213                         while (fgets(buf, sizeof(buf), fp) != NULL) {
214                                 printf("   %s", buf);
215                         }
216                         fclose(fp);
217                 }
218         }
219         if (fd >= 0) 
220                 remove(log);
221         return rc;
222 }                                                       
223
224 static int check_mtab_entry(char *spec)
225 {
226         FILE *fp;
227         struct mntent *mnt;
228
229         fp = setmntent(MOUNTED, "r");
230         if (fp == NULL)
231                 return(0);
232
233         while ((mnt = getmntent(fp)) != NULL) {
234                 if (strcmp(mnt->mnt_fsname, spec) == 0) {
235                         endmntent(fp);
236                         fprintf(stderr, "%s: according to %s %s is "
237                                 "already mounted on %s\n",
238                                 progname, MOUNTED, spec, mnt->mnt_dir);
239                         return(EEXIST);
240                 }
241         }
242         endmntent(fp);
243
244         return(0);
245 }
246
247 /*============ disk dev functions ===================*/
248
249 /* Setup a file in the first unused loop_device */
250 int loop_setup(struct mkfs_opts *mop)
251 {
252         char loop_base[20];
253         char l_device[64];
254         int i,ret = 0;
255
256         /* Figure out the loop device names */
257         if (!access("/dev/loop0", F_OK | R_OK))
258                 strcpy(loop_base, "/dev/loop\0");
259         else if (!access("/dev/loop/0", F_OK | R_OK))
260                 strcpy(loop_base, "/dev/loop/\0");
261         else {
262                 fprintf(stderr, "%s: can't access loop devices\n", progname);
263                 return EACCES;
264         }
265
266         /* Find unused loop device */
267         for (i = 0; i < MAX_LOOP_DEVICES; i++) {
268                 char cmd[PATH_MAX];
269                 int cmdsz = sizeof(cmd);
270                 sprintf(l_device, "%s%d", loop_base, i);
271                 if (access(l_device, F_OK | R_OK)) 
272                         break;
273                 snprintf(cmd, cmdsz, "losetup %s > /dev/null 2>&1", l_device);
274                 ret = system(cmd);
275                 
276                 /* losetup gets 1 (ret=256) for non-set-up device */
277                 if (ret) {
278                         /* Set up a loopback device to our file */
279                         snprintf(cmd, cmdsz, "losetup %s %s", l_device,
280                                  mop->mo_device);
281                         ret = run_command(cmd, cmdsz);
282                         if (ret) {
283                                 fprintf(stderr, "%s: error %d on losetup: %s\n",
284                                         progname, ret, strerror(ret));
285                                 return ret;
286                         }
287                         strscpy(mop->mo_loopdev, l_device, 
288                                 sizeof(mop->mo_loopdev));
289                         return ret;
290                 }
291         }
292         
293         fprintf(stderr, "%s: out of loop devices!\n", progname);
294         return EMFILE;
295 }       
296
297 int loop_cleanup(struct mkfs_opts *mop)
298 {
299         char cmd[150];
300         int ret = 1;
301         if ((mop->mo_flags & MO_IS_LOOP) && *mop->mo_loopdev) {
302                 sprintf(cmd, "losetup -d %s", mop->mo_loopdev);
303                 ret = run_command(cmd, sizeof(cmd));
304         }
305         return ret;
306 }
307
308 /* Determine if a device is a block device (as opposed to a file) */
309 int is_block(char* devname)
310 {
311         struct stat st;
312         int ret = 0;
313
314         ret = access(devname, F_OK);
315         if (ret != 0) 
316                 return 0;
317         ret = stat(devname, &st);
318         if (ret != 0) {
319                 fprintf(stderr, "%s: cannot stat %s\n", progname, devname);
320                 return -1;
321         }
322         return S_ISBLK(st.st_mode);
323 }
324
325 __u64 get_device_size(char* device) 
326 {
327         int ret, fd;
328         __u64 size = 0;
329
330         fd = open(device, O_RDONLY);
331         if (fd < 0) {
332                 fprintf(stderr, "%s: cannot open %s: %s\n", 
333                         progname, device, strerror(errno));
334                 return 0;
335         }
336
337 #ifdef BLKGETSIZE64
338         /* size in bytes. bz5831 */
339         ret = ioctl(fd, BLKGETSIZE64, (void*)&size);
340 #else
341         {
342                 __u32 lsize = 0;
343                 /* size in blocks */
344                 ret = ioctl(fd, BLKGETSIZE, (void*)&lsize);
345                 size = (__u64)lsize * 512; 
346         }
347 #endif
348         close(fd);
349         if (ret < 0) {
350                 fprintf(stderr, "%s: size ioctl failed: %s\n", 
351                         progname, strerror(errno));
352                 return 0;
353         }
354         
355         vprint("device size = "LPU64"MB\n", size >> 20);
356         /* return value in KB */
357         return size >> 10;
358 }
359
360 int loop_format(struct mkfs_opts *mop)
361 {
362         int ret = 0;
363        
364         if (mop->mo_device_sz == 0) {
365                 fatal();
366                 fprintf(stderr, "loop device requires a --device-size= "
367                         "param\n");
368                 return EINVAL;
369         }
370
371         ret = creat(mop->mo_device, S_IRUSR|S_IWUSR);
372         ret = truncate(mop->mo_device, mop->mo_device_sz * 1024);
373         if (ret != 0) {
374                 ret = errno;
375                 fprintf(stderr, "%s: Unable to create backing store: %d\n", 
376                         progname, ret);
377         }
378
379         return ret;
380 }
381
382 /* Check whether the file exists in the device */
383 static int file_in_dev(char *file_name, char *dev_name)
384 {
385         FILE *fp;
386         char debugfs_cmd[256];
387         unsigned int inode_num;
388         int i;
389
390         /* Construct debugfs command line. */
391         snprintf(debugfs_cmd, sizeof(debugfs_cmd), 
392                 "debugfs -c -R 'stat %s' %s 2>&1 | egrep '(Inode|unsupported)'",
393                 file_name, dev_name);
394
395         fp = popen(debugfs_cmd, "r");
396         if (!fp) {
397                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
398                 return 0;
399         }
400
401         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
402                 pclose(fp);
403                 return 1;
404         }
405         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd), fp);
406         if (i) {
407                 debugfs_cmd[i] = 0;
408                 fprintf(stderr, "%s", debugfs_cmd);
409                 if (strstr(debugfs_cmd, "unsupported feature")) {
410                         fprintf(stderr, "In all likelihood, the "
411                                 "'unsupported feature' is 'extents', which "
412                                 "older debugfs does not understand.\n"  
413                                 "Use e2fsprogs-1.38-cfs1 or later, available "
414                                 "from ftp://ftp.lustre.org/pub/lustre/other/"
415                                 "e2fsprogs/\n");
416                 }
417                 return -1;
418         }
419         pclose(fp);
420         return 0;
421 }
422
423 /* Check whether the device has already been used with lustre */
424 static int is_lustre_target(struct mkfs_opts *mop)
425 {
426         int rc;
427         vprint("checking for existing Lustre data: ");
428         
429         if ((rc = file_in_dev(MOUNT_DATA_FILE, mop->mo_device))) {
430                 vprint("found %s\n", 
431                        (rc == 1) ? MOUNT_DATA_FILE : "extents");
432                  /* in the -1 case, 'extents' means this really IS a lustre
433                     target */
434                 return rc;
435         }
436         
437         if ((rc = file_in_dev(LAST_RCVD, mop->mo_device))) { 
438                 vprint("found %s\n", LAST_RCVD);
439                 return rc; 
440         }
441
442         vprint("not found\n");
443         return 0; /* The device is not a lustre target. */
444 }
445
446 /* Build fs according to type */
447 int make_lustre_backfs(struct mkfs_opts *mop)
448 {
449         char mkfs_cmd[PATH_MAX];
450         char buf[64];
451         char *dev;
452         int ret = 0;
453         int block_count = 0;
454
455         if (mop->mo_device_sz != 0) {
456                 if (mop->mo_device_sz < 8096){
457                         fprintf(stderr, "%s: size of filesystem must be larger "
458                                 "than 8MB, but is set to %lluKB\n",
459                                 progname, (long long)mop->mo_device_sz);
460                         return EINVAL;
461                 }
462                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
463         }
464
465         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
466             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
467             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
468                 __u64 device_sz = mop->mo_device_sz;
469
470                 /* we really need the size */
471                 if (device_sz == 0) {
472                         device_sz = get_device_size(mop->mo_device);
473                         if (device_sz == 0)
474                                 return ENODEV;
475                 }
476
477                 /* Journal size in MB */
478                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
479                         /* Choose our own default journal size */
480                         long journal_sz = 0, max_sz;
481                         if (device_sz > 1024 * 1024) /* 1GB */
482                                 journal_sz = (device_sz / 102400) * 4;
483                         /* man mkfs.ext3 */
484                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
485                         if (journal_sz > max_sz)
486                                 journal_sz = max_sz;
487                         if (journal_sz) {
488                                 sprintf(buf, " -J size=%ld", journal_sz);
489                                 strscat(mop->mo_mkfsopts, buf, 
490                                         sizeof(mop->mo_mkfsopts));
491                         }
492                 }
493
494                 /* bytes_per_inode: disk size / num inodes */
495                 if (strstr(mop->mo_mkfsopts, "-i") == NULL) {
496                         long bytes_per_inode = 0;
497                                         
498                         if (IS_MDT(&mop->mo_ldd)) 
499                                 bytes_per_inode = 4096;
500
501                         /* Allocate fewer inodes on large OST devices.  Most
502                            filesystems can be much more aggressive than even 
503                            this. */
504                         if ((IS_OST(&mop->mo_ldd) && (device_sz > 1000000))) 
505                                 bytes_per_inode = 16384;
506                         
507                         if (bytes_per_inode > 0) {
508                                 sprintf(buf, " -i %ld", bytes_per_inode);
509                                 strscat(mop->mo_mkfsopts, buf,
510                                         sizeof(mop->mo_mkfsopts));
511                         }
512                 }
513                 
514                 /* Inode size (for extended attributes) */
515                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
516                         long inode_size = 0;
517                         if (IS_MDT(&mop->mo_ldd)) {
518                                 if (mop->mo_stripe_count > 72)
519                                         inode_size = 512; /* bz 7241 */
520                                 /* cray stripes across all osts (>60) */
521                                 else if (mop->mo_stripe_count > 32)
522                                         inode_size = 2048;
523                                 else if (mop->mo_stripe_count > 10)
524                                         inode_size = 1024;
525                                 else
526                                         inode_size = 512;
527                         } else if (IS_OST(&mop->mo_ldd)) {
528                                 /* now as we store fids in EA on OST we need
529                                    to make inode bigger */
530                                 inode_size = 256;
531                         }
532
533                         if (inode_size > 0) {
534                                 sprintf(buf, " -I %ld", inode_size);
535                                 strscat(mop->mo_mkfsopts, buf,
536                                         sizeof(mop->mo_mkfsopts));
537                         }
538                         
539                 }
540
541                 if (verbose < 2) {
542                         strscat(mop->mo_mkfsopts, " -q", 
543                                 sizeof(mop->mo_mkfsopts));
544                 }
545
546                 if (strstr(mop->mo_mkfsopts, "-O") == NULL) {
547                         /* Enable hashed b-tree directory lookup in large dirs
548                            bz6224 */
549                         strscat(mop->mo_mkfsopts, " -O dir_index",
550                                 sizeof(mop->mo_mkfsopts));
551                         /* ldiskfs2: do not initialize all groups. */
552                         if (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)
553                                 strscat(mop->mo_mkfsopts, ",uninit_groups",
554                                         sizeof(mop->mo_mkfsopts));
555                 }
556
557                 /* Allow reformat of full devices (as opposed to 
558                    partitions.)  We already checked for mounted dev. */
559                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
560
561                 snprintf(mkfs_cmd, sizeof(mkfs_cmd), 
562                          "mkfs.ext2 -j -b %d -L %s ", L_BLOCK_SIZE,
563                          mop->mo_ldd.ldd_svname);
564
565         } else if (mop->mo_ldd.ldd_mount_type == LDD_MT_REISERFS) {
566                 long journal_sz = 0; /* FIXME default journal size */
567                 if (journal_sz > 0) { 
568                         sprintf(buf, " --journal_size %ld", journal_sz);
569                         strscat(mop->mo_mkfsopts, buf,
570                                 sizeof(mop->mo_mkfsopts));
571                 }
572                 snprintf(mkfs_cmd, sizeof(mkfs_cmd), "mkreiserfs -ff ");
573
574         } else {
575                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
576                         progname, mop->mo_ldd.ldd_mount_type, 
577                         MT_STR(&mop->mo_ldd));
578                 return EINVAL;
579         }
580
581         /* For loop device format the dev, not the filename */
582         dev = mop->mo_device;
583         if (mop->mo_flags & MO_IS_LOOP) 
584                 dev = mop->mo_loopdev;
585         
586         vprint("formatting backing filesystem %s on %s\n",
587                MT_STR(&mop->mo_ldd), dev);
588         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
589         vprint("\t4k blocks     %d\n", block_count);
590         vprint("\toptions       %s\n", mop->mo_mkfsopts);
591
592         /* mkfs_cmd's trailing space is important! */
593         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
594         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
595         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
596         if (block_count != 0) {
597                 sprintf(buf, " %d", block_count);
598                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
599         }
600
601         vprint("mkfs_cmd = %s\n", mkfs_cmd);
602         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
603         if (ret) {
604                 fatal();
605                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
606         }
607         return ret;
608 }
609
610 /* ==================== Lustre config functions =============*/
611
612 void print_ldd(char *str, struct lustre_disk_data *ldd)
613 {
614         printf("\n   %s:\n", str);
615         printf("Target:     %s\n", ldd->ldd_svname);
616         if (ldd->ldd_svindex == INDEX_UNASSIGNED) 
617                 printf("Index:      unassigned\n");
618         else
619                 printf("Index:      %d\n", ldd->ldd_svindex);
620         if (ldd->ldd_uuid[0])
621                 printf("UUID:       %s\n", (char *)ldd->ldd_uuid);
622         printf("Lustre FS:  %s\n", ldd->ldd_fsname);
623         printf("Mount type: %s\n", MT_STR(ldd));
624         printf("Flags:      %#x\n", ldd->ldd_flags);
625         printf("              (%s%s%s%s%s%s%s%s)\n",
626                IS_MDT(ldd) ? "MDT ":"", 
627                IS_OST(ldd) ? "OST ":"",
628                IS_MGS(ldd) ? "MGS ":"",
629                ldd->ldd_flags & LDD_F_NEED_INDEX ? "needs_index ":"",
630                ldd->ldd_flags & LDD_F_VIRGIN     ? "first_time ":"",
631                ldd->ldd_flags & LDD_F_UPDATE     ? "update ":"",
632                ldd->ldd_flags & LDD_F_WRITECONF  ? "writeconf ":"",
633                ldd->ldd_flags & LDD_F_UPGRADE14  ? "upgrade1.4 ":"");
634         printf("Persistent mount opts: %s\n", ldd->ldd_mount_opts);
635         printf("Parameters:%s\n", ldd->ldd_params);
636         if (ldd->ldd_userdata[0])
637                 printf("Comment: %s\n", ldd->ldd_userdata);
638         printf("\n");
639 }
640
641 /* Write the server config files */
642 int write_local_files(struct mkfs_opts *mop)
643 {
644         char mntpt[] = "/tmp/mntXXXXXX";
645         char filepnm[128];
646         char *dev;
647         FILE *filep;
648         int ret = 0;
649
650         /* Mount this device temporarily in order to write these files */
651         if (!mkdtemp(mntpt)) {
652                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
653                         progname, mntpt, strerror(errno));
654                 return errno;
655         }
656
657         dev = mop->mo_device;
658         if (mop->mo_flags & MO_IS_LOOP) 
659                 dev = mop->mo_loopdev;
660         
661         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0, NULL);
662         if (ret) {
663                 fprintf(stderr, "%s: Unable to mount %s: %s\n", 
664                         progname, dev, strerror(errno));
665                 ret = errno;
666                 if (errno == ENODEV) {
667                         fprintf(stderr, "Is the %s module available?\n", 
668                                 MT_STR(&mop->mo_ldd));
669                 }
670                 goto out_rmdir;
671         }
672
673         /* Set up initial directories */
674         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
675         ret = mkdir(filepnm, 0777);
676         if ((ret != 0) && (errno != EEXIST)) {
677                 fprintf(stderr, "%s: Can't make configs dir %s: %s\n", 
678                         progname, filepnm, strerror(errno));
679                 goto out_umnt;
680         } else if (errno == EEXIST) {
681                 ret = 0;
682         }
683
684         /* Save the persistent mount data into a file. Lustre must pre-read
685            this file to get the real mount options. */
686         vprint("Writing %s\n", MOUNT_DATA_FILE);
687         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
688         filep = fopen(filepnm, "w");
689         if (!filep) {
690                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
691                         progname, filepnm, strerror(errno));
692                 goto out_umnt;
693         }
694         fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
695         fclose(filep);
696         
697         /* COMPAT_146 */
698 #ifdef TUNEFS
699         /* Check for upgrade */
700         if ((mop->mo_ldd.ldd_flags & (LDD_F_UPGRADE14 | LDD_F_SV_TYPE_MGS)) 
701             == (LDD_F_UPGRADE14 | LDD_F_SV_TYPE_MGS)) {
702                 char cmd[128];
703                 char *term;
704                 int cmdsz = sizeof(cmd);
705                 vprint("Copying old logs\n");
706                 
707                 /* Copy the old client log to fsname-client */
708                 sprintf(filepnm, "%s/%s/%s-client", 
709                         mntpt, MOUNT_CONFIGS_DIR, mop->mo_ldd.ldd_fsname);
710                 snprintf(cmd, cmdsz, "cp %s/%s/client %s", mntpt, MDT_LOGS_DIR,
711                          filepnm);
712                 ret = run_command(cmd, cmdsz);
713                 if (ret) {
714                         fprintf(stderr, "%s: Can't copy 1.4 config %s/client "
715                                 "(%d)\n", progname, MDT_LOGS_DIR, ret);
716                         fprintf(stderr, "mount -t ldiskfs %s somewhere, "
717                                 "find the client log for fs %s and "
718                                 "copy it manually into %s/%s-client, "
719                                 "then umount.\n",
720                                 mop->mo_device, 
721                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
722                                 mop->mo_ldd.ldd_fsname);
723                         goto out_umnt;
724                 }
725
726                 /* We need to use the old mdt log because otherwise mdt won't
727                    have complete lov if old clients connect before all 
728                    servers upgrade. */
729                 /* Copy the old mdt log to fsname-MDT0000 (get old
730                    name from mdt_UUID) */
731                 ret = 1;
732                 strscpy(filepnm, mop->mo_ldd.ldd_uuid, sizeof(filepnm));
733                 term = strstr(filepnm, "_UUID");
734                 if (term) {
735                         *term = '\0';
736                         snprintf(cmd, cmdsz, "cp %s/%s/%s %s/%s/%s",
737                                  mntpt, MDT_LOGS_DIR, filepnm, 
738                                  mntpt, MOUNT_CONFIGS_DIR,
739                                  mop->mo_ldd.ldd_svname);
740                         ret = run_command(cmd, cmdsz);
741                 }
742                 if (ret) {
743                         fprintf(stderr, "%s: Can't copy 1.4 config %s/%s "
744                                 "(%d)\n", progname, MDT_LOGS_DIR, filepnm, ret);
745                         fprintf(stderr, "mount -t ext3 %s somewhere, "
746                                 "find the MDT log for fs %s and "
747                                 "copy it manually into %s/%s, "
748                                 "then umount.\n",
749                                 mop->mo_device, 
750                                 mop->mo_ldd.ldd_fsname, MOUNT_CONFIGS_DIR,
751                                 mop->mo_ldd.ldd_svname);
752                         goto out_umnt;
753                 }
754         }
755 #endif
756         /* end COMPAT_146 */
757
758
759 out_umnt:
760         umount(mntpt);    
761 out_rmdir:
762         rmdir(mntpt);
763         return ret;
764 }
765
766 int read_local_files(struct mkfs_opts *mop)
767 {
768         char tmpdir[] = "/tmp/dirXXXXXX";
769         char cmd[PATH_MAX];
770         char filepnm[128];
771         char *dev;
772         FILE *filep;
773         int ret = 0;
774         int cmdsz = sizeof(cmd);
775
776         /* Make a temporary directory to hold Lustre data files. */
777         if (!mkdtemp(tmpdir)) {
778                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
779                         progname, tmpdir, strerror(errno));
780                 return errno;
781         }
782
783         dev = mop->mo_device;
784
785         /* Construct debugfs command line. */
786         snprintf(cmd, cmdsz, "debugfs -c -R 'dump /%s %s/mountdata' %s",
787                  MOUNT_DATA_FILE, tmpdir, dev);
788
789         ret = run_command(cmd, cmdsz);
790         if (ret)
791                 verrprint("%s: Unable to dump %s dir (%d)\n",
792                           progname, MOUNT_CONFIGS_DIR, ret);
793
794         sprintf(filepnm, "%s/mountdata", tmpdir);
795         filep = fopen(filepnm, "r");
796         if (filep) {
797                 vprint("Reading %s\n", MOUNT_DATA_FILE);
798                 fread(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
799         } else {
800                 /* COMPAT_146 */
801                 /* Try to read pre-1.6 config from last_rcvd */
802                 struct lr_server_data lsd;
803                 verrprint("%s: Unable to read %s (%s).\n",
804                           progname, filepnm, strerror(errno));
805
806                 verrprint("Trying last_rcvd\n");
807                 sprintf(filepnm, "%s/%s", tmpdir, LAST_RCVD);
808
809                 /* Construct debugfs command line. */
810                 snprintf(cmd, cmdsz, "debugfs -c -R 'dump /%s %s' %s",
811                          LAST_RCVD, filepnm, dev);
812
813                 ret = run_command(cmd, cmdsz);
814                 if (ret) {
815                         fprintf(stderr, "%s: Unable to dump %s file (%d)\n",
816                                 progname, LAST_RCVD, ret);
817                         goto out_rmdir;
818                 }
819                 
820                 filep = fopen(filepnm, "r");
821                 if (!filep) {
822                         fprintf(stderr, "%s: Unable to open %s: %s\n",
823                                 progname, filepnm, strerror(errno));
824                         ret = errno;
825                         verrprint("Contents of %s:\n", tmpdir);
826                         verbose+=2;
827                         snprintf(cmd, cmdsz, "ls -l %s/", tmpdir);
828                         run_command(cmd, cmdsz);
829                         verrprint("Contents of disk:\n");
830                         snprintf(cmd, cmdsz, "debugfs -c -R 'ls -l /' %s", dev);
831                         run_command(cmd, cmdsz);
832
833                         goto out_rmdir;
834                 }
835                 vprint("Reading %s\n", LAST_RCVD);
836                 ret = fread(&lsd, 1, sizeof(lsd), filep);
837                 if (ret < sizeof(lsd)) {
838                         fprintf(stderr, "%s: Short read (%d of %d)\n",
839                                 progname, ret, (int)sizeof(lsd));
840                         ret = ferror(filep);
841                         if (ret)
842                                 goto out_close;
843                 }
844                 vprint("Feature compat=%x, incompat=%x\n",
845                        lsd.lsd_feature_compat, lsd.lsd_feature_incompat);
846
847                 if ((lsd.lsd_feature_compat & OBD_COMPAT_OST) ||
848                     (lsd.lsd_feature_incompat & OBD_INCOMPAT_OST)) {
849                         mop->mo_ldd.ldd_flags = LDD_F_SV_TYPE_OST;
850                         mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
851                 } else if ((lsd.lsd_feature_compat & OBD_COMPAT_MDT) ||
852                            (lsd.lsd_feature_incompat & OBD_INCOMPAT_MDT)) {
853                         /* We must co-locate so mgs can see old logs.
854                            If user doesn't want this, they can copy the old
855                            logs manually and re-tunefs. */
856                         mop->mo_ldd.ldd_flags = 
857                                 LDD_F_SV_TYPE_MDT | LDD_F_SV_TYPE_MGS;
858                         mop->mo_ldd.ldd_svindex = lsd.lsd_mdt_index;
859                 } else  {
860                         /* If neither is set, we're pre-1.4.6, make a guess. */
861                         /* Construct debugfs command line. */
862                         snprintf(cmd, cmdsz, "debugfs -c -R 'rdump /%s %s' %s",
863                                  MDT_LOGS_DIR, tmpdir, dev);
864                         run_command(cmd, cmdsz);
865
866                         sprintf(filepnm, "%s/%s", tmpdir, MDT_LOGS_DIR);
867                         if (lsd.lsd_ost_index > 0) {
868                                 mop->mo_ldd.ldd_flags = LDD_F_SV_TYPE_OST;
869                                 mop->mo_ldd.ldd_svindex = lsd.lsd_ost_index;
870                         } else {
871                                 /* If there's a LOGS dir, it's an MDT */
872                                 if ((ret = access(filepnm, F_OK)) == 0) {
873                                         mop->mo_ldd.ldd_flags =
874                                         LDD_F_SV_TYPE_MDT | 
875                                         LDD_F_SV_TYPE_MGS;
876                                         /* Old MDT's are always index 0 
877                                            (pre CMD) */
878                                         mop->mo_ldd.ldd_svindex = 0;
879                                 } else {
880                                         /* The index may not be correct */
881                                         mop->mo_ldd.ldd_flags =
882                                         LDD_F_SV_TYPE_OST | LDD_F_NEED_INDEX;
883                                         verrprint("OST with unknown index\n");
884                                 }
885                         }
886                 }
887                 
888                 ret = 0;
889                 memcpy(mop->mo_ldd.ldd_uuid, lsd.lsd_uuid, 
890                        sizeof(mop->mo_ldd.ldd_uuid));
891                 mop->mo_ldd.ldd_flags |= LDD_F_UPGRADE14;
892         }
893         /* end COMPAT_146 */
894 out_close:        
895         fclose(filep);
896
897 out_rmdir:
898         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
899         run_command(cmd, cmdsz);
900         if (ret) 
901                 verrprint("Failed to read old data (%d)\n", ret);
902         return ret;
903 }
904
905
906 void set_defaults(struct mkfs_opts *mop)
907 {
908         mop->mo_ldd.ldd_magic = LDD_MAGIC;
909         mop->mo_ldd.ldd_config_ver = 1;
910         mop->mo_ldd.ldd_flags = LDD_F_NEED_INDEX | LDD_F_UPDATE | LDD_F_VIRGIN;
911         mop->mo_mgs_failnodes = 0;
912         strcpy(mop->mo_ldd.ldd_fsname, "lustre");
913         if (get_os_version() == 24) 
914                 mop->mo_ldd.ldd_mount_type = LDD_MT_EXT3;
915         else 
916                 mop->mo_ldd.ldd_mount_type = LDD_MT_LDISKFS;
917         
918         mop->mo_ldd.ldd_svindex = INDEX_UNASSIGNED;
919         mop->mo_stripe_count = 1;
920 }
921
922 static inline void badopt(const char *opt, char *type)
923 {
924         fprintf(stderr, "%s: '--%s' only valid for %s\n",
925                 progname, opt, type);
926         usage(stderr);
927 }
928
929 static int add_param(char *buf, char *key, char *val)
930 {
931         int end = sizeof(((struct lustre_disk_data *)0)->ldd_params);
932         int start = strlen(buf);
933         int keylen = 0;
934
935         if (key) 
936                 keylen = strlen(key);
937         if (start + 1 + keylen + strlen(val) >= end) {
938                 fprintf(stderr, "%s: params are too long-\n%s %s%s\n",
939                         progname, buf, key ? key : "", val);
940                 return 1;
941         }
942
943         sprintf(buf + start, " %s%s", key ? key : "", val);
944         return 0;
945 }
946
947 /* from mount_lustre */
948 /* Get rid of symbolic hostnames for tcp, since kernel can't do lookups */
949 #define MAXNIDSTR 1024
950 static char *convert_hostnames(char *s1)
951 {
952         char *converted, *s2 = 0, *c;
953         int left = MAXNIDSTR;
954         lnet_nid_t nid;
955         
956         converted = malloc(left);
957         c = converted;
958         while ((left > 0) && ((s2 = strsep(&s1, ",: \0")))) {
959                 nid = libcfs_str2nid(s2);
960                 if (nid == LNET_NID_ANY) {
961                         if (*s2 == '/') 
962                                 /* end of nids */
963                                 break;
964                         fprintf(stderr, "%s: Can't parse NID '%s'\n", 
965                                 progname, s2);
966                         free(converted);
967                         return NULL;
968                 }
969
970                 if (strncmp(libcfs_nid2str(nid), "127.0.0.1", 
971                             strlen("127.0.0.1")) == 0) {
972                         fprintf(stderr, "%s: The NID '%s' resolves to the "
973                                 "loopback address '%s'.  Lustre requires a "
974                                 "non-loopback address.\n", 
975                                 progname, s2, libcfs_nid2str(nid));
976                         free(converted);
977                         return NULL;
978                 }
979
980                 c += snprintf(c, left, "%s,", libcfs_nid2str(nid));
981                 left = converted + MAXNIDSTR - c;
982         }
983         *(c - 1) = '\0';
984         return converted;
985 }
986
987 int parse_opts(int argc, char *const argv[], struct mkfs_opts *mop,
988                char **mountopts)
989 {
990         static struct option long_opt[] = {
991                 {"backfstype", 1, 0, 'b'},
992                 {"stripe-count-hint", 1, 0, 'c'},
993                 {"comment", 1, 0, 'u'},
994                 {"configdev", 1, 0, 'C'},
995                 {"device-size", 1, 0, 'd'},
996                 {"dryrun", 0, 0, 'n'},
997                 {"erase-params", 0, 0, 'e'},
998                 {"failnode", 1, 0, 'f'},
999                 {"failover", 1, 0, 'f'},
1000                 {"mgs", 0, 0, 'G'},
1001                 {"help", 0, 0, 'h'},
1002                 {"index", 1, 0, 'i'},
1003                 {"mkfsoptions", 1, 0, 'k'},
1004                 {"mgsnode", 1, 0, 'm'},
1005                 {"mgsnid", 1, 0, 'm'},
1006                 {"mdt", 0, 0, 'M'},
1007                 {"fsname",1, 0, 'L'},
1008                 {"noformat", 0, 0, 'n'},
1009                 {"nomgs", 0, 0, 'N'},
1010                 {"mountfsoptions", 1, 0, 'o'},
1011                 {"ost", 0, 0, 'O'},
1012                 {"param", 1, 0, 'p'},
1013                 {"print", 0, 0, 'n'},
1014                 {"quiet", 0, 0, 'q'},
1015                 {"reformat", 0, 0, 'r'},
1016                 {"verbose", 0, 0, 'v'},
1017                 {"writeconf", 0, 0, 'w'},
1018                 {0, 0, 0, 0}
1019         };
1020         char *optstring = "b:c:C:d:ef:Ghi:k:L:m:MnNo:Op:Pqru:vw";
1021         int opt;
1022         int rc, longidx;
1023
1024         while ((opt = getopt_long(argc, argv, optstring, long_opt, &longidx)) != 
1025                EOF) {
1026                 switch (opt) {
1027                 case 'b': {
1028                         int i = 0;
1029                         while (i < LDD_MT_LAST) {
1030                                 if (strcmp(optarg, mt_str(i)) == 0) {
1031                                         mop->mo_ldd.ldd_mount_type = i;
1032                                         break;
1033                                 }
1034                                 i++;
1035                         }
1036                         break;
1037                 }
1038                 case 'c':
1039                         if (IS_MDT(&mop->mo_ldd)) {
1040                                 int stripe_count = atol(optarg);
1041                                 if (stripe_count <= 0) {
1042                                         fprintf(stderr, "%s: bad stripe count "
1043                                                 "%d\n", progname, stripe_count);
1044                                         return 1;
1045                                 }
1046                                 mop->mo_stripe_count = stripe_count;
1047                         } else {
1048                                 badopt(long_opt[longidx].name, "MDT");
1049                                 return 1;
1050                         }
1051                         break;
1052                 case 'C': /* Configdev */
1053                         //FIXME
1054                         printf("Configdev not implemented\n");
1055                         return 1;
1056                 case 'd':
1057                         mop->mo_device_sz = atol(optarg); 
1058                         break;
1059                 case 'e':
1060                         mop->mo_ldd.ldd_params[0] = '\0';
1061                         /* Must update the mgs logs */
1062                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1063                         break;
1064                 case 'f': {
1065                         char *nids = convert_hostnames(optarg);
1066                         if (!nids) 
1067                                 return 1;
1068                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_FAILNODE, 
1069                                        nids); 
1070                         /* Combo needs to add MDT failnodes as MGS failnodes
1071                            as well */
1072                         if (!rc && IS_MGS(&mop->mo_ldd)) {
1073                                 rc = add_param(mop->mo_ldd.ldd_params, 
1074                                                PARAM_MGSNODE, nids); 
1075                         }
1076                         free(nids);
1077                         if (rc) 
1078                                 return rc;
1079                         /* Must update the mgs logs */
1080                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1081                         break;
1082                 }
1083                 case 'G':
1084                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_MGS;
1085                         break;
1086                 case 'h':
1087                         usage(stdout);
1088                         return 1;
1089                 case 'i':
1090                         if (!(mop->mo_ldd.ldd_flags & 
1091                               (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1092                                LDD_F_WRITECONF))) {
1093                                 fprintf(stderr, "%s: cannot change the index of"
1094                                         " a registered target\n", progname);
1095                                 return 1;
1096                         }
1097                         if (IS_MDT(&mop->mo_ldd) || IS_OST(&mop->mo_ldd)) {
1098                                 mop->mo_ldd.ldd_svindex = atol(optarg);
1099                                 mop->mo_ldd.ldd_flags &= ~LDD_F_NEED_INDEX;
1100                         } else {
1101                                 badopt(long_opt[longidx].name, "MDT,OST");
1102                                 return 1;
1103                         }
1104                         break;
1105                 case 'k':
1106                         strscpy(mop->mo_mkfsopts, optarg, 
1107                                 sizeof(mop->mo_mkfsopts));
1108                         break;
1109                 case 'L': {
1110                         char *tmp;
1111                         if (!(mop->mo_flags & MO_FORCEFORMAT) &&
1112                             (!(mop->mo_ldd.ldd_flags & 
1113                                (LDD_F_UPGRADE14 | LDD_F_VIRGIN |
1114                                 LDD_F_WRITECONF)))) {
1115                                 fprintf(stderr, "%s: cannot change the name of"
1116                                         " a registered target\n", progname);
1117                                 return 1;
1118                         }
1119                         if ((strlen(optarg) < 1) || (strlen(optarg) > 8)) {
1120                                 fprintf(stderr, "%s: filesystem name must be "
1121                                         "1-8 chars\n", progname);
1122                                 return 1;
1123                         }
1124                         if ((tmp = strpbrk(optarg, "/:"))) {
1125                                 fprintf(stderr, "%s: char '%c' not allowed in "
1126                                         "filesystem name\n", progname, *tmp);
1127                                 return 1;
1128                         }
1129                         strscpy(mop->mo_ldd.ldd_fsname, optarg, 
1130                                 sizeof(mop->mo_ldd.ldd_fsname));
1131                         break;
1132                 }
1133                 case 'm': {
1134                         char *nids = convert_hostnames(optarg);
1135                         if (!nids) 
1136                                 return 1;
1137                         rc = add_param(mop->mo_ldd.ldd_params, PARAM_MGSNODE, 
1138                                        nids); 
1139                         free(nids);
1140                         if (rc) 
1141                                 return rc;
1142                         mop->mo_mgs_failnodes++;
1143                         break;
1144                 }
1145                 case 'M':
1146                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_MDT;
1147                         break;
1148                 case 'n':
1149                         print_only++;
1150                         break;
1151                 case 'N':
1152                         mop->mo_ldd.ldd_flags &= ~LDD_F_SV_TYPE_MGS;
1153                         break;
1154                 case 'o':
1155                         *mountopts = optarg;
1156                         break;
1157                 case 'O':
1158                         mop->mo_ldd.ldd_flags |= LDD_F_SV_TYPE_OST;
1159                         break;
1160                 case 'p':
1161                         rc = add_param(mop->mo_ldd.ldd_params, NULL, optarg);
1162                         if (rc) 
1163                                 return rc;
1164                         /* Must update the mgs logs */
1165                         mop->mo_ldd.ldd_flags |= LDD_F_UPDATE;
1166                         break;
1167                 case 'q':
1168                         verbose--;
1169                         break;
1170                 case 'r':
1171                         mop->mo_flags |= MO_FORCEFORMAT;
1172                         break;
1173                 case 'u':
1174                         strscpy(mop->mo_ldd.ldd_userdata, optarg,
1175                                 sizeof(mop->mo_ldd.ldd_userdata));
1176                         break;
1177                 case 'v':
1178                         verbose++;
1179                         break;
1180                 case 'w':
1181                         mop->mo_ldd.ldd_flags |= LDD_F_WRITECONF;
1182                         break;
1183                 default:
1184                         if (opt != '?') {
1185                                 fatal();
1186                                 fprintf(stderr, "Unknown option '%c'\n", opt);
1187                         }
1188                         return EINVAL;
1189                 }
1190         }//while
1191
1192         /* Last arg is device */
1193         if (optind != argc - 1) {
1194                 fatal();
1195                 fprintf(stderr, "Bad argument: %s\n", argv[optind]);
1196                 return EINVAL;
1197         }
1198
1199         return 0;
1200 }
1201
1202 int main(int argc, char *const argv[])
1203 {
1204         struct mkfs_opts mop;
1205         struct lustre_disk_data *ldd;
1206         char *mountopts = NULL;
1207         char always_mountopts[512] = "";
1208         char default_mountopts[512] = "";
1209         int  ret = 0;
1210
1211         if ((progname = strrchr(argv[0], '/')) != NULL)
1212                 progname++;
1213         else
1214                 progname = argv[0];
1215
1216         if ((argc < 2) || (argv[argc - 1][0] == '-')) {
1217                 usage(stderr);
1218                 return(EINVAL);
1219         }
1220
1221         memset(&mop, 0, sizeof(mop));
1222         set_defaults(&mop);
1223
1224         /* device is last arg */
1225         strscpy(mop.mo_device, argv[argc - 1], sizeof(mop.mo_device));
1226
1227         /* Are we using a loop device? */
1228         ret = is_block(mop.mo_device);
1229         if (ret < 0) 
1230                 goto out;
1231         if (ret == 0) 
1232                 mop.mo_flags |= MO_IS_LOOP;
1233
1234 #ifdef TUNEFS
1235         /* For tunefs, we must read in the old values before parsing any
1236            new ones. */
1237         
1238         /* Check whether the disk has already been formatted by mkfs.lustre */
1239         ret = is_lustre_target(&mop);
1240         if (ret == 0) {
1241                 fatal();
1242                 fprintf(stderr, "Device %s has not been formatted with "
1243                         "mkfs.lustre\n", mop.mo_device);
1244                 ret = ENODEV;
1245                 goto out;
1246         }
1247
1248         ret = read_local_files(&mop);
1249         if (ret) {
1250                 fatal();
1251                 fprintf(stderr, "Failed to read previous Lustre data from %s "
1252                         "(%d)\n", mop.mo_device, ret);
1253                 goto out;
1254         }
1255         if (strstr(mop.mo_ldd.ldd_params, PARAM_MGSNODE))
1256             mop.mo_mgs_failnodes++;
1257
1258         if (verbose > 0) 
1259                 print_ldd("Read previous values", &(mop.mo_ldd));
1260 #endif
1261
1262         ret = parse_opts(argc, argv, &mop, &mountopts);
1263         if (ret) 
1264                 goto out;
1265
1266         ldd = &mop.mo_ldd;
1267         
1268         if (!(IS_MDT(ldd) || IS_OST(ldd) || IS_MGS(ldd))) {
1269                 fatal();
1270                 fprintf(stderr, "must set target type: MDT,OST,MGS\n");
1271                 ret = EINVAL;
1272                 goto out;
1273         }
1274
1275         if (((IS_MDT(ldd) || IS_MGS(ldd))) && IS_OST(ldd)) {
1276                 fatal();
1277                 fprintf(stderr, "OST type is exclusive with MDT,MGS\n");
1278                 ret = EINVAL;
1279                 goto out;
1280         }
1281
1282         if ((mop.mo_ldd.ldd_flags & (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) ==
1283             (LDD_F_NEED_INDEX | LDD_F_UPGRADE14)) {
1284                 fatal();
1285                 fprintf(stderr, "Can't find the target index, "
1286                         "specify with --index\n");
1287                 ret = EINVAL;
1288                 goto out;
1289         }
1290
1291         if (!IS_MGS(ldd) && (mop.mo_mgs_failnodes == 0)) {
1292                 fatal();
1293                 if (IS_MDT(ldd)) 
1294                         fprintf(stderr, "Must specify --mgs or --mgsnode=\n");
1295                 else 
1296                         fprintf(stderr, "Must specify --mgsnode=\n");
1297                 ret = EINVAL;
1298                 goto out;
1299         }
1300
1301         /* These are the permanent mount options (always included) */ 
1302         switch (ldd->ldd_mount_type) {
1303         case LDD_MT_EXT3:
1304         case LDD_MT_LDISKFS:
1305         case LDD_MT_LDISKFS2: {
1306                 sprintf(always_mountopts, "errors=remount-ro");
1307                 if (IS_MDT(ldd) || IS_MGS(ldd))
1308                         strscat(always_mountopts, ",iopen_nopriv,user_xattr",
1309                                 sizeof(always_mountopts));
1310                 if ((get_os_version() == 24) && IS_OST(ldd))
1311                         strscat(always_mountopts, ",asyncdel",
1312                                 sizeof(always_mountopts));
1313                 /* NB: Files created while extents are enabled cannot be read
1314                    if mounted with a kernel that doesn't include the CFS 
1315                    patches! */
1316                 if (IS_OST(ldd) && 
1317                     (ldd->ldd_mount_type == LDD_MT_LDISKFS ||
1318                      ldd->ldd_mount_type == LDD_MT_LDISKFS2)) {
1319                         strscat(default_mountopts, ",extents,mballoc",
1320                                 sizeof(default_mountopts));
1321                 }
1322                 break;
1323         }
1324         case LDD_MT_SMFS: {
1325                 mop.mo_flags |= MO_IS_LOOP;
1326                 sprintf(always_mountopts, "type=ext3,dev=%s",
1327                         mop.mo_device);
1328                 break;
1329         }
1330         default: {
1331                 fatal();
1332                 fprintf(stderr, "unknown fs type %d '%s'\n",
1333                         ldd->ldd_mount_type,
1334                         MT_STR(ldd));
1335                 ret = EINVAL;
1336                 goto out;
1337         }
1338         }               
1339
1340         if (mountopts) {
1341                 /* If user specifies mount opts, don't use defaults,
1342                    but always use always_mountopts */
1343                 sprintf(ldd->ldd_mount_opts, "%s,%s", 
1344                         always_mountopts, mountopts);
1345         } else {
1346 #ifdef TUNEFS
1347                 if (ldd->ldd_mount_opts[0] == 0) 
1348                         /* use the defaults unless old opts exist */
1349 #endif
1350                 {
1351                         sprintf(ldd->ldd_mount_opts, "%s%s", 
1352                                 always_mountopts, default_mountopts);
1353                 }
1354         }
1355
1356         server_make_name(ldd->ldd_flags, ldd->ldd_svindex,
1357                          ldd->ldd_fsname, ldd->ldd_svname);
1358
1359         if (verbose >= 0)
1360                 print_ldd("Permanent disk data", ldd);
1361
1362         if (print_only) {
1363                 printf("exiting before disk write.\n");
1364                 goto out;
1365         }
1366
1367         if (check_mtab_entry(mop.mo_device))
1368                 return(EEXIST);
1369
1370         /* Create the loopback file */
1371         if (mop.mo_flags & MO_IS_LOOP) {
1372                 ret = access(mop.mo_device, F_OK);
1373                 if (ret) 
1374                         ret = errno;
1375 #ifndef TUNEFS /* mkfs.lustre */
1376                 /* Reformat the loopback file */
1377                 if (ret || (mop.mo_flags & MO_FORCEFORMAT))
1378                         ret = loop_format(&mop);
1379 #endif
1380                 if (ret == 0)  
1381                         ret = loop_setup(&mop);
1382                 if (ret) {
1383                         fatal();
1384                         fprintf(stderr, "Loop device setup for %s failed: %s\n",
1385                                 mop.mo_device, strerror(ret));
1386                         goto out;
1387                 }
1388         }
1389
1390 #ifndef TUNEFS /* mkfs.lustre */
1391         /* Check whether the disk has already been formatted by mkfs.lustre */
1392         if (!(mop.mo_flags & MO_FORCEFORMAT)) {
1393                 ret = is_lustre_target(&mop);
1394                 if (ret) {
1395                         fatal();
1396                         fprintf(stderr, "Device %s was previously formatted " 
1397                                 "for lustre. Use --reformat to reformat it, "
1398                                 "or tunefs.lustre to modify.\n",
1399                                 mop.mo_device);
1400                         goto out;
1401                 }
1402         }
1403
1404         /* Format the backing filesystem */
1405         ret = make_lustre_backfs(&mop);
1406         if (ret != 0) {
1407                 fatal();
1408                 fprintf(stderr, "mkfs failed %d\n", ret);
1409                 goto out;
1410         }
1411 #endif
1412
1413         /* Write our config files */
1414         ret = write_local_files(&mop);
1415         if (ret != 0) {
1416                 fatal();
1417                 fprintf(stderr, "failed to write local files\n");
1418                 goto out;
1419         }
1420
1421 out:
1422         loop_cleanup(&mop);    
1423
1424         /* Fix any crazy return values from system() */      
1425         if (ret && ((ret & 255) == 0))
1426                 return (1);
1427         if (ret)
1428                 verrprint("%s: exiting with %d (%s)\n",
1429                           progname, ret, strerror(ret));
1430         return (ret);
1431 }