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