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