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