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