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