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