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