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