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