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