Whamcloud - gitweb
LU-1303 lod: introduce lod device
[fs/lustre-release.git] / lustre / utils / mount_utils_ldiskfs.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, Whamcloud, Inc.
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/mount_utils_ldiskfs.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 #include <glob.h>
57
58 #include <sys/types.h>
59 #include <sys/stat.h>
60 #include <sys/mount.h>
61 #include <sys/utsname.h>
62
63 #include <string.h>
64 #include <getopt.h>
65 #include <limits.h>
66 #include <ctype.h>
67
68 #ifdef __linux__
69 /* libcfs.h is not really needed here, but on SLES10/PPC, fs.h includes idr.h
70  * which requires BITS_PER_LONG to be defined */
71 #include <libcfs/libcfs.h>
72 #ifndef BLKGETSIZE64
73 #include <linux/fs.h> /* for BLKGETSIZE64 */
74 #endif
75 #include <linux/version.h>
76 #endif
77 #include <lustre_disk.h>
78 #include <lustre_param.h>
79 #include <lnet/lnetctl.h>
80 #include <lustre_ver.h>
81 #include "mount_utils.h"
82
83 #define MAX_HW_SECTORS_KB_PATH  "queue/max_hw_sectors_kb"
84 #define MAX_SECTORS_KB_PATH     "queue/max_sectors_kb"
85 #define STRIPE_CACHE_SIZE       "md/stripe_cache_size"
86
87 extern char *progname;
88
89 #define L_BLOCK_SIZE 4096
90 /* keep it less than LL_FID_NAMELEN */
91 #define DUMMY_FILE_NAME_LEN             25
92 #define EXT3_DIRENT_SIZE                DUMMY_FILE_NAME_LEN
93
94 /* Write the server config files */
95 int ldiskfs_write_ldd(struct mkfs_opts *mop)
96 {
97         char mntpt[] = "/tmp/mntXXXXXX";
98         char filepnm[128];
99         char *dev;
100         FILE *filep;
101         int ret = 0;
102         size_t num;
103
104         /* Mount this device temporarily in order to write these files */
105         if (!mkdtemp(mntpt)) {
106                 fprintf(stderr, "%s: Can't create temp mount point %s: %s\n",
107                         progname, mntpt, strerror(errno));
108                 return errno;
109         }
110
111         dev = mop->mo_device;
112         if (mop->mo_flags & MO_IS_LOOP)
113                 dev = mop->mo_loopdev;
114
115         ret = mount(dev, mntpt, MT_STR(&mop->mo_ldd), 0,
116                     mop->mo_ldd.ldd_mount_opts);
117         if (ret) {
118                 fprintf(stderr, "%s: Unable to mount %s: %s\n",
119                         progname, dev, strerror(errno));
120                 ret = errno;
121                 if (errno == ENODEV) {
122                         fprintf(stderr, "Is the %s module available?\n",
123                                 MT_STR(&mop->mo_ldd));
124                 }
125                 goto out_rmdir;
126         }
127
128         /* Set up initial directories */
129         sprintf(filepnm, "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
130         ret = mkdir(filepnm, 0777);
131         if ((ret != 0) && (errno != EEXIST)) {
132                 fprintf(stderr, "%s: Can't make configs dir %s (%s)\n",
133                         progname, filepnm, strerror(errno));
134                 goto out_umnt;
135         } else if (errno == EEXIST) {
136                 ret = 0;
137         }
138
139         /* Save the persistent mount data into a file. Lustre must pre-read
140            this file to get the real mount options. */
141         vprint("Writing %s\n", MOUNT_DATA_FILE);
142         sprintf(filepnm, "%s/%s", mntpt, MOUNT_DATA_FILE);
143         filep = fopen(filepnm, "w");
144         if (!filep) {
145                 fprintf(stderr, "%s: Unable to create %s file: %s\n",
146                         progname, filepnm, strerror(errno));
147                 goto out_umnt;
148         }
149         num = fwrite(&mop->mo_ldd, sizeof(mop->mo_ldd), 1, filep);
150         if (num < 1 && ferror(filep)) {
151                 fprintf(stderr, "%s: Unable to write to file (%s): %s\n",
152                         progname, filepnm, strerror(errno));
153                 fclose(filep);
154                 goto out_umnt;
155         }
156         fclose(filep);
157
158 out_umnt:
159         umount(mntpt);
160 out_rmdir:
161         rmdir(mntpt);
162         return ret;
163 }
164
165 static int readcmd(char *cmd, char *buf, int len)
166 {
167         FILE *fp;
168         int red;
169
170         fp = popen(cmd, "r");
171         if (!fp)
172                 return errno;
173
174         red = fread(buf, 1, len, fp);
175         pclose(fp);
176
177         /* strip trailing newline */
178         if (buf[red - 1] == '\n')
179                 buf[red - 1] = '\0';
180
181         return (red == 0) ? -ENOENT : 0;
182 }
183
184 int ldiskfs_read_ldd(char *dev, struct lustre_disk_data *mo_ldd)
185 {
186         char tmpdir[] = "/tmp/dirXXXXXX";
187         char cmd[PATH_MAX];
188         char filepnm[128];
189         FILE *filep;
190         int ret = 0;
191         int cmdsz = sizeof(cmd);
192
193         /* Make a temporary directory to hold Lustre data files. */
194         if (!mkdtemp(tmpdir)) {
195                 fprintf(stderr, "%s: Can't create temporary directory %s: %s\n",
196                         progname, tmpdir, strerror(errno));
197                 return errno;
198         }
199
200         /* TODO: it's worth observing the get_mountdata() function that is
201            in mount_utils.c for getting the mountdata out of the
202            filesystem */
203
204         /* Construct debugfs command line. */
205         snprintf(cmd, cmdsz, "%s -c -R 'dump /%s %s/mountdata' '%s'",
206                  DEBUGFS, MOUNT_DATA_FILE, tmpdir, dev);
207
208         ret = run_command(cmd, cmdsz);
209         if (ret)
210                 verrprint("%s: Unable to dump %s dir (%d)\n",
211                           progname, MOUNT_CONFIGS_DIR, ret);
212
213         sprintf(filepnm, "%s/mountdata", tmpdir);
214         filep = fopen(filepnm, "r");
215         if (filep) {
216                 size_t num_read;
217                 vprint("Reading %s\n", MOUNT_DATA_FILE);
218                 num_read = fread(mo_ldd, sizeof(*mo_ldd), 1, filep);
219                 if (num_read < 1 && ferror(filep)) {
220                         fprintf(stderr, "%s: Unable to read from file %s: %s\n",
221                                 progname, filepnm, strerror(errno));
222                         goto out_close;
223                 }
224         }
225 out_close:
226         fclose(filep);
227
228         snprintf(cmd, cmdsz, "rm -rf %s", tmpdir);
229         run_command(cmd, cmdsz);
230         if (ret)
231                 verrprint("Failed to read old data (%d)\n", ret);
232
233         /* As long as we at least have the label, we're good to go */
234         snprintf(cmd, sizeof(cmd), E2LABEL" %s", dev);
235         ret = readcmd(cmd, mo_ldd->ldd_svname, sizeof(mo_ldd->ldd_svname) - 1);
236
237         return ret;
238 }
239
240
241 /* Display the need for the latest e2fsprogs to be installed. make_backfs
242  * indicates if the caller is make_lustre_backfs() or not. */
243 void disp_old_e2fsprogs_msg(const char *feature, int make_backfs)
244 {
245         static int msg_displayed;
246
247         if (msg_displayed) {
248                 fprintf(stderr, "WARNING: %s does not support %s "
249                         "feature.\n\n", E2FSPROGS, feature);
250                 return;
251         }
252
253         msg_displayed++;
254
255         fprintf(stderr, "WARNING: The %s package currently installed on "
256                 "your system does not support \"%s\" feature.\n",
257                 E2FSPROGS, feature);
258 #if !(HAVE_LDISKFSPROGS)
259         fprintf(stderr, "Please install the latest version of e2fsprogs from\n"
260                 "http://downloads.whamcloud.com/public/e2fsprogs/latest/\n"
261                 "to enable this feature.\n");
262 #endif
263         if (make_backfs)
264                 fprintf(stderr, "Feature will not be enabled until %s"
265                         "is updated and '%s -O %s %%{device}' "
266                         "is run.\n\n", E2FSPROGS, TUNE2FS, feature);
267 }
268
269 /* Check whether the file exists in the device */
270 static int file_in_dev(char *file_name, char *dev_name)
271 {
272         FILE *fp;
273         char debugfs_cmd[256];
274         unsigned int inode_num;
275         int i;
276
277         /* Construct debugfs command line. */
278         snprintf(debugfs_cmd, sizeof(debugfs_cmd),
279                  "%s -c -R 'stat %s' '%s' 2>&1 | egrep '(Inode|unsupported)'",
280                  DEBUGFS, file_name, dev_name);
281
282         fp = popen(debugfs_cmd, "r");
283         if (!fp) {
284                 fprintf(stderr, "%s: %s\n", progname, strerror(errno));
285                 return 0;
286         }
287
288         if (fscanf(fp, "Inode: %u", &inode_num) == 1) { /* exist */
289                 pclose(fp);
290                 return 1;
291         }
292         i = fread(debugfs_cmd, 1, sizeof(debugfs_cmd), fp);
293         if (i) {
294                 debugfs_cmd[i] = 0;
295                 fprintf(stderr, "%s", debugfs_cmd);
296                 if (strstr(debugfs_cmd, "unsupported feature")) {
297                         disp_old_e2fsprogs_msg("an unknown", 0);
298                 }
299                 pclose(fp);
300                 return -1;
301         }
302         pclose(fp);
303         return 0;
304 }
305
306 /* Check whether the device has already been used with lustre */
307 int ldiskfs_is_lustre(char *dev, unsigned *mount_type)
308 {
309         int ret;
310
311         ret = file_in_dev(MOUNT_DATA_FILE, dev);
312         if (ret) {
313                 /* in the -1 case, 'extents' means IS a lustre target */
314                 *mount_type = LDD_MT_LDISKFS;
315                 return 1;
316         }
317
318         ret = file_in_dev(LAST_RCVD, dev);
319         if (ret) {
320                 *mount_type = LDD_MT_LDISKFS;
321                 return 1;
322         }
323
324         return 0;
325 }
326
327 /* Check if a certain feature is supported by e2fsprogs.
328  * Firstly we try to use "debugfs supported_features" command to check if
329  * the feature is supported. If this fails we try to set this feature with
330  * mke2fs to check for its support. */
331 static int is_e2fsprogs_feature_supp(const char *feature)
332 {
333         static char supp_features[4096] = "";
334         FILE *fp;
335         char cmd[PATH_MAX];
336         char imgname[] = "/tmp/test-img-XXXXXX";
337         int fd = -1;
338         int ret = 1;
339
340         if (supp_features[0] == '\0') {
341                 snprintf(cmd, sizeof(cmd), "%s -c -R supported_features 2>&1",
342                          DEBUGFS);
343
344                 /* Using popen() instead of run_command() since debugfs does
345                  * not return proper error code if command is not supported */
346                 fp = popen(cmd, "r");
347                 if (!fp) {
348                         fprintf(stderr, "%s: %s\n", progname, strerror(errno));
349                         return 0;
350                 }
351                 ret = fread(supp_features, 1, sizeof(supp_features), fp);
352                 fclose(fp);
353         }
354         if (ret > 0 && strstr(supp_features,
355                               strncmp(feature, "-O ", 3) ? feature : feature+3))
356                 return 0;
357
358         if ((fd = mkstemp(imgname)) < 0)
359                 return -1;
360         else
361                 close(fd);
362
363         snprintf(cmd, sizeof(cmd), "%s -F %s %s 100 >/dev/null 2>&1",
364                  MKE2FS, feature, imgname);
365         /* run_command() displays the output of mke2fs when it fails for
366          * some feature, so use system() directly */
367         ret = system(cmd);
368         unlink(imgname);
369
370         return ret;
371 }
372
373
374 /**
375  * append_unique: append @key or @key=@val pair to @buf only if @key does not
376  *                exists
377  *      @buf: buffer to hold @key or @key=@val
378  *      @prefix: prefix string before @key
379  *      @key: key string
380  *      @val: value string if it's a @key=@val pair
381  */
382 static void append_unique(char *buf, char *prefix, char *key, char *val,
383                           size_t maxbuflen)
384 {
385         char *anchor, *end;
386         int  len;
387
388         if (key == NULL)
389                 return;
390
391         anchor = end = strstr(buf, key);
392         /* try to find exact match string in @buf */
393         while (end && *end != '\0' && *end != ',' && *end != ' ' && *end != '=')
394                 ++end;
395         len = end - anchor;
396         if (anchor == NULL || strlen(key) != len ||
397                         strncmp(anchor, key, len) != 0) {
398                 if (prefix != NULL)
399                         strscat(buf, prefix, maxbuflen);
400
401                 strscat(buf, key, maxbuflen);
402                 if (val != NULL) {
403                         strscat(buf, "=", maxbuflen);
404                         strscat(buf, val, maxbuflen);
405                 }
406         }
407 }
408
409 static void enable_default_ext4_features(struct mkfs_opts *mop, char *anchor,
410                                          size_t maxbuflen, int user_spec)
411 {
412         if (IS_OST(&mop->mo_ldd)) {
413                 append_unique(anchor, user_spec ? "," : " -O ",
414                               "extents", NULL, sizeof(mop->mo_mkfsopts));
415                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
416         } else if (IS_MDT(&mop->mo_ldd)) {
417                 append_unique(anchor, user_spec ? "," : " -O ",
418                               "dirdata", NULL, maxbuflen);
419                 append_unique(anchor, ",", "uninit_bg", NULL, maxbuflen);
420                 append_unique(anchor, ",", "^extents", NULL, maxbuflen);
421         } else {
422                 append_unique(anchor, user_spec ? "," : " -O ",
423                               "uninit_bg", NULL, maxbuflen);
424         }
425
426         /* Multiple mount protection enabled only if failover node specified */
427         if (mop->mo_flags & MO_FAILOVER) {
428                 if (is_e2fsprogs_feature_supp("-O mmp") == 0)
429                         append_unique(anchor, ",", "mmp", NULL, maxbuflen);
430                 else
431                         disp_old_e2fsprogs_msg("mmp", 1);
432         }
433
434         /* Allow more than 65000 subdirectories */
435         if (is_e2fsprogs_feature_supp("-O dir_nlink") == 0)
436                 append_unique(anchor, ",", "dir_nlink", NULL, maxbuflen);
437
438         /* The following options are only valid for ext4-based ldiskfs.
439          * If --backfstype=ext3 is specified, do not enable them. */
440         if (mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3)
441                 return;
442
443         /* Allow files larger than 2TB.  Also needs LU-16, but not harmful. */
444         if (is_e2fsprogs_feature_supp("-O huge_file") == 0)
445                 append_unique(anchor, ",", "huge_file", NULL, maxbuflen);
446
447         /* Enable large block addresses if the LUN is over 2^32 blocks. */
448         if (mop->mo_device_sz / (L_BLOCK_SIZE >> 10) >= 0x100002000ULL &&
449             is_e2fsprogs_feature_supp("-O 64bit") == 0)
450                 append_unique(anchor, ",", "64bit", NULL, maxbuflen);
451
452         /* Cluster inode/block bitmaps and inode table for more efficient IO.
453          * Align the flex groups on a 1MB boundary for better performance. */
454         /* This -O feature needs to go last, since it adds the "-G" option. */
455         if (is_e2fsprogs_feature_supp("-O flex_bg") == 0) {
456                 char tmp_buf[64];
457
458                 append_unique(anchor, ",", "flex_bg", NULL, maxbuflen);
459
460                 if (IS_OST(&mop->mo_ldd)) {
461                         snprintf(tmp_buf, sizeof(tmp_buf), " -G %u",
462                                  (1 << 20) / L_BLOCK_SIZE);
463                         strscat(anchor, tmp_buf, maxbuflen);
464                 }
465         }
466         /* Don't add any more "-O" options here, see last comment above */
467 }
468
469 /**
470  * moveopts_to_end: find the option string, move remaining strings to
471  *                  where option string starts, and append the option
472  *                  string at the end
473  *      @start: where the option string starts before the move
474  *      RETURN: where the option string starts after the move
475  */
476 static char *moveopts_to_end(char *start)
477 {
478         char save[512];
479         char *end, *idx;
480
481         /* skip whitespace before options */
482         end = start + 2;
483         while (*end == ' ')
484                 ++end;
485
486         /* find end of option characters */
487         while (*end != ' ' && *end != '\0')
488                 ++end;
489
490         /* save options */
491         strncpy(save, start, end - start);
492         save[end - start] = '\0';
493
494         /* move remaining options up front */
495         if (*end)
496                 memmove(start, end, strlen(end));
497         *(start + strlen(end)) = '\0';
498
499         /* append the specified options */
500         if (*(start + strlen(start) - 1) != ' ')
501                 strcat(start, " ");
502         idx = start + strlen(start);
503         strcat(start, save);
504
505         return idx;
506 }
507
508 /* Build fs according to type */
509 int ldiskfs_make_lustre(struct mkfs_opts *mop)
510 {
511         __u64 device_sz = mop->mo_device_sz, block_count = 0;
512         char mkfs_cmd[PATH_MAX];
513         char buf[64];
514         char *start;
515         char *dev;
516         int ret = 0, ext_opts = 0;
517         size_t maxbuflen;
518
519         if (!(mop->mo_flags & MO_IS_LOOP)) {
520                 mop->mo_device_sz = get_device_size(mop->mo_device);
521
522                 if (mop->mo_device_sz == 0)
523                         return ENODEV;
524
525                 /* Compare to real size */
526                 if (device_sz == 0 || device_sz > mop->mo_device_sz)
527                         device_sz = mop->mo_device_sz;
528                 else
529                         mop->mo_device_sz = device_sz;
530         }
531
532         if (mop->mo_device_sz != 0) {
533                 if (mop->mo_device_sz < 8096){
534                         fprintf(stderr, "%s: size of filesystem must be larger "
535                                 "than 8MB, but is set to %lldKB\n",
536                                 progname, (long long)mop->mo_device_sz);
537                         return EINVAL;
538                 }
539                 block_count = mop->mo_device_sz / (L_BLOCK_SIZE >> 10);
540                 /* If the LUN size is just over 2^32 blocks, limit the
541                  * filesystem size to 2^32-1 blocks to avoid problems with
542                  * ldiskfs/mkfs not handling this size.  Bug 22906 */
543                 if (block_count > 0xffffffffULL && block_count < 0x100002000ULL)
544                         block_count = 0xffffffffULL;
545         }
546
547         if ((mop->mo_ldd.ldd_mount_type == LDD_MT_EXT3) ||
548             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS) ||
549             (mop->mo_ldd.ldd_mount_type == LDD_MT_LDISKFS2)) {
550                 long inode_size = 0;
551
552                 /* Journal size in MB */
553                 if (strstr(mop->mo_mkfsopts, "-J") == NULL) {
554                         /* Choose our own default journal size */
555                         long journal_sz = 0, max_sz;
556                         if (device_sz > 1024 * 1024) /* 1GB */
557                                 journal_sz = (device_sz / 102400) * 4;
558                         /* cap journal size at 1GB */
559                         if (journal_sz > 1024L)
560                                 journal_sz = 1024L;
561                         /* man mkfs.ext3 */
562                         max_sz = (102400 * L_BLOCK_SIZE) >> 20; /* 400MB */
563                         if (journal_sz > max_sz)
564                                 journal_sz = max_sz;
565                         if (journal_sz) {
566                                 sprintf(buf, " -J size=%ld", journal_sz);
567                                 strscat(mop->mo_mkfsopts, buf,
568                                         sizeof(mop->mo_mkfsopts));
569                         }
570                 }
571
572                 /* Inode size (for extended attributes).  The LOV EA size is
573                  * 32 (EA hdr) + 32 (lov_mds_md) + stripes * 24 (lov_ost_data),
574                  * and we want some margin above that for ACLs, other EAs... */
575                 if (strstr(mop->mo_mkfsopts, "-I") == NULL) {
576                         if (IS_MDT(&mop->mo_ldd)) {
577                                 if (mop->mo_stripe_count > 72)
578                                         inode_size = 512; /* bz 7241 */
579                                 /* see also "-i" below for EA blocks */
580                                 else if (mop->mo_stripe_count > 32)
581                                         inode_size = 2048;
582                                 else if (mop->mo_stripe_count > 10)
583                                         inode_size = 1024;
584                                 else
585                                         inode_size = 512;
586                         } else if (IS_OST(&mop->mo_ldd)) {
587                                 /* We store MDS FID and OST objid in EA on OST
588                                  * we need to make inode bigger as well. */
589                                 inode_size = 256;
590                         }
591
592                         if (inode_size > 0) {
593                                 sprintf(buf, " -I %ld", inode_size);
594                                 strscat(mop->mo_mkfsopts, buf,
595                                         sizeof(mop->mo_mkfsopts));
596                         }
597                 }
598
599                 /* Bytes_per_inode: disk size / num inodes */
600                 if (strstr(mop->mo_mkfsopts, "-i") == NULL &&
601                     strstr(mop->mo_mkfsopts, "-N") == NULL) {
602                         long bytes_per_inode = 0;
603
604                         /* Allocate more inodes on MDT devices.  There is
605                          * no data stored on the MDT, and very little extra
606                          * metadata beyond the inode.  It could go down as
607                          * low as 1024 bytes, but this is conservative.
608                          * Account for external EA blocks for wide striping. */
609                         if (IS_MDT(&mop->mo_ldd)) {
610                                 bytes_per_inode = inode_size + 1536;
611
612                                 if (mop->mo_stripe_count > 72) {
613                                         int extra = mop->mo_stripe_count * 24;
614                                         extra = ((extra - 1) | 4095) + 1;
615                                         bytes_per_inode += extra;
616                                 }
617                         }
618
619                         /* Allocate fewer inodes on large OST devices.  Most
620                          * filesystems can be much more aggressive than even
621                          * this, but it is impossible to know in advance. */
622                         if (IS_OST(&mop->mo_ldd)) {
623                                 /* OST > 16TB assume average file size 1MB */
624                                 if (device_sz > (16ULL << 30))
625                                         bytes_per_inode = 1024 * 1024;
626                                 /* OST > 4TB assume average file size 512kB */
627                                 else if (device_sz > (4ULL << 30))
628                                         bytes_per_inode = 512 * 1024;
629                                 /* OST > 1TB assume average file size 256kB */
630                                 else if (device_sz > (1ULL << 30))
631                                         bytes_per_inode = 256 * 1024;
632                                 /* OST > 10GB assume average file size 64kB,
633                                  * plus a bit so that inodes will fit into a
634                                  * 256x flex_bg without overflowing */
635                                 else if (device_sz > (10ULL << 20))
636                                         bytes_per_inode = 69905;
637                         }
638
639                         if (bytes_per_inode > 0) {
640                                 sprintf(buf, " -i %ld", bytes_per_inode);
641                                 strscat(mop->mo_mkfsopts, buf,
642                                         sizeof(mop->mo_mkfsopts));
643                         }
644                 }
645
646                 if (verbose < 2) {
647                         strscat(mop->mo_mkfsopts, " -q",
648                                 sizeof(mop->mo_mkfsopts));
649                 }
650
651                 /* start handle -O mkfs options */
652                 if ((start = strstr(mop->mo_mkfsopts, "-O")) != NULL) {
653                         if (strstr(start + 2, "-O") != NULL) {
654                                 fprintf(stderr,
655                                         "%s: don't specify multiple -O options\n",
656                                         progname);
657                                 return EINVAL;
658                         }
659                         start = moveopts_to_end(start);
660                         maxbuflen = sizeof(mop->mo_mkfsopts) -
661                                 (start - mop->mo_mkfsopts) - strlen(start);
662                         enable_default_ext4_features(mop, start, maxbuflen, 1);
663                 } else {
664                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts),
665                               maxbuflen = sizeof(mop->mo_mkfsopts) -
666                                       strlen(mop->mo_mkfsopts);
667                         enable_default_ext4_features(mop, start, maxbuflen, 0);
668                 }
669                 /* end handle -O mkfs options */
670
671                 /* start handle -E mkfs options */
672                 if ((start = strstr(mop->mo_mkfsopts, "-E")) != NULL) {
673                         if (strstr(start + 2, "-E") != NULL) {
674                                 fprintf(stderr,
675                                         "%s: don't specify multiple -E options\n",
676                                         progname);
677                                 return EINVAL;
678                         }
679                         start = moveopts_to_end(start);
680                         maxbuflen = sizeof(mop->mo_mkfsopts) -
681                                 (start - mop->mo_mkfsopts) - strlen(start);
682                         ext_opts = 1;
683                 } else {
684                         start = mop->mo_mkfsopts + strlen(mop->mo_mkfsopts);
685                         maxbuflen = sizeof(mop->mo_mkfsopts) -
686                                 strlen(mop->mo_mkfsopts);
687                 }
688
689                 /* In order to align the filesystem metadata on 1MB boundaries,
690                  * give a resize value that will reserve a power-of-two group
691                  * descriptor blocks, but leave one block for the superblock.
692                  * Only useful for filesystems with < 2^32 blocks due to resize
693                  * limitations. */
694                 if (IS_OST(&mop->mo_ldd) && mop->mo_device_sz > 100 * 1024 &&
695                     mop->mo_device_sz * 1024 / L_BLOCK_SIZE <= 0xffffffffULL) {
696                         unsigned group_blocks = L_BLOCK_SIZE * 8;
697                         unsigned desc_per_block = L_BLOCK_SIZE / 32;
698                         unsigned resize_blks;
699
700                         resize_blks = (1ULL<<32) - desc_per_block*group_blocks;
701                         snprintf(buf, sizeof(buf), "%u", resize_blks);
702                         append_unique(start, ext_opts ? "," : " -E ",
703                                       "resize", buf, maxbuflen);
704                         ext_opts = 1;
705                 }
706
707                 /* Avoid zeroing out the full journal - speeds up mkfs */
708                 if (is_e2fsprogs_feature_supp("-E lazy_journal_init") == 0)
709                         append_unique(start, ext_opts ? "," : " -E ",
710                                       "lazy_journal_init", NULL, maxbuflen);
711                 /* end handle -E mkfs options */
712
713                 /* Allow reformat of full devices (as opposed to
714                    partitions.)  We already checked for mounted dev. */
715                 strscat(mop->mo_mkfsopts, " -F", sizeof(mop->mo_mkfsopts));
716
717                 snprintf(mkfs_cmd, sizeof(mkfs_cmd),
718                          "%s -j -b %d -L %s ", MKE2FS, L_BLOCK_SIZE,
719                          mop->mo_ldd.ldd_svname);
720         } else {
721                 fprintf(stderr,"%s: unsupported fs type: %d (%s)\n",
722                         progname, mop->mo_ldd.ldd_mount_type,
723                         MT_STR(&mop->mo_ldd));
724                 return EINVAL;
725         }
726
727         /* For loop device format the dev, not the filename */
728         dev = mop->mo_device;
729         if (mop->mo_flags & MO_IS_LOOP)
730                 dev = mop->mo_loopdev;
731
732         vprint("formatting backing filesystem %s on %s\n",
733                MT_STR(&mop->mo_ldd), dev);
734         vprint("\ttarget name  %s\n", mop->mo_ldd.ldd_svname);
735         vprint("\t4k blocks     "LPU64"\n", block_count);
736         vprint("\toptions       %s\n", mop->mo_mkfsopts);
737
738         /* mkfs_cmd's trailing space is important! */
739         strscat(mkfs_cmd, mop->mo_mkfsopts, sizeof(mkfs_cmd));
740         strscat(mkfs_cmd, " ", sizeof(mkfs_cmd));
741         strscat(mkfs_cmd, dev, sizeof(mkfs_cmd));
742         if (block_count != 0) {
743                 sprintf(buf, " "LPU64, block_count);
744                 strscat(mkfs_cmd, buf, sizeof(mkfs_cmd));
745         }
746
747         vprint("mkfs_cmd = %s\n", mkfs_cmd);
748         ret = run_command(mkfs_cmd, sizeof(mkfs_cmd));
749         if (ret) {
750                 fatal();
751                 fprintf(stderr, "Unable to build fs %s (%d)\n", dev, ret);
752         }
753         return ret;
754 }
755
756 int ldiskfs_prepare_lustre(struct mkfs_opts *mop,
757                            char *default_mountopts, int default_len,
758                            char *always_mountopts, int always_len)
759 {
760         struct lustre_disk_data *ldd = &mop->mo_ldd;
761         int ret;
762
763         /* Set MO_IS_LOOP to indicate a loopback device is needed */
764         ret = is_block(mop->mo_device);
765         if (ret < 0) {
766                 return errno;
767         } else if (ret == 0) {
768                 mop->mo_flags |= MO_IS_LOOP;
769         }
770
771         strscat(default_mountopts, ",errors=remount-ro", default_len);
772         if (IS_MDT(ldd) || IS_MGS(ldd))
773                 strscat(always_mountopts, ",user_xattr", always_len);
774
775         return 0;
776 }
777
778 int read_file(char *path, char *buf, int size)
779 {
780         FILE *fd;
781
782         fd = fopen(path, "r");
783         if (fd == NULL)
784                 return errno;
785
786         /* should not ignore fgets(3)'s return value */
787         if (!fgets(buf, size, fd)) {
788                 fprintf(stderr, "reading from %s: %s", path, strerror(errno));
789                 fclose(fd);
790                 return 1;
791         }
792         fclose(fd);
793         return 0;
794 }
795
796 int write_file(char *path, char *buf)
797 {
798         FILE *fd;
799
800         fd = fopen(path, "w");
801         if (fd == NULL)
802                 return errno;
803
804         fputs(buf, fd);
805         fclose(fd);
806         return 0;
807 }
808
809 /* This is to tune the kernel for good SCSI performance.
810  * For that we set the value of /sys/block/{dev}/queue/max_sectors_kb
811  * to the value of /sys/block/{dev}/queue/max_hw_sectors_kb */
812 int set_blockdev_tunables(char *source, struct mount_opts *mop, int fan_out)
813 {
814         glob_t glob_info = { 0 };
815         struct stat stat_buf;
816         char *chk_major, *chk_minor;
817         char *savept = NULL, *dev;
818         char *ret_path;
819         char buf[PATH_MAX] = {'\0'}, path[PATH_MAX] = {'\0'};
820         char real_path[PATH_MAX] = {'\0'};
821         int i, rc = 0;
822         int major, minor;
823
824         if (!source)
825                 return -EINVAL;
826
827         ret_path = realpath(source, real_path);
828         if (ret_path == NULL) {
829                 if (verbose)
830                         fprintf(stderr, "warning: %s: cannot resolve: %s\n",
831                                 source, strerror(errno));
832                 return -EINVAL;
833         }
834
835         if (strncmp(real_path, "/dev/loop", 9) == 0)
836                 return 0;
837
838         if ((real_path[0] != '/') && (strpbrk(real_path, ",:") != NULL))
839                 return 0;
840
841         snprintf(path, sizeof(path), "/sys/block%s", real_path + 4);
842         if (access(path, X_OK) == 0)
843                 goto set_params;
844
845         /* The name of the device say 'X' specified in /dev/X may not
846          * match any entry under /sys/block/. In that case we need to
847          * match the major/minor number to find the entry under
848          * sys/block corresponding to /dev/X */
849
850         /* Don't chop tail digit on /dev/mapper/xxx, LU-478 */
851         if (strncmp(real_path, "/dev/mapper", 11) != 0) {
852                 dev = real_path + strlen(real_path);
853                 while (--dev > real_path && isdigit(*dev))
854                         *dev = 0;
855
856                 if (strncmp(real_path, "/dev/md_", 8) == 0)
857                         *dev = 0;
858         }
859
860         rc = stat(real_path, &stat_buf);
861         if (rc) {
862                 if (verbose)
863                         fprintf(stderr, "warning: %s, device %s stat failed\n",
864                                 strerror(errno), real_path);
865                 return rc;
866         }
867
868         major = major(stat_buf.st_rdev);
869         minor = minor(stat_buf.st_rdev);
870         rc = glob("/sys/block/*", GLOB_NOSORT, NULL, &glob_info);
871         if (rc) {
872                 if (verbose)
873                         fprintf(stderr, "warning: failed to read entries under "
874                                 "/sys/block\n");
875                 globfree(&glob_info);
876                 return rc;
877         }
878
879         for (i = 0; i < glob_info.gl_pathc; i++){
880                 snprintf(path, sizeof(path), "%s/dev", glob_info.gl_pathv[i]);
881
882                 rc = read_file(path, buf, sizeof(buf));
883                 if (rc)
884                         continue;
885
886                 if (buf[strlen(buf) - 1] == '\n')
887                         buf[strlen(buf) - 1] = '\0';
888
889                 chk_major = strtok_r(buf, ":", &savept);
890                 chk_minor = savept;
891                 if (major == atoi(chk_major) &&minor == atoi(chk_minor))
892                         break;
893         }
894
895         if (i == glob_info.gl_pathc) {
896                 if (verbose)
897                         fprintf(stderr,"warning: device %s does not match any "
898                                 "entry under /sys/block\n", real_path);
899                 globfree(&glob_info);
900                 return -EINVAL;
901         }
902
903         /* Chop off "/dev" from path we found */
904         path[strlen(glob_info.gl_pathv[i])] = '\0';
905         globfree(&glob_info);
906
907 set_params:
908         if (strncmp(real_path, "/dev/md", 7) == 0) {
909                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
910                          STRIPE_CACHE_SIZE);
911
912                 rc = read_file(real_path, buf, sizeof(buf));
913                 if (rc) {
914                         if (verbose)
915                                 fprintf(stderr, "warning: opening %s: %s\n",
916                                         real_path, strerror(errno));
917                         return 0;
918                 }
919
920                 if (atoi(buf) >= mop->mo_md_stripe_cache_size)
921                         return 0;
922
923                 if (strlen(buf) - 1 > 0) {
924                         snprintf(buf, sizeof(buf), "%d",
925                                  mop->mo_md_stripe_cache_size);
926                         rc = write_file(real_path, buf);
927                         if (rc && verbose)
928                                 fprintf(stderr, "warning: opening %s: %s\n",
929                                         real_path, strerror(errno));
930                 }
931                 /* Return since raid and disk tunables are different */
932                 return rc;
933         }
934
935         snprintf(real_path, sizeof(real_path), "%s/%s", path,
936                  MAX_HW_SECTORS_KB_PATH);
937         rc = read_file(real_path, buf, sizeof(buf));
938         if (rc) {
939                 if (verbose)
940                         fprintf(stderr, "warning: opening %s: %s\n",
941                                 real_path, strerror(errno));
942                 /* No MAX_HW_SECTORS_KB_PATH isn't necessary an
943                  * error for some device. */
944                 rc = 0;
945         }
946
947         if (strlen(buf) - 1 > 0) {
948                 snprintf(real_path, sizeof(real_path), "%s/%s", path,
949                          MAX_SECTORS_KB_PATH);
950                 rc = write_file(real_path, buf);
951                 if (rc) {
952                         if (verbose)
953                                 fprintf(stderr, "warning: writing to %s: %s\n",
954                                         real_path, strerror(errno));
955                         /* No MAX_SECTORS_KB_PATH isn't necessary an
956                          * error for some device. */
957                         rc = 0;
958                 }
959         }
960
961         if (fan_out) {
962                 char *slave = NULL;
963                 glob_info.gl_pathc = 0;
964                 glob_info.gl_offs = 0;
965                 /* if device is multipath device, tune its slave devices */
966                 snprintf(real_path, sizeof(real_path), "%s/slaves/*", path);
967                 rc = glob(real_path, GLOB_NOSORT, NULL, &glob_info);
968
969                 for (i = 0; rc == 0 && i < glob_info.gl_pathc; i++){
970                         slave = basename(glob_info.gl_pathv[i]);
971                         snprintf(real_path, sizeof(real_path), "/dev/%s", slave);
972                         rc = set_blockdev_tunables(real_path, mop, 0);
973                 }
974
975                 if (rc == GLOB_NOMATCH) {
976                         /* no slave device is not an error */
977                         rc = 0;
978                 } else if (rc && verbose) {
979                         if (slave == NULL) {
980                                 fprintf(stderr, "warning: %s, failed to read"
981                                         " entries under %s/slaves\n",
982                                         strerror(errno), path);
983                         } else {
984                                 fprintf(stderr, "unable to set tunables for"
985                                         " slave device %s (slave would be"
986                                         " unable to handle IO request from"
987                                         " master %s)\n",
988                                         real_path, source);
989                         }
990                 }
991                 globfree(&glob_info);
992         }
993
994         return rc;
995 }
996
997 int ldiskfs_tune_lustre(char *dev, struct mount_opts *mop)
998 {
999         return set_blockdev_tunables(dev, mop, 1);
1000 }
1001
1002 int ldiskfs_label_lustre(struct mount_opts *mop)
1003 {
1004         char label_cmd[PATH_MAX];
1005         int rc;
1006
1007         snprintf(label_cmd, sizeof(label_cmd), E2LABEL" %s %s",
1008                  mop->mo_source, mop->mo_ldd.ldd_svname);
1009         rc = run_command(label_cmd, sizeof(label_cmd));
1010
1011         return rc;
1012 }
1013
1014 /* return canonicalized absolute pathname, even if the target file does not
1015  * exist, unlike realpath */
1016 static char *absolute_path(char *devname)
1017 {
1018         char  buf[PATH_MAX + 1];
1019         char *path;
1020         char *ptr;
1021
1022         path = malloc(PATH_MAX + 1);
1023         if (path == NULL)
1024                 return NULL;
1025
1026         if (devname[0] != '/') {
1027                 if (getcwd(buf, sizeof(buf) - 1) == NULL) {
1028                         free(path);
1029                         return NULL;
1030                 }
1031                 strcat(buf, "/");
1032                 strcat(buf, devname);
1033         } else {
1034                 strcpy(buf, devname);
1035         }
1036         /* truncate filename before calling realpath */
1037         ptr = strrchr(buf, '/');
1038         if (ptr == NULL) {
1039                 free(path);
1040                 return NULL;
1041         }
1042         *ptr = '\0';
1043         if (path != realpath(buf, path)) {
1044                 free(path);
1045                 return NULL;
1046         }
1047         /* add the filename back */
1048         strcat(path, "/");
1049         strcat(path, ptr + 1);
1050         return path;
1051 }
1052
1053 /* Determine if a device is a block device (as opposed to a file) */
1054 int is_block(char* devname)
1055 {
1056         struct stat st;
1057         int     ret = 0;
1058         char    *devpath;
1059
1060         devpath = absolute_path(devname);
1061         if (devpath == NULL) {
1062                 fprintf(stderr, "%s: failed to resolve path to %s\n",
1063                         progname, devname);
1064                 return -1;
1065         }
1066
1067         ret = access(devname, F_OK);
1068         if (ret != 0) {
1069                 if (strncmp(devpath, "/dev/", 5) == 0) {
1070                         /* nobody sane wants to create a loopback file under
1071                          * /dev. Let's just report the device doesn't exist */
1072                         fprintf(stderr, "%s: %s apparently does not exist\n",
1073                                 progname, devpath);
1074                         ret = -1;
1075                         goto out;
1076                 }
1077                 ret = 0;
1078                 goto out;
1079         }
1080         ret = stat(devpath, &st);
1081         if (ret != 0) {
1082                 fprintf(stderr, "%s: cannot stat %s\n", progname, devpath);
1083                 goto out;
1084         }
1085         ret = S_ISBLK(st.st_mode);
1086 out:
1087         free(devpath);
1088         return ret;
1089 }
1090
1091 int ldiskfs_init(void)
1092 {
1093         /* Required because full path to DEBUGFS is not specified */
1094         setenv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin", 0);
1095
1096         return 0;
1097 }
1098
1099 void ldiskfs_fini(void)
1100 {
1101         return;
1102 }
1103