Whamcloud - gitweb
LU-17744 ldiskfs: mballoc stats fixes
[fs/lustre-release.git] / lustre / utils / mount_lustre.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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/utils/mount_lustre.c
32  *
33  * Author: Robert Read <rread@clusterfs.com>
34  * Author: Nathan Rutman <nathan@clusterfs.com>
35  */
36
37 #ifndef _GNU_SOURCE
38 #define _GNU_SOURCE
39 #endif
40 #include <getopt.h>
41 #include <mntent.h>
42 #include <stdbool.h>
43 #include <stdlib.h>
44 #include <stdio.h>
45 #include <unistd.h>
46 #include <fcntl.h>
47 #include <errno.h>
48 #include <string.h>
49 #include <sys/mount.h>
50 #include <sys/param.h>
51 #include <linux/lustre/lustre_ver.h>
52 #include <ctype.h>
53 #include <limits.h>
54 #if defined(HAVE_LUSTRE_CRYPTO) && defined(HAVE_LIBKEYUTILS)
55 #include <keyutils.h>
56 #endif
57 #include <linux/lnet/nidstr.h>
58 #include <libcfs/util/string.h>
59
60 #include "obdctl.h"
61 #include "mount_utils.h"
62
63 #define MAX_RETRIES 99
64
65 int     verbose;
66 int     version;
67 char    *progname;
68
69 static void usage(FILE *out)
70 {
71         fprintf(out,
72                 "\nThis mount helper should only be invoked via the mount (8) command,\ne.g. mount -t lustre dev dir\n\n");
73         fprintf(out, "usage: %s [-fhnvV] [-o <srvopt>] <device> <mountpt>\n",
74                 progname);
75         fprintf(out, "usage: %s [-fhnvV] [-o <cliopt>] <mgstarget> <mountpt>\n",
76                 progname);
77         fprintf(out,
78                 "\t<device>: the local disk device when mounting a server\n"
79                 "\t<mgstarget>: the server MGS and filesystem for a client:\n"
80                 "\t\t<mgsnid>[:<altmgsnid>...]:/<filesystem>[/<subdir>]\n"
81                 "\t\t\t<mgsnid>: MGS LNet Node Identifier (e.g. mgs01@o2ib)\n"
82                 "\t\t\t<filesystem>: Lustre filesystem name (e.g. lustre1)\n"
83                 "\t\t\t<subdir>: subdirectory of the filesystem to mount\n"
84                 "\t<mountpt>: filesystem mountpoint (e.g. /mnt/lustre)\n"
85                 "\t-f|--fake: fake mount (only update /etc/mtab)\n"
86                 "\t-o force|--force: force mount even if already in /etc/mtab\n"
87                 "\t-h|--help: print this usage message\n"
88                 "\t-n|--nomtab: do not update /etc/mtab after mount\n"
89                 "\t-v|--verbose: print verbose config settings\n"
90                 "\t-V|--version: output build version of the utility and exit\n"
91                 "\tdefault options are marked below with '*'\n"
92                 "\t\t(no)flock: disable* or enable POSIX flock support\n"
93                 "\t\t(no)user_xattr: disable or enable* user xattr namespace\n"
94                 "\t<srvopt>: one or more comma separated server options:\n"
95                 "\t\t(no)acl: disable or enable* POSIX ACL support completely\n"
96                 "\t\tabort_recov: abort server recovery handling\n"
97                 "\t\tnosvc: only start MGC/MGS without starting MDS/OSS\n"
98                 "\t\tnomgs: only start target MDS/OSS, using existing MGS\n"
99                 "\t\tnoscrub: do NOT auto start OI scrub unless requested\n"
100                 "\t\tskip_lfsck: do NOT auto resume paused/crashed LFSCK\n"
101                 "\t\tmax_sectors_kb=<size>: set device max_sectors_kb to size or leaves it untouched if size=0\n"
102                 "\t\t\tIf not specified, device max_sectors_kb will be set to max_hw_sectors_kb\n"
103                 "\t\tmd_stripe_cache_size=<num>: set MD RAID device stripe cache size\n"
104                 "\t<cliopt>: one or more comma separated client options:\n"
105                 "\t\texclude=<ostname>[:<ostname>]: list of inactive OSTs (e.g. lustre-OST0001)\n"
106                 "\t\tlocalflock: enable POSIX flock only on local client\n"
107                 "\t\tretry=<num>: number of times mount is retried by client\n"
108 #ifdef HAVE_GSS
109                 "\t\tskpath=<file|directory>: path of keys to load into kernel keyring\n"
110 #endif
111                 "\t\t(no)user_fid2path: disable* or enable user $MOUNT/.lustre/fid access\n"
112                 "\t\t(no)checksum: disable or enable* data checksums\n"
113                 "\t\t(no)lruresize: disable or enable* LDLM dynamic LRU size\n"
114                 "\t\t(no)lazystatfs: disable or enable* statfs to work if OST is unavailable\n"
115                 "\t\t32bitapi: return only 32-bit inode numbers to userspace\n"
116                 "\t\t(no)verbose: disable or enable* messages at filesystem (un,re)mount\n"
117 #ifdef HAVE_LUSTRE_CRYPTO
118 #ifdef HAVE_LIBKEYUTILS
119                 "\t\ttest_dummy_encryption: enable test dummy encryption mode\n"
120 #endif
121                 "\t\tnoencrypt: disable client side encryption\n"
122 #endif
123                 );
124         exit((out != stdout) ? EINVAL : 0);
125 }
126
127 /*****************************************************************************
128  *
129  * This part was cribbed from util-linux/mount/mount.c.  There was no clear
130  * license information, but many other files in the package are identified as
131  * GNU GPL, so it's a pretty safe bet that was their intent.
132  *
133  ****************************************************************************/
134 struct opt_map {
135         const char *opt;        /* option name */
136         int inv;                /* true if flag value should be inverted */
137         int mask;               /* flag mask value */
138 };
139
140 static const struct opt_map opt_map[] = {
141 /* these flags are parsed by mount, not Lustre */
142 { .opt = "async",   .mask = MS_SYNCHRONOUS, .inv = 1 }, /* asynchronous I/O */
143 { .opt = "atime",   .mask = MS_NOATIME,     .inv = 1 }, /* set access time */
144 { .opt = "auto" },                                      /* allow auto mount */
145 { .opt = "defaults" },                                  /* default options */
146 { .opt = "dev",     .mask = MS_NODEV,       .inv = 1 }, /* interpret devs */
147 { .opt = "exec",    .mask = MS_NOEXEC,      .inv = 1 }, /* allow execution */
148 { .opt = "loop" },
149 { .opt = "noatime", .mask = MS_NOATIME },               /* do not set atime */
150 { .opt = "noauto" },                                    /* mount explicitly */
151 { .opt = "nodev",   .mask = MS_NODEV },                 /* no interpret devs */
152 { .opt = "noowner",                         .inv = 1 }, /* no special privs */
153 { .opt = "nosuid",  .mask = MS_NOSUID },                /* do not honor suid */
154 { .opt = "nouser",                          .inv = 1 }, /* users cannot mount */
155 { .opt = "nousers",                         .inv = 1 }, /* users cannot mount */
156 { .opt = "_netdev" },                                   /* network only */
157 { .opt = "noexec",  .mask = MS_NOEXEC },                /* no execute */
158 { .opt = "remount", .mask = MS_REMOUNT },               /* remount */
159 { .opt = "ro",      .mask = MS_RDONLY },                /* read-only */
160 { .opt = "rw",      .mask = MS_RDONLY,      .inv = 1 }, /* read-write */
161 { .opt = "suid",    .mask = MS_NOSUID,      .inv = 1 }, /* honor suid */
162 { .opt = "sync",    .mask = MS_SYNCHRONOUS },           /* synchronous I/O */
163 #ifdef MS_NODIRATIME
164 { .opt = "diratime",                                    /* set access time */
165                     .mask = MS_NODIRATIME,  .inv = 1 }, /* on read */
166 { .opt = "nodiratime",                                  /* do not set access */
167                     .mask = MS_NODIRATIME },            /* time on read */
168 #endif
169 #ifdef MS_RELATIME
170 { .opt = "norelatime",                                  /* do not set rel */
171                     .mask = MS_RELATIME,    .inv = 1 }, /* access time */
172 { .opt = "relatime",                                    /* set relative */
173                     .mask = MS_RELATIME },              /* access time */
174 #endif
175 #ifdef MS_STRICTATIME
176 { .opt = "strictatime",
177                     .mask = MS_STRICTATIME },           /* strict access time */
178 #endif
179 { .opt = NULL } };
180 /****************************************************************************/
181
182 /*
183  * 1  = don't pass on to lustre
184  * 0  = pass on to lustre
185  */
186 static int parse_one_option(const char *check, int *flagp)
187 {
188         const struct opt_map *opt;
189
190         for (opt = &opt_map[0]; opt->opt != NULL; opt++) {
191                 if (strncmp(check, opt->opt, strlen(opt->opt)) == 0) {
192                         if (opt->mask) {
193                                 if (opt->inv)
194                                         *flagp &= ~(opt->mask);
195                                 else
196                                         *flagp |= opt->mask;
197                         }
198                         return 1;
199                 }
200         }
201         /*
202          * Assume any unknown options are valid and pass them on.  The mount
203          * will fail if lmd_parse, ll_options or ldiskfs doesn't recognize it.
204          */
205         return 0;
206 }
207
208 static size_t merge_strings(char *dst, const char *src, size_t size)
209 {
210         size_t dsize = strlen(dst);
211         size_t len = strlen(src);
212         size_t ret = dsize + len;
213
214         dst  += dsize;
215         size -= dsize;
216         if (len >= size)
217                 len = size - 1;
218         memcpy(dst, src, len);
219         dst[len] = '\0';
220         return ret;
221 }
222
223 static int append_option(char *options, size_t options_len,
224                          const char *param, const char *value)
225 {
226         int rc;
227
228         if (options[0] != '\0') {
229                 rc = merge_strings(options, ",", options_len);
230                 if (rc >= options_len)
231                         goto out_err;
232         }
233
234         rc = merge_strings(options, param, options_len);
235         if (rc >= options_len)
236                 goto out_err;
237
238         if (value) {
239                 rc = merge_strings(options, value, options_len);
240                 if (rc >= options_len)
241                         goto out_err;
242         }
243         return 0;
244 out_err:
245         fprintf(stderr, "error: mount options %s%s too long\n", param, value);
246         return E2BIG;
247 }
248
249 /*
250  * Replace options with subset of Lustre-specific options, and
251  * fill in mount flags
252  */
253 static int parse_options(struct mount_opts *mop, char *orig_options,
254                          int *flagp, size_t options_len)
255 {
256         char *options, *opt, *nextopt, *arg, *val;
257         int rc = 0;
258
259         options = calloc(strlen(orig_options) + 1, 1);
260         if (!options)
261                 return ENOMEM;
262
263         *flagp = 0;
264         nextopt = orig_options;
265         while ((opt = strsep(&nextopt, ","))) {
266                 if (!*opt)
267                         /* empty option */
268                         continue;
269
270                 /* Handle retries in a slightly different manner */
271                 arg = opt;
272                 val = strchr(opt, '=');
273                 /*
274                  * please note that some ldiskfs mount options are also in
275                  * the form of param=value. We should pay attention not to
276                  * remove those mount options, see bug 22097.
277                  */
278                 if (val && strncmp(arg, "max_sectors_kb", 14) == 0) {
279                         mop->mo_max_sectors_kb = atoi(val + 1);
280                 } else if (val &&
281                            strncmp(arg, "md_stripe_cache_size", 20) == 0) {
282                         mop->mo_md_stripe_cache_size = atoi(val + 1);
283                 } else if (val && strncmp(arg, "retry", 5) == 0) {
284                         mop->mo_retry = atoi(val + 1);
285                         if (mop->mo_retry > MAX_RETRIES)
286                                 mop->mo_retry = MAX_RETRIES;
287                         else if (mop->mo_retry < 0)
288                                 mop->mo_retry = 0;
289                 } else if (val && strncmp(arg, "mgssec", 6) == 0) {
290                         rc = append_option(options, options_len, opt, NULL);
291                         if (rc != 0)
292                                 goto out_options;
293                 } else if (strncmp(arg, "nosvc", 5) == 0) {
294                         mop->mo_nosvc = 1;
295                         rc = append_option(options, options_len, opt, NULL);
296                         if (rc != 0)
297                                 goto out_options;
298                 } else if (strcmp(opt, "force") == 0) {
299                         /* XXX special check for 'force' option */
300                         ++mop->mo_force;
301                         printf("force: %d\n", mop->mo_force);
302 #ifdef HAVE_GSS
303                 } else if (val && strncmp(opt, "skpath=", 7) == 0) {
304                         if (strlen(val) + 1 >= sizeof(mop->mo_skpath)) {
305                                 fprintf(stderr,
306                                         "%s: shared key path too long\n",
307                                         progname);
308                                 free(options);
309                                 return EINVAL;
310                         }
311                         strncpy(mop->mo_skpath, val + 1,
312                                 sizeof(mop->mo_skpath) - 1);
313 #endif
314 #ifdef HAVE_LUSTRE_CRYPTO
315                 } else if (strncmp(arg, "test_dummy_encryption", 21) == 0) {
316 #ifdef HAVE_LIBKEYUTILS
317 #ifdef HAVE_FSCRYPT_DUMMY_CONTEXT_ENABLED
318                         /* Using dummy encryption mode requires inserting a
319                          * special dummy key into the session keyring.
320                          * Key type is "logon", key description is
321                          * "fscrypt:4242424242424242", and key payload has to be
322                          * in the form <mode><raw><size>, where:
323                          * <mode> is "\x00\x00\x00\x00"
324                          * <raw> is "$(printf ""\\\\x%02x"" {0..63})"
325                          * <size> is "\x40\x00\x00\x00" for little endian,
326                          * "\x00\x00\x00\x40" for big endian.
327                          */
328                         char payload[72];
329                         int *p = (int *)payload;
330                         char *q = (char *)(p + 1);
331                         int i = 0;
332                         key_serial_t key;
333
334                         *p = 0;
335                         while (i < 0x40)
336                                 *(q++) = i++;
337                         p = (int *)q;
338                         *p = 0x40;
339
340                         key = add_key("logon", "fscrypt:4242424242424242",
341                                       (const void *)payload, sizeof(payload),
342                                       KEY_SPEC_SESSION_KEYRING);
343
344                         if (key == -1) {
345                                 fprintf(stderr,
346                                         "%s: test dummy encryption option ignored: could not insert dummy encryption key into session keyring\n",
347                                         progname);
348                         } else {
349                                 /* pass this on as an option */
350                                 rc = append_option(options, options_len, opt,
351                                                    NULL);
352                                 if (rc != 0)
353                                         goto out_options;
354                         }
355 #else /* !HAVE_FSCRYPT_DUMMY_CONTEXT_ENABLED */
356                         /* pass this on as an option */
357                         rc = append_option(options, options_len, opt,
358                                            NULL);
359                         if (rc != 0)
360                                 goto out_options;
361 #endif
362 #else /* HAVE_LIBKEYUTILS */
363                         fprintf(stderr,
364                                 "%s: test dummy encryption option ignored: Lustre not built with libkeyutils support\n",
365                                 progname);
366 #endif
367 #endif
368                 } else if (parse_one_option(opt, flagp) == 0) {
369                         /* pass this on as an option */
370                         rc = append_option(options, options_len, opt, NULL);
371                         if (rc != 0)
372                                 goto out_options;
373                 }
374         }
375 #ifdef MS_STRICTATIME
376 #if LUSTRE_VERSION_CODE > OBD_OCD_VERSION(3, 2, 53, 0)
377         /*
378          * LU-1783
379          * In the future when upstream fixes land in all supported kernels
380          * we should stop forcing MS_STRICTATIME in lustre mounts.
381          * We override the kernel level default of MS_RELATIME for now
382          * due to a kernel vfs level bug in atime updates that fails
383          * to reset timestamps from the future.
384          */
385 #warn "remove MS_STRICTATIME override if kernel updates atime from the future"
386 #endif
387         /*
388          * set strictatime to default if NOATIME or RELATIME
389          * not given explicit
390          */
391         if (!(*flagp & (MS_NOATIME | MS_RELATIME)))
392                 *flagp |= MS_STRICTATIME;
393 #endif
394         strcpy(orig_options, options);
395
396 out_options:
397         free(options);
398         return rc;
399 }
400
401 #ifdef HAVE_SERVER_SUPPORT
402 /* Add mgsnids from ldd params */
403 static int add_mgsnids(struct mount_opts *mop, char *options,
404                        const char *params, size_t options_len)
405 {
406         char *ptr = (char *)params;
407         char tmp, *sep;
408         int rc = 0;
409
410         while ((ptr = strstr(ptr, PARAM_MGSNODE)) != NULL) {
411                 sep = strchr(ptr, ' ');
412                 if (sep) {
413                         tmp = *sep;
414                         *sep = '\0';
415                 }
416                 rc = append_option(options, options_len, ptr, NULL);
417                 if (rc != 0)
418                         goto out;
419                 mop->mo_have_mgsnid++;
420                 if (sep) {
421                         *sep = tmp;
422                         ptr = sep;
423                 } else {
424                         break;
425                 }
426         }
427
428 out:
429         return rc;
430 }
431
432 static int clear_update_ondisk(char *source, struct lustre_disk_data *ldd)
433 {
434         char wanted_mountopts[512] = "";
435         struct mkfs_opts mkop;
436         int ret;
437         int ret2;
438
439         memset(&mkop, 0, sizeof(mkop));
440         mkop.mo_ldd = *ldd;
441         mkop.mo_ldd.ldd_flags &= ~LDD_F_UPDATE;
442         mkop.mo_flags = MO_NOHOSTID_CHECK; /* Ignore missing hostid */
443         if (strlen(source) > sizeof(mkop.mo_device) - 1) {
444                 fatal();
445                 fprintf(stderr, "Device name too long: %s\n", source);
446                 return -E2BIG;
447         }
448         strncpy(mkop.mo_device, source, sizeof(mkop.mo_device));
449
450         ret = osd_prepare_lustre(&mkop,
451                                  wanted_mountopts, sizeof(wanted_mountopts));
452         if (ret) {
453                 fatal();
454                 fprintf(stderr, "Can't prepare device %s: %s\n",
455                         source, strerror(ret));
456                 return ret;
457         }
458
459         /* Create the loopback file */
460         if (mkop.mo_flags & MO_IS_LOOP) {
461                 ret = access(mkop.mo_device, F_OK);
462                 if (ret) {
463                         ret = errno;
464                         fatal();
465                         fprintf(stderr, "Can't access device %s: %s\n",
466                                 source, strerror(ret));
467                         return ret;
468                 }
469
470                 ret = loop_setup(&mkop);
471                 if (ret) {
472                         fatal();
473                         fprintf(stderr, "Loop device setup for %s failed: %s\n",
474                                 mkop.mo_device, strerror(ret));
475                         return ret;
476                 }
477         }
478         ret = osd_write_ldd(&mkop);
479         if (ret != 0) {
480                 fatal();
481                 fprintf(stderr, "failed to write local files: %s\n",
482                         strerror(ret));
483         }
484
485         ret2 = loop_cleanup(&mkop);
486         if (ret == 0)
487                 ret = ret2;
488
489         return ret;
490 }
491
492 static int parse_ldd(char *source, struct mount_opts *mop,
493                      char *options, size_t options_len)
494 {
495         struct lustre_disk_data *ldd = &mop->mo_ldd;
496         char *cur, *start;
497         char *temp_options;
498         int rc = 0;
499
500         rc = osd_is_lustre(source, &ldd->ldd_mount_type);
501         if (rc == 0) {
502                 fprintf(stderr,
503                         "%s: %s has not been formatted with mkfs.lustre or the backend filesystem type is not supported by this tool\n",
504                         progname, source);
505                 return ENODEV;
506         }
507
508         rc = osd_read_ldd(source, ldd);
509         if (rc) {
510                 fprintf(stderr,
511                         "%s: %s failed to read permanent mount data: %s\n",
512                         progname, source, rc >= 0 ? strerror(rc) : "");
513                 return rc;
514         }
515
516         if ((IS_MDT(ldd) || IS_OST(ldd)) &&
517             (ldd->ldd_flags & LDD_F_NEED_INDEX)) {
518                 fprintf(stderr,
519                         "%s: %s has no index assigned (probably formatted with old mkfs)\n",
520                         progname, source);
521                 return EINVAL;
522         }
523
524         if (ldd->ldd_flags & LDD_F_UPDATE)
525                 clear_update_ondisk(source, ldd);
526
527         /* Since we never rewrite ldd, ignore temp flags */
528         ldd->ldd_flags &= ~(LDD_F_VIRGIN | LDD_F_WRITECONF |
529                             LDD_F_NO_LOCAL_LOGS);
530
531         /* This is to make sure default options go first */
532         temp_options = strdup(options);
533         if (!temp_options) {
534                 fprintf(stderr, "%s: can't allocate memory for temp_options\n",
535                         progname);
536                 return ENOMEM;
537         }
538         strncpy(options, ldd->ldd_mount_opts, options_len);
539         rc = append_option(options, options_len, temp_options, NULL);
540         free(temp_options);
541         if (rc != 0)
542                 return rc;
543
544         /* svname of the form lustre:OST1234 means never registered */
545         rc = strlen(ldd->ldd_svname);
546         if (strcmp(ldd->ldd_svname, "MGS") != 0) {
547                 if (rc < 8) {
548                         fprintf(stderr, "%s: invalid name '%s'\n",
549                                 progname, ldd->ldd_svname);
550                         return EINVAL;
551                 } else if (ldd->ldd_svname[rc - 8] == ':') {
552                         ldd->ldd_svname[rc - 8] = '-';
553                         ldd->ldd_flags |= LDD_F_VIRGIN;
554                 } else if (ldd->ldd_svname[rc - 8] == '=') {
555                         ldd->ldd_svname[rc - 8] = '-';
556                         ldd->ldd_flags |= LDD_F_WRITECONF;
557                 } else if (ldd->ldd_svname[rc - 8] == '+') {
558                         ldd->ldd_svname[rc - 8] = '-';
559                         ldd->ldd_flags |= LDD_F_NO_LOCAL_LOGS;
560                 }
561         }
562         /* backend osd type */
563         rc = append_option(options, options_len, "osd=",
564                            mt_type(ldd->ldd_mount_type));
565         if (rc != 0)
566                 return rc;
567
568         if (!mop->mo_have_mgsnid) {
569                 /*
570                  * Only use disk data if mount -o mgsnode=nid wasn't
571                  * specified
572                  */
573                 if (ldd->ldd_flags & LDD_F_SV_TYPE_MGS) {
574                         rc = append_option(options, options_len, "mgs", NULL);
575                         if (rc != 0)
576                                 return rc;
577                         mop->mo_have_mgsnid++;
578                 } else {
579                         if (add_mgsnids(mop, options, ldd->ldd_params,
580                                         options_len))
581                                 return E2BIG;
582                 }
583         }
584         /* Better have an mgsnid by now */
585         if (!mop->mo_have_mgsnid) {
586                 fprintf(stderr, "%s: missing option mgsnode=<nid>\n",
587                         progname);
588                 return EINVAL;
589         }
590
591         if (ldd->ldd_flags & LDD_F_VIRGIN) {
592                 rc = append_option(options, options_len, "virgin", NULL);
593                 if (rc != 0)
594                         return rc;
595         }
596         if (ldd->ldd_flags & LDD_F_UPDATE) {
597                 rc = append_option(options, options_len, "update", NULL);
598                 if (rc != 0)
599                         return rc;
600         }
601         if (ldd->ldd_flags & LDD_F_WRITECONF) {
602                 rc = append_option(options, options_len, "writeconf", NULL);
603                 if (rc != 0)
604                         return rc;
605         }
606         if (ldd->ldd_flags & LDD_F_NO_LOCAL_LOGS) {
607                 rc = append_option(options, options_len, "nolocallogs", NULL);
608                 if (rc != 0)
609                         return rc;
610         }
611         if (ldd->ldd_flags & LDD_F_NO_PRIMNODE) {
612                 rc = append_option(options, options_len, "noprimnode", NULL);
613                 if (rc != 0)
614                         return rc;
615         }
616
617         /*
618          * prefix every lustre parameter with param= so that in-kernel
619          * mount can recognize them properly and send to MGS at registration
620          */
621         start = ldd->ldd_params;
622         while (start && *start != '\0') {
623                 while (*start == ' ')
624                         start++;
625                 if (*start == '\0')
626                         break;
627                 cur = start;
628                 start = strchr(cur, ' ');
629                 if (start) {
630                         *start = '\0';
631                         start++;
632                 }
633                 rc = append_option(options, options_len, "param=", cur);
634                 if (rc != 0)
635                         return rc;
636         }
637
638         /* svname must be last option */
639         rc = append_option(options, options_len, "svname=", ldd->ldd_svname);
640
641         return rc;
642 }
643 #endif /* HAVE_SERVER_SUPPORT */
644
645 static void set_defaults(struct mount_opts *mop)
646 {
647         memset(mop, 0, sizeof(*mop));
648         mop->mo_usource = NULL;
649         mop->mo_source = NULL;
650         mop->mo_nomtab = 0;
651         mop->mo_fake = 0;
652         mop->mo_force = 0;
653         mop->mo_retry = 0;
654         mop->mo_have_mgsnid = 0;
655         mop->mo_md_stripe_cache_size = 16384;
656         mop->mo_orig_options = "";
657         mop->mo_nosvc = 0;
658         mop->mo_max_sectors_kb = -1;
659 }
660
661 static int parse_opts(int argc, char *const argv[], struct mount_opts *mop)
662 {
663         static struct option long_opts[] = {
664         { .val = 1,     .name = "force",        .has_arg = no_argument },
665         { .val = 'f',   .name = "fake",         .has_arg = no_argument },
666         { .val = 'h',   .name = "help",         .has_arg = no_argument },
667         { .val = 'n',   .name = "nomtab",       .has_arg = no_argument },
668         { .val = 'o',   .name = "options",      .has_arg = required_argument },
669         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
670         { .val = 'V',   .name = "version",      .has_arg = no_argument },
671         { .name = NULL } };
672         char real_path[PATH_MAX] = {'\0'};
673         FILE *f;
674         char path[256], name[256];
675         size_t sz;
676         char *ptr;
677         int opt, rc;
678
679         while ((opt = getopt_long(argc, argv, "fhno:vV",
680                                   long_opts, NULL)) != EOF){
681                 switch (opt) {
682                 case 1:
683                         ++mop->mo_force;
684                         printf("force: %d\n", mop->mo_force);
685                         break;
686                 case 'f':
687                         ++mop->mo_fake;
688                         printf("fake: %d\n", mop->mo_fake);
689                         break;
690                 case 'h':
691                         usage(stdout);
692                         break;
693                 case 'n':
694                         ++mop->mo_nomtab;
695                         printf("nomtab: %d\n", mop->mo_nomtab);
696                         break;
697                 case 'o':
698                         mop->mo_orig_options = optarg;
699                         break;
700                 case 'v':
701                         ++verbose;
702                         break;
703                 case 'V':
704                         ++version;
705                         fprintf(stdout, "%s %s (libmount)\n", progname,
706                                 LUSTRE_VERSION_STRING);
707                         return 0;
708                 default:
709                         fprintf(stderr, "%s: unknown option '%c'\n",
710                                 progname, opt);
711                         usage(stderr);
712                         break;
713                 }
714         }
715
716         if (optind + 2 > argc) {
717                 fprintf(stderr, "%s: too few arguments\n", progname);
718                 usage(stderr);
719         }
720
721         mop->mo_usource = argv[optind];
722         if (!mop->mo_usource)
723                 usage(stderr);
724
725         /**
726          * Try to get the real path to the device, in case it is a
727          * symbolic link for instance
728          */
729         if (realpath(mop->mo_usource, real_path) != NULL) {
730                 ptr = strrchr(real_path, '/');
731                 if (ptr && strncmp(ptr, "/dm-", 4) == 0 &&
732                     isdigit(*(ptr + 4))) {
733                         snprintf(path, sizeof(path), "/sys/block/%s/dm/name",
734                                  ptr + 1);
735                         if ((f = fopen(path, "r"))) {
736                                 /* read "<name>\n" from sysfs */
737                                 if (fgets(name, sizeof(name), f) &&
738                                     (sz = strlen(name)) > 1) {
739                                         name[sz - 1] = '\0';
740                                         snprintf(real_path, sizeof(real_path),
741                                                  "/dev/mapper/%s", name);
742                                 }
743                                 fclose(f);
744                         }
745                 }
746                 mop->mo_usource = strdup(real_path);
747         }
748
749         ptr = strstr(mop->mo_usource, ":/");
750         if (ptr) {
751                 mop->mo_source = convert_hostnames(mop->mo_usource, true);
752                 if (!mop->mo_source)
753                         usage(stderr);
754         } else {
755                 mop->mo_source = strdup(mop->mo_usource);
756         }
757
758         if (realpath(argv[optind + 1], mop->mo_target) == NULL) {
759                 rc = errno;
760                 fprintf(stderr, "warning: %s: cannot resolve: %s\n",
761                         argv[optind + 1], strerror(errno));
762                 return rc;
763         }
764
765         return 0;
766 }
767
768 #ifdef HAVE_SERVER_SUPPORT
769 /*
770  * change label from <fsname>:<index> to
771  * <fsname>-<index> to indicate the device has
772  * been registered. only if the label is
773  * supposed to be changed and target service
774  * is supposed to start
775  */
776 static void label_lustre(struct mount_opts *mop)
777 {
778         if (mop->mo_nosvc)
779                 return;
780
781         if (mop->mo_ldd.ldd_flags & (LDD_F_VIRGIN | LDD_F_WRITECONF |
782             LDD_F_NO_LOCAL_LOGS)) {
783                 (void)osd_label_lustre(mop);
784         } else {
785                 struct lustre_disk_data ldd;
786                 int rc;
787
788                 /*
789                  * device label could be changed after journal recovery,
790                  * it should also be relabeled for mount has succeeded.
791                  */
792                 memset(&ldd, 0, sizeof(ldd));
793                 ldd.ldd_mount_type = mop->mo_ldd.ldd_mount_type;
794                 rc = osd_read_ldd(mop->mo_source, &ldd);
795                 if (rc == 0) {
796                         rc = strlen(ldd.ldd_svname);
797                         if (rc >= 8 && ldd.ldd_svname[rc - 8] != '-')
798                                 (void)osd_label_lustre(mop);
799                 }
800         }
801 }
802 #endif /* HAVE_SERVER_SUPPORT */
803
804 int main(int argc, char *const argv[])
805 {
806         struct mount_opts mop;
807         char *options;
808         int i, flags;
809         int rc;
810         bool client;
811         size_t maxopt_len;
812         size_t g_pagesize;
813
814         progname = strrchr(argv[0], '/');
815         progname = progname ? progname + 1 : argv[0];
816
817         set_defaults(&mop);
818
819         g_pagesize = sysconf(_SC_PAGESIZE);
820         if (g_pagesize == -1) {
821                 rc = errno;
822                 printf("error: %d failed to get page size.\n", rc);
823                 return rc;
824         }
825         maxopt_len = MIN(g_pagesize, 64 * 1024);
826
827         rc = parse_opts(argc, argv, &mop);
828         if (rc || version)
829                 return rc;
830
831         if (verbose) {
832                 for (i = 0; i < argc; i++)
833                         printf("arg[%d] = %s\n", i, argv[i]);
834                 printf("source = %s (%s), target = %s\n", mop.mo_usource,
835                        mop.mo_source, mop.mo_target);
836                 printf("options = %s\n", mop.mo_orig_options);
837         }
838
839         options = malloc(maxopt_len);
840         if (!options) {
841                 fprintf(stderr, "can't allocate memory for options\n");
842                 rc = ENOMEM;
843                 goto out_mo_source;
844         }
845
846         if (strlen(mop.mo_orig_options) >= maxopt_len) {
847                 fprintf(stderr, "error: mount options too long\n");
848                 rc = E2BIG;
849                 goto out_options;
850         }
851
852         strcpy(options, mop.mo_orig_options);
853         rc = parse_options(&mop, options, &flags, maxopt_len);
854         if (rc) {
855                 fprintf(stderr, "%s: can't parse options: %s\n",
856                         progname, options);
857                 goto out_options;
858         }
859
860         if (!mop.mo_force) {
861                 rc = check_mtab_entry(mop.mo_usource, mop.mo_source,
862                                       mop.mo_target, "lustre");
863                 if (rc && !(flags & MS_REMOUNT)) {
864                         fprintf(stderr,
865                                 "%s: according to %s %s is already mounted on %s\n",
866                                 progname, MOUNTED, mop.mo_usource,
867                                 mop.mo_target);
868                         rc = EEXIST;
869                         goto out_options;
870                 }
871                 if (!rc && (flags & MS_REMOUNT)) {
872                         fprintf(stderr,
873                                 "%s: according to %s %s is not already mounted on %s\n",
874                                 progname, MOUNTED, mop.mo_usource,
875                                 mop.mo_target);
876                         rc = ENOENT;
877                         goto out_options;
878                 }
879         }
880         if (flags & MS_REMOUNT)
881                 mop.mo_nomtab++;
882
883         rc = access(mop.mo_target, F_OK);
884         if (rc) {
885                 rc = errno;
886                 fprintf(stderr, "%s: %s inaccessible: %s\n", progname,
887                         mop.mo_target, strerror(errno));
888                 goto out_options;
889         }
890
891         client = (strstr(mop.mo_usource, ":/") != NULL);
892         if (!client) {
893 #ifdef HAVE_SERVER_SUPPORT
894                 rc = osd_init();
895                 if (rc)
896                         goto out_options;
897
898                 rc = parse_ldd(mop.mo_source, &mop, options, maxopt_len);
899                 if (rc)
900                         goto out_osd;
901 #else
902                 rc = EINVAL;
903                 fprintf(stderr, "%s: cannot mount %s: no server support\n",
904                         progname, mop.mo_usource);
905                 goto out_options;
906 #endif
907         }
908
909         /*
910          * In Linux 2.4, the target device doesn't get passed to any of our
911          * functions.  So we'll stick it on the end of the options.
912          */
913         rc = append_option(options, maxopt_len, "device=", mop.mo_source);
914         if (rc != 0)
915                 goto out_osd;
916
917         if (verbose)
918                 printf("mounting device %s at %s, flags=%#x options=%s\n",
919                        mop.mo_source, mop.mo_target, flags, options);
920
921 #ifdef HAVE_SERVER_SUPPORT
922         if (!client && osd_tune_lustre(mop.mo_source, &mop)) {
923                 if (verbose)
924                         fprintf(stderr,
925                                 "%s: unable to set tunables for %s (may cause reduced IO performance)\n",
926                                 argv[0], mop.mo_source);
927         }
928 #endif
929 #ifdef HAVE_GSS
930         if (mop.mo_skpath[0] != '\0') {
931                 /* Treat shared key failures as fatal */
932                 rc = load_shared_keys(&mop);
933                 if (rc) {
934                         fprintf(stderr, "%s: Error loading shared keys: %s\n",
935                                 progname, strerror(rc));
936                         goto out_osd;
937                 }
938         }
939 #endif /* HAVE_GSS */
940
941         if (!mop.mo_fake) {
942                 char *fstype;
943
944                 /* Prefer filesystem type given on mount command line
945                  * so it appears correctly in the /proc/mounts output.
946                  */
947                 if (strstr(argv[0], "mount.lustre_tgt"))
948                         fstype = "lustre_tgt";
949                 else
950                         fstype = "lustre";
951                 /*
952                  * flags and target get to lustre_get_sb(), but not
953                  * lustre_fill_super().  Lustre ignores the flags, but mount
954                  * does not.
955                  */
956                 for (i = 0, rc = -EAGAIN; i <= mop.mo_retry && rc != 0; i++) {
957                         rc = mount(mop.mo_source, mop.mo_target, fstype,
958                                    flags, (void *)options);
959                         if (rc != 0) {
960                                 if (verbose) {
961                                         fprintf(stderr,
962                                                 "%s: mount -t %s %s at %s failed: %s retries left: %d\n",
963                                                 basename(progname), fstype,
964                                                 mop.mo_usource, mop.mo_target,
965                                                 strerror(errno),
966                                                 mop.mo_retry - i);
967                                 }
968
969                                 /* Pre-2.13 Lustre without 'lustre_tgt' type?
970                                  * Try with 'lustre' instead.  Eventually this
971                                  * can be removed (e.g. 2.18 or whenever).
972                                  */
973                                 if (errno == ENODEV &&
974                                     strcmp(fstype, "lustre_tgt") == 0) {
975                                         fstype = "lustre";
976                                         i--;
977                                         continue;
978                                 }
979
980                                 if (mop.mo_retry) {
981                                         int limit = i / 2 > 5 ? i / 2 : 5;
982
983                                         sleep(1 << limit);
984                                 } else {
985                                         rc = errno;
986                                 }
987 #ifdef HAVE_SERVER_SUPPORT
988                         } else {
989                                 if (!client)
990                                         label_lustre(&mop);
991 #endif
992                         }
993                 }
994         }
995
996         if (rc) {
997                 char *cli;
998
999                 rc = errno;
1000
1001                 cli = strrchr(mop.mo_usource, ':');
1002                 if (cli && (strlen(cli) > 2))
1003                         cli += 2;
1004                 else
1005                         cli = NULL;
1006
1007                 fprintf(stderr, "%s: mount %s at %s failed: %s\n", progname,
1008                         mop.mo_usource, mop.mo_target, strerror(errno));
1009                 if (errno == EBUSY)
1010                         fprintf(stderr,
1011                                 "Is the backend filesystem mounted?\n Check /etc/mtab and /proc/mounts\n");
1012                 if (errno == ENODEV)
1013                         fprintf(stderr,
1014                                 "Are the lustre modules loaded?\n Check /etc/modprobe.conf and /proc/filesystems\n");
1015                 if (errno == ENOTBLK)
1016                         fprintf(stderr, "Do you need -o loop?\n");
1017                 if (errno == ENOMEDIUM)
1018                         fprintf(stderr,
1019                                 "This filesystem needs at least 1 OST\n");
1020                 if (errno == ENOENT) {
1021                         fprintf(stderr, "Is the MGS specification correct?\n");
1022                         fprintf(stderr, "Is the filesystem name correct?\n");
1023                         fprintf(stderr,
1024                                 "If upgrading, is the copied client log valid? (see upgrade docs)\n");
1025                 }
1026                 if (errno == EALREADY)
1027                         fprintf(stderr,
1028                                 "The target service is already running. (%s)\n",
1029                                 mop.mo_usource);
1030                 if (errno == ENXIO)
1031                         fprintf(stderr,
1032                                 "The target service failed to start (bad config log?) (%s).  See /var/log/messages.\n",
1033                                 mop.mo_usource);
1034                 if (errno == EIO)
1035                         fprintf(stderr, "Is the MGS running?\n");
1036                 if (errno == EADDRINUSE)
1037                         fprintf(stderr,
1038                                 "The target service's index is already in use. (%s)\n",
1039                                 mop.mo_usource);
1040                 if (errno == EINVAL) {
1041                         fprintf(stderr, "This may have multiple causes.\n");
1042                         if (cli)
1043                                 fprintf(stderr,
1044                                         "Is '%s' the correct filesystem name?\n",
1045                                         cli);
1046                         fprintf(stderr, "Are the mount options correct?\n");
1047                         fprintf(stderr, "Check the syslog for more info.\n");
1048                 }
1049
1050                 /* May as well try to clean up loop devs */
1051                 if (strncmp(mop.mo_usource, "/dev/loop", 9) == 0) {
1052                         char cmd[256];
1053                         int ret;
1054
1055                         sprintf(cmd, "/sbin/losetup -d %s", mop.mo_usource);
1056                         if ((ret = system(cmd)) < 0)
1057                                 rc = errno;
1058                         else if (ret > 0)
1059                                 rc = WEXITSTATUS(ret);
1060                 }
1061
1062         } else {
1063                 /*
1064                  * Deal with utab just for client. Note that we ignore
1065                  * the return value here since it is not worth to fail
1066                  * mount by prevent some rare cases
1067                  */
1068                 if (strstr(mop.mo_usource, ":/") != NULL)
1069                         update_utab_entry(&mop);
1070                 if (!mop.mo_nomtab) {
1071                         rc = update_mtab_entry(mop.mo_usource, mop.mo_target,
1072                                                "lustre", mop.mo_orig_options,
1073                                                0, 0, 0);
1074                 }
1075         }
1076
1077 out_osd:
1078 #ifdef HAVE_SERVER_SUPPORT
1079         if (!client)
1080                 osd_fini();
1081 #endif
1082 out_options:
1083         free(options);
1084
1085 out_mo_source:
1086         /* mo_usource should be freed, but we can rely on the kernel */
1087         free(mop.mo_source);
1088         return rc;
1089 }