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