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