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