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