Whamcloud - gitweb
LU-6401 uapi: migrate remaining uapi headers to uapi directory
[fs/lustre-release.git] / lustre / utils / mount_utils.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) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, 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
33 #if HAVE_CONFIG_H
34 #  include "config.h"
35 #endif /* HAVE_CONFIG_H */
36
37 #include <inttypes.h>
38 #include <limits.h>
39 #include <mntent.h>
40 #include <stdio.h>
41 #include <errno.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <config.h>
45 #include <linux/lustre/lustre_ver.h>
46 #include <sys/mount.h>
47 #include <sys/stat.h>
48 #include <sys/utsname.h>
49 #include <linux/loop.h>
50 #include <sys/types.h>
51 #include <dirent.h>
52 #include <dlfcn.h>
53 #include <linux/lustre/lustre_cfg.h>
54 #include <dirent.h>
55 #include <sys/types.h>
56 #include <sys/xattr.h>
57
58 #ifdef HAVE_GSS
59 #include <keyutils.h>
60 #include <lustre/utils/gss/sk_utils.h>
61 #endif
62
63 #include "mount_utils.h"
64
65 extern char *progname;
66 extern int verbose;
67
68 #define vprint(fmt, arg...) if (verbose > 0) printf(fmt, ##arg)
69 #define verrprint(fmt, arg...) if (verbose >= 0) fprintf(stderr, fmt, ##arg)
70
71 static struct module_backfs_ops *backfs_ops[LDD_MT_LAST];
72
73 void fatal(void)
74 {
75         verbose = 0;
76         fprintf(stderr, "\n%s FATAL: ", progname);
77 }
78
79 int run_command(char *cmd, int cmdsz)
80 {
81         char log[] = "/tmp/run_command_logXXXXXX";
82         int fd = -1, rc;
83
84         if ((cmdsz - strlen(cmd)) < 6) {
85                 fatal();
86                 fprintf(stderr, "Command buffer overflow: %.*s...\n",
87                         cmdsz, cmd);
88                 return ENOMEM;
89         }
90
91         if (verbose > 1) {
92                 printf("cmd: %s\n", cmd);
93         } else {
94                 if ((fd = mkstemp(log)) >= 0) {
95                         close(fd);
96                         strcat(cmd, " >");
97                         strcat(cmd, log);
98                 }
99         }
100         strcat(cmd, " 2>&1");
101
102         /* Can't use popen because we need the rv of the command */
103         rc = system(cmd);
104         if (rc && (fd >= 0)) {
105                 char buf[128];
106                 FILE *fp;
107                 fp = fopen(log, "r");
108                 if (fp) {
109                         while (fgets(buf, sizeof(buf), fp) != NULL) {
110                                 printf("   %s", buf);
111                         }
112                         fclose(fp);
113                 }
114         }
115         if (fd >= 0)
116                 remove(log);
117         return rc;
118 }
119
120 int add_param(char *buf, char *key, char *val)
121 {
122         int end = sizeof(((struct lustre_disk_data *)0)->ldd_params);
123         int start = strlen(buf);
124         int keylen = 0;
125
126         if (key)
127                 keylen = strlen(key);
128         if (start + 1 + keylen + strlen(val) >= end) {
129                 fprintf(stderr, "%s: params are too long-\n%s %s%s\n",
130                         progname, buf, key ? key : "", val);
131                 return 1;
132         }
133
134         sprintf(buf + start, " %s%s", key ? key : "", val);
135         return 0;
136 }
137
138 int get_param(char *buf, char *key, char **val)
139 {
140         int i, key_len = strlen(key);
141         char *ptr;
142
143         ptr = strstr(buf, key);
144         if (ptr) {
145                 *val = strdup(ptr + key_len);
146                 if (*val == NULL)
147                         return ENOMEM;
148
149                 for (i = 0; i < strlen(*val); i++)
150                         if (((*val)[i] == ' ') || ((*val)[i] == '\0'))
151                                 break;
152
153                 (*val)[i] = '\0';
154                 return 0;
155         }
156
157         return ENOENT;
158 }
159
160 int append_param(char *buf, char *key, char *val, char sep)
161 {
162         int key_len, i, offset, old_val_len;
163         char *ptr = NULL, str[1024];
164
165         if (key)
166                 ptr = strstr(buf, key);
167
168         /* key doesn't exist yet, so just add it */
169         if (ptr == NULL)
170                 return add_param(buf, key, val);
171
172         key_len = strlen(key);
173
174         /* Copy previous values to str */
175         for (i = 0; i < sizeof(str); ++i) {
176                 if ((ptr[i+key_len] == ' ') || (ptr[i+key_len] == '\0'))
177                         break;
178                 str[i] = ptr[i+key_len];
179         }
180         if (i == sizeof(str))
181                 return E2BIG;
182         old_val_len = i;
183
184         offset = old_val_len+key_len;
185
186         /* Move rest of buf to overwrite previous key and value */
187         for (i = 0; ptr[i+offset] != '\0'; ++i)
188                 ptr[i] = ptr[i+offset];
189
190         ptr[i] = '\0';
191
192         snprintf(str+old_val_len, sizeof(str)-old_val_len, "%c%s", sep, val);
193
194         return add_param(buf, key, str);
195 }
196
197 char *strscat(char *dst, char *src, int buflen)
198 {
199         dst[buflen - 1] = 0;
200         if (strlen(dst) + strlen(src) >= buflen) {
201                 fprintf(stderr, "string buffer overflow (max %d): '%s' + '%s'"
202                         "\n", buflen, dst, src);
203                 exit(EOVERFLOW);
204         }
205         return strcat(dst, src);
206 }
207
208 char *strscpy(char *dst, char *src, int buflen)
209 {
210         dst[0] = 0;
211         return strscat(dst, src, buflen);
212 }
213
214 int check_mtab_entry(char *spec1, char *spec2, char *mtpt, char *type)
215 {
216         FILE *fp;
217         struct mntent *mnt;
218
219         fp = setmntent(MOUNTED, "r");
220         if (fp == NULL)
221                 return 0;
222
223         while ((mnt = getmntent(fp)) != NULL) {
224                 if ((strcmp(mnt->mnt_fsname, spec1) == 0 ||
225                      strcmp(mnt->mnt_fsname, spec2) == 0) &&
226                     (mtpt == NULL || strcmp(mnt->mnt_dir, mtpt) == 0) &&
227                     (type == NULL || strcmp(mnt->mnt_type, type) == 0)) {
228                         endmntent(fp);
229                         return(EEXIST);
230                 }
231         }
232         endmntent(fp);
233
234         return 0;
235 }
236
237 #include <sys/vfs.h>
238 #include <linux/magic.h>
239
240 static int mtab_is_proc(const char *mtab)
241 {
242         struct statfs s;
243         if (statfs(mtab, &s) < 0)
244                 return 0;
245
246         return (s.f_type == PROC_SUPER_MAGIC);
247 }
248
249 #ifdef HAVE_LIBMOUNT
250
251 # include <libmount/libmount.h>
252
253 /*
254  * The libmount is part of util-linux since 2.18.
255  * We use it to update utab to avoid umount would
256  * blocked in some rare case.
257  */
258 int update_utab_entry(struct mount_opts *mop)
259 {
260         struct libmnt_fs *fs = mnt_new_fs();
261         struct libmnt_update *upd;
262         int rc;
263
264         mnt_fs_set_source(fs, mop->mo_source);
265         mnt_fs_set_target(fs, mop->mo_target);
266         mnt_fs_set_fstype(fs, "lustre");
267         mnt_fs_set_attributes(fs, "lustre");
268
269         upd = mnt_new_update();
270         if (!upd)
271                 return -ENOMEM;
272
273         rc = mnt_update_set_fs(upd, mop->mo_nomtab ? MS_REMOUNT : 0, NULL, fs);
274         if (rc == 1) /* update is unnecessary */
275                 rc = 0;
276         if (rc) {
277                 fprintf(stderr,
278                         "error: failed to save utab entry: rc = %d\n", rc);
279         } else {
280                 rc = mnt_update_table(upd, NULL);
281         }
282
283         mnt_free_update(upd);
284         mnt_free_fs(fs);
285
286         return rc;
287 }
288 #else
289 int update_utab_entry(struct mount_opts *mop)
290 {
291         return 0;
292 }
293 #endif /* HAVE_LIBMOUNT */
294
295 int update_mtab_entry(char *spec, char *mtpt, char *type, char *opts,
296                 int flags, int freq, int pass)
297 {
298         FILE *fp;
299         struct mntent mnt;
300         int rc = 0;
301
302         /* Don't update mtab if it is linked to any file in /proc direcotry.*/
303         if (mtab_is_proc(MOUNTED))
304                 return 0;
305
306         mnt.mnt_fsname = spec;
307         mnt.mnt_dir = mtpt;
308         mnt.mnt_type = type;
309         mnt.mnt_opts = opts ? opts : "";
310         mnt.mnt_freq = freq;
311         mnt.mnt_passno = pass;
312
313         fp = setmntent(MOUNTED, "a+");
314         if (fp == NULL) {
315                 fprintf(stderr, "%s: setmntent(%s): %s\n",
316                         progname, MOUNTED, strerror (errno));
317                 rc = 16;
318         } else {
319                 if ((addmntent(fp, &mnt)) == 1) {
320                         fprintf(stderr, "%s: addmntent: %s\n",
321                                 progname, strerror (errno));
322                         rc = 16;
323                 }
324                 endmntent(fp);
325         }
326
327         return rc;
328 }
329
330 /* Search for opt in mntlist, returning true if found.
331  */
332 static int in_mntlist(char *opt, char *mntlist)
333 {
334         char *ml, *mlp, *item, *ctx = NULL;
335
336         if (!(ml = strdup(mntlist))) {
337                 fprintf(stderr, "%s: out of memory\n", progname);
338                 exit(1);
339         }
340         mlp = ml;
341         while ((item = strtok_r(mlp, ",", &ctx))) {
342                 if (!strcmp(opt, item))
343                         break;
344                 mlp = NULL;
345         }
346         free(ml);
347         return (item != NULL);
348 }
349
350 /* Issue a message on stderr for every item in wanted_mountopts that is not
351  * present in mountopts.  The justwarn boolean toggles between error and
352  * warning message.  Return an error count.
353  */
354 int check_mountfsoptions(char *mountopts, char *wanted_mountopts)
355 {
356         char *ml, *mlp, *item, *ctx = NULL;
357         int errors = 0;
358
359         if (!(ml = strdup(wanted_mountopts))) {
360                 fprintf(stderr, "%s: out of memory\n", progname);
361                 exit(1);
362         }
363         mlp = ml;
364         while ((item = strtok_r(mlp, ",", &ctx))) {
365                 if (!in_mntlist(item, mountopts)) {
366                         fprintf(stderr, "%s: Error: mandatory mount option"
367                                 " '%s' is missing\n", progname, item);
368                         errors++;
369                 }
370                 mlp = NULL;
371         }
372         free(ml);
373         return errors;
374 }
375
376 /* Trim embedded white space, leading and trailing commas from string s.
377  */
378 void trim_mountfsoptions(char *s)
379 {
380         char *p;
381
382         for (p = s; *p; ) {
383                 if (isspace(*p)) {
384                         memmove(p, p + 1, strlen(p + 1) + 1);
385                         continue;
386                 }
387                 p++;
388         }
389
390         while (s[0] == ',')
391                 memmove(&s[0], &s[1], strlen(&s[1]) + 1);
392
393         p = s + strlen(s) - 1;
394         while (p >= s && *p == ',')
395                 *p-- = '\0';
396 }
397
398 /* Setup a file in the first unused loop_device */
399 int loop_setup(struct mkfs_opts *mop)
400 {
401         char loop_base[20];
402         char l_device[64];
403         int i, ret = 0;
404
405         /* Figure out the loop device names */
406         if (!access("/dev/loop0", F_OK | R_OK) ||
407             !access("/dev/loop-control", F_OK | R_OK)) {
408                 strcpy(loop_base, "/dev/loop\0");
409         } else if (!access("/dev/loop/0", F_OK | R_OK)) {
410                 strcpy(loop_base, "/dev/loop/\0");
411         } else {
412                 fprintf(stderr, "%s: can't access loop devices\n", progname);
413                 return EACCES;
414         }
415
416         /* Find unused loop device */
417         for (i = 0; i < MAX_LOOP_DEVICES; i++) {
418                 char cmd[PATH_MAX];
419                 int cmdsz = sizeof(cmd);
420
421 #ifdef HAVE_LOOP_CTL_GET_FREE
422                 ret = open("/dev/loop-control", O_RDWR);
423                 if (ret < 0) {
424                         fprintf(stderr, "%s: can't access loop control\n", progname);
425                         return EACCES;
426                 }
427                 /* find or allocate a free loop device to use */
428                 i = ioctl(ret, LOOP_CTL_GET_FREE);
429                 close(ret);
430                 if (i < 0) {
431                         fprintf(stderr, "%s: access loop control error\n", progname);
432                         return EACCES;
433                 }
434                 sprintf(l_device, "%s%d", loop_base, i);
435 #else
436                 sprintf(l_device, "%s%d", loop_base, i);
437                 if (access(l_device, F_OK | R_OK))
438                         break;
439 #endif
440                 snprintf(cmd, cmdsz, "losetup %s > /dev/null 2>&1", l_device);
441                 ret = system(cmd);
442
443                 /* losetup gets 1 (ret=256) for non-set-up device */
444                 if (ret) {
445                         /* Set up a loopback device to our file */
446                         snprintf(cmd, cmdsz, "losetup %s %s", l_device,
447                                  mop->mo_device);
448                         ret = run_command(cmd, cmdsz);
449                         if (ret == 256)
450                                 /* someone else picked up this loop device
451                                  * behind our back */
452                                 continue;
453                         if (ret) {
454                                 fprintf(stderr, "%s: error %d on losetup: %s\n",
455                                         progname, ret,
456                                         ret >= 0 ? strerror(ret) : "");
457                                 return ret;
458                         }
459                         strscpy(mop->mo_loopdev, l_device,
460                                 sizeof(mop->mo_loopdev));
461                         return ret;
462                 }
463         }
464
465         fprintf(stderr, "%s: out of loop devices!\n", progname);
466         return EMFILE;
467 }
468
469 int loop_cleanup(struct mkfs_opts *mop)
470 {
471         char cmd[150];
472         int ret = 0;
473
474         if ((mop->mo_flags & MO_IS_LOOP) && *mop->mo_loopdev) {
475                 int tries;
476
477                 sprintf(cmd, "losetup -d %s", mop->mo_loopdev);
478                 for (tries = 0; tries < 3; tries++) {
479                         ret = run_command(cmd, sizeof(cmd));
480                         if (ret == 0)
481                                 break;
482                         sleep(1);
483                 }
484         }
485
486         if (ret != 0)
487                 fprintf(stderr, "cannot cleanup %s: rc = %d\n",
488                         mop->mo_loopdev, ret);
489         return ret;
490 }
491
492 int loop_format(struct mkfs_opts *mop)
493 {
494         int fd;
495
496         if (mop->mo_device_kb == 0) {
497                 fatal();
498                 fprintf(stderr, "loop device requires a --device-size= "
499                         "param\n");
500                 return EINVAL;
501         }
502
503         fd = creat(mop->mo_device, S_IRUSR|S_IWUSR);
504         if (fd < 0) {
505                 fatal();
506                 fprintf(stderr, "%s: Unable to create backing store: %s\n",
507                         progname, strerror(errno));
508                 return errno;
509         }
510
511         if (ftruncate(fd, mop->mo_device_kb * 1024) != 0) {
512                 close(fd);
513                 fatal();
514                 fprintf(stderr, "%s: Unable to truncate backing store: %s\n",
515                         progname, strerror(errno));
516                 return errno;
517         }
518
519         close(fd);
520         return 0;
521 }
522
523 #ifdef PLUGIN_DIR
524 #define DLSYM(prefix, sym, func)                                        \
525         do {                                                            \
526                 char _fname[64];                                        \
527                 snprintf(_fname, sizeof(_fname), "%s_%s", prefix, #func); \
528                 sym->func = (typeof(sym->func))dlsym(sym->dl_handle, _fname); \
529         } while (0)
530 #endif /* PLUGIN_DIR */
531
532 /**
533  * Load plugin for a given mount_type from ${pkglibdir}/mount_osd_FSTYPE.so and
534  * return struct of function pointers (will be freed in unloack_backfs_module).
535  *
536  * \param[in] mount_type        Mount type to load module for.
537  * \retval Value of backfs_ops struct
538  * \retval NULL if no module exists
539  */
540 struct module_backfs_ops *load_backfs_module(enum ldd_mount_type mount_type)
541 {
542         struct module_backfs_ops *ops;
543 #ifdef PLUGIN_DIR
544         char *error, filename[512], fsname[512], *name;
545         void *handle;
546
547         /* This deals with duplicate ldd_mount_types resolving to same OSD layer
548          * plugin (e.g. ext3/ldiskfs/ldiskfs2 all being ldiskfs) */
549         strncpy(fsname, mt_type(mount_type), sizeof(fsname));
550         name = fsname + sizeof("osd-") - 1;
551
552         /* change osd- to osd_ */
553         fsname[sizeof("osd-") - 2] = '_';
554
555         snprintf(filename, sizeof(filename), PLUGIN_DIR"/mount_%s.so", fsname);
556
557         handle = dlopen(filename, RTLD_LAZY);
558
559         /* Check for $LUSTRE environment variable from test-framework.
560          * This allows using locally built modules to be used.
561          */
562         if (handle == NULL) {
563                 char *dirname;
564                 dirname = getenv("LUSTRE");
565                 if (dirname) {
566                         snprintf(filename, sizeof(filename),
567                                  "%s/utils/.libs/mount_%s.so",
568                                  dirname, fsname);
569                         handle = dlopen(filename, RTLD_LAZY);
570                 }
571         }
572
573         /* Do not clutter up console with missing types */
574         if (handle == NULL)
575                 return NULL;
576
577         ops = malloc(sizeof(*ops));
578         if (ops == NULL) {
579                 dlclose(handle);
580                 return NULL;
581         }
582
583         ops->dl_handle = handle;
584         dlerror(); /* Clear any existing error */
585
586         DLSYM(name, ops, init);
587         DLSYM(name, ops, fini);
588         DLSYM(name, ops, read_ldd);
589         DLSYM(name, ops, write_ldd);
590         DLSYM(name, ops, erase_ldd);
591         DLSYM(name, ops, print_ldd_params);
592         DLSYM(name, ops, is_lustre);
593         DLSYM(name, ops, make_lustre);
594         DLSYM(name, ops, prepare_lustre);
595         DLSYM(name, ops, tune_lustre);
596         DLSYM(name, ops, label_lustre);
597         DLSYM(name, ops, rename_fsname);
598         DLSYM(name, ops, enable_quota);
599
600         error = dlerror();
601         if (error != NULL) {
602                 fatal();
603                 fprintf(stderr, "%s\n", error);
604                 dlclose(handle);
605                 free(ops);
606                 return NULL;
607         }
608
609         /* optional methods */
610         DLSYM(name, ops, fix_mountopts);
611 #else
612         switch (mount_type) {
613 #ifdef HAVE_LDISKFS_OSD
614         case LDD_MT_LDISKFS:
615                 ops = &ldiskfs_ops;
616                 break;
617 #endif /* HAVE_LDISKFS_OSD */
618 #ifdef HAVE_ZFS_OSD
619         case LDD_MT_ZFS:
620                 ops = &zfs_ops;
621                 break;
622 #endif /* HAVE_ZFS_OSD */
623         default:
624                 ops = NULL;
625                 break;
626         }
627 #endif
628         return ops;
629 }
630
631 /**
632  * Unload plugin and free backfs_ops structure. Must be called the same number
633  * of times as load_backfs_module is.
634  */
635 void unload_backfs_module(struct module_backfs_ops *ops)
636 {
637 #ifdef PLUGIN_DIR
638         if (ops == NULL)
639                 return;
640
641         dlclose(ops->dl_handle);
642         free(ops);
643 #endif
644 }
645
646 /* Return true if backfs_ops has operations for the given mount_type. */
647 int backfs_mount_type_okay(enum ldd_mount_type mount_type)
648 {
649         if (mount_type >= LDD_MT_LAST || mount_type < 0) {
650                 fatal();
651                 fprintf(stderr, "fs type out of range %d\n", mount_type);
652                 return 0;
653         }
654         if (backfs_ops[mount_type] == NULL) {
655                 fatal();
656                 fprintf(stderr, "unhandled/unloaded fs type %d '%s'\n",
657                         mount_type, mt_str(mount_type));
658                 return 0;
659         }
660         return 1;
661 }
662
663 /* Write the server config files */
664 int osd_write_ldd(struct mkfs_opts *mop)
665 {
666         struct lustre_disk_data *ldd = &mop->mo_ldd;
667         int ret;
668
669         if (backfs_mount_type_okay(ldd->ldd_mount_type))
670                 ret = backfs_ops[ldd->ldd_mount_type]->write_ldd(mop);
671         else
672                 ret = EINVAL;
673
674         return ret;
675 }
676
677 /* Read the server config files */
678 int osd_read_ldd(char *dev, struct lustre_disk_data *ldd)
679 {
680         int ret;
681
682         if (backfs_mount_type_okay(ldd->ldd_mount_type))
683                 ret = backfs_ops[ldd->ldd_mount_type]->read_ldd(dev, ldd);
684         else
685                 ret = EINVAL;
686
687         return ret;
688 }
689
690 /* Erase param from the server config files */
691 int osd_erase_ldd(struct mkfs_opts *mop, char *param)
692 {
693         struct lustre_disk_data *ldd = &mop->mo_ldd;
694         int ret;
695
696         if (backfs_mount_type_okay(ldd->ldd_mount_type))
697                 ret = backfs_ops[ldd->ldd_mount_type]->erase_ldd(mop, param);
698         else
699                 ret = EINVAL;
700
701         return ret;
702 }
703
704 /* Print ldd_params */
705 void osd_print_ldd_params(struct mkfs_opts *mop)
706 {
707         struct lustre_disk_data *ldd = &mop->mo_ldd;
708
709         if (backfs_mount_type_okay(ldd->ldd_mount_type))
710                 backfs_ops[ldd->ldd_mount_type]->print_ldd_params(mop);
711 }
712
713 /* Was this device formatted for Lustre */
714 int osd_is_lustre(char *dev, unsigned *mount_type)
715 {
716         int i;
717
718         vprint("checking for existing Lustre data: ");
719
720         for (i = 0; i < LDD_MT_LAST; ++i) {
721                 if (backfs_ops[i] != NULL &&
722                     backfs_ops[i]->is_lustre(dev, mount_type)) {
723                         vprint("found\n");
724                         return 1;
725                 }
726         }
727
728         vprint("not found\n");
729         return 0;
730 }
731
732 /* Build fs according to type */
733 int osd_make_lustre(struct mkfs_opts *mop)
734 {
735         struct lustre_disk_data *ldd = &mop->mo_ldd;
736         int ret;
737
738         if (backfs_mount_type_okay(ldd->ldd_mount_type))
739                 ret = backfs_ops[ldd->ldd_mount_type]->make_lustre(mop);
740         else
741                 ret = EINVAL;
742
743         return ret;
744 }
745
746 int osd_prepare_lustre(struct mkfs_opts *mop,
747                        char *wanted_mountopts, size_t len)
748 {
749         struct lustre_disk_data *ldd = &mop->mo_ldd;
750         int ret;
751
752         if (backfs_mount_type_okay(ldd->ldd_mount_type))
753                 ret = backfs_ops[ldd->ldd_mount_type]->prepare_lustre(mop,
754                                                         wanted_mountopts, len);
755         else
756                 ret = EINVAL;
757
758         return ret;
759 }
760
761 int osd_fix_mountopts(struct mkfs_opts *mop, char *mountopts, size_t len)
762 {
763         struct lustre_disk_data *ldd = &mop->mo_ldd;
764
765         if (!backfs_mount_type_okay(ldd->ldd_mount_type))
766                 return EINVAL;
767
768         if (backfs_ops[ldd->ldd_mount_type]->fix_mountopts == NULL)
769                 return 0;
770
771         return backfs_ops[ldd->ldd_mount_type]->fix_mountopts(mop, mountopts,
772                                                               len);
773 }
774
775 int osd_tune_lustre(char *dev, struct mount_opts *mop)
776 {
777         struct lustre_disk_data *ldd = &mop->mo_ldd;
778         int ret;
779
780         if (backfs_mount_type_okay(ldd->ldd_mount_type))
781                 ret = backfs_ops[ldd->ldd_mount_type]->tune_lustre(dev, mop);
782         else
783                 ret = EINVAL;
784
785         return ret;
786 }
787
788 int osd_label_lustre(struct mount_opts *mop)
789 {
790         struct lustre_disk_data *ldd = &mop->mo_ldd;
791         int ret;
792
793         if (backfs_mount_type_okay(ldd->ldd_mount_type))
794                 ret = backfs_ops[ldd->ldd_mount_type]->label_lustre(mop);
795         else
796                 ret = EINVAL;
797
798         return ret;
799 }
800
801 /* Rename filesystem fsname */
802 int osd_rename_fsname(struct mkfs_opts *mop, const char *oldname)
803 {
804         struct lustre_disk_data *ldd = &mop->mo_ldd;
805         int ret;
806
807         if (backfs_mount_type_okay(ldd->ldd_mount_type))
808                 ret = backfs_ops[ldd->ldd_mount_type]->rename_fsname(mop,
809                                                                      oldname);
810         else
811                 ret = EINVAL;
812
813         return ret;
814 }
815
816 /* Enable quota accounting */
817 int osd_enable_quota(struct mkfs_opts *mop)
818 {
819         struct lustre_disk_data *ldd = &mop->mo_ldd;
820         int ret;
821
822         if (backfs_mount_type_okay(ldd->ldd_mount_type))
823                 ret = backfs_ops[ldd->ldd_mount_type]->enable_quota(mop);
824         else
825                 ret = EINVAL;
826
827         return ret;
828 }
829
830 int osd_init(void)
831 {
832         int i, rc, ret = EINVAL;
833
834         for (i = 0; i < LDD_MT_LAST; ++i) {
835                 rc = 0;
836                 backfs_ops[i] = load_backfs_module(i);
837                 if (backfs_ops[i] != NULL) {
838                         rc = backfs_ops[i]->init();
839                         if (rc != 0) {
840                                 backfs_ops[i]->fini();
841                                 unload_backfs_module(backfs_ops[i]);
842                                 backfs_ops[i] = NULL;
843                         } else
844                                 ret = 0;
845                 }
846         }
847
848         return ret;
849 }
850
851 void osd_fini(void)
852 {
853         int i;
854
855         for (i = 0; i < LDD_MT_LAST; ++i) {
856                 if (backfs_ops[i] != NULL) {
857                         backfs_ops[i]->fini();
858                         unload_backfs_module(backfs_ops[i]);
859                         backfs_ops[i] = NULL;
860                 }
861         }
862 }
863
864 __u64 get_device_size(char* device)
865 {
866         int ret, fd;
867         __u64 size = 0;
868
869         fd = open(device, O_RDONLY);
870         if (fd < 0) {
871                 fprintf(stderr, "%s: cannot open %s: %s\n",
872                         progname, device, strerror(errno));
873                 return 0;
874         }
875
876 #ifdef BLKGETSIZE64
877         /* size in bytes. bz5831 */
878         ret = ioctl(fd, BLKGETSIZE64, (void*)&size);
879 #else
880         {
881                 __u32 lsize = 0;
882                 /* size in blocks */
883                 ret = ioctl(fd, BLKGETSIZE, (void*)&lsize);
884                 size = (__u64)lsize * 512;
885         }
886 #endif
887         close(fd);
888         if (ret < 0) {
889                 fprintf(stderr, "%s: size ioctl failed: %s\n",
890                         progname, strerror(errno));
891                 return 0;
892         }
893
894         vprint("device size = %juMB\n", (uintmax_t)(size >> 20));
895         /* return value in KB */
896         return size >> 10;
897 }
898
899 int file_create(char *path, __u64 size)
900 {
901         __u64 size_max;
902         int ret;
903         int fd;
904
905         /*
906          * Since "size" is in KB, the file offset it represents could overflow
907          * off_t.
908          */
909         size_max = (off_t)1 << (_FILE_OFFSET_BITS - 1 - 10);
910         if (size >= size_max) {
911                 fprintf(stderr, "%s: %ju KB: Backing store size must be "
912                         "smaller than %ju KB\n", progname, (uintmax_t) size,
913                         (uintmax_t)size_max);
914                 return EFBIG;
915         }
916
917         ret = access(path, F_OK);
918         if (ret == 0) {
919                 ret = unlink(path);
920                 if (ret != 0)
921                         return errno;
922         }
923
924         fd = creat(path, S_IRUSR|S_IWUSR);
925         if (fd < 0) {
926                 fatal();
927                 fprintf(stderr, "%s: Unable to create backing store: %s\n",
928                         progname, strerror(errno));
929                 return errno;
930         }
931
932         ret = ftruncate(fd, size * 1024);
933         close(fd);
934         if (ret != 0) {
935                 fatal();
936                 fprintf(stderr, "%s: Unable to truncate backing store: %s\n",
937                         progname, strerror(errno));
938                 return errno;
939         }
940
941         return 0;
942 }
943
944
945 struct lustre_cfg_entry {
946         struct list_head lce_list;
947         char             lce_name[0];
948 };
949
950 static struct lustre_cfg_entry *lustre_cfg_entry_init(const char *name)
951 {
952         struct lustre_cfg_entry *lce;
953         int len = strlen(name) + 1;
954
955         lce = malloc(sizeof(*lce) + len);
956         if (lce) {
957                 INIT_LIST_HEAD(&lce->lce_list);
958                 memcpy(lce->lce_name, name, len);
959         }
960
961         return lce;
962 }
963
964 static void lustre_cfg_entry_fini(struct lustre_cfg_entry *lce)
965 {
966         free(lce);
967 }
968
969 int lustre_rename_fsname(struct mkfs_opts *mop, const char *mntpt,
970                          const char *oldname)
971 {
972         struct lustre_disk_data *ldd = &mop->mo_ldd;
973         struct lr_server_data lsd;
974         char filepnm[128];
975         char cfg_dir[128];
976         DIR *dir = NULL;
977         struct dirent64 *dirent;
978         struct lustre_cfg_entry *lce;
979         struct list_head cfg_list;
980         int old_namelen = strlen(oldname);
981         int new_namelen = strlen(ldd->ldd_fsname);
982         int ret;
983         int fd;
984
985         INIT_LIST_HEAD(&cfg_list);
986
987         snprintf(filepnm, sizeof(filepnm), "%s/%s", mntpt, LAST_RCVD);
988         fd = open(filepnm, O_RDWR);
989         if (fd < 0) {
990                 if (errno == ENOENT)
991                         goto config;
992
993                 if (errno != 0)
994                         ret = errno;
995                 else
996                         ret = fd;
997                 fprintf(stderr, "Unable to open %s: %s\n",
998                         filepnm, strerror(ret));
999                 return ret;
1000         }
1001
1002         ret = read(fd, &lsd, sizeof(lsd));
1003         if (ret != sizeof(lsd)) {
1004                 if (errno != 0)
1005                         ret = errno;
1006                 fprintf(stderr, "Unable to read %s: %s\n",
1007                         filepnm, strerror(ret));
1008                 close(fd);
1009                 return ret;
1010         }
1011
1012         ret = lseek(fd, 0, SEEK_SET);
1013         if (ret) {
1014                 if (errno != 0)
1015                         ret = errno;
1016                 fprintf(stderr, "Unable to lseek %s: %s\n",
1017                         filepnm, strerror(ret));
1018                 close(fd);
1019                 return ret;
1020         }
1021
1022         /* replace fsname in lr_server_data::lsd_uuid. */
1023         if (old_namelen > new_namelen)
1024                 memmove(lsd.lsd_uuid + new_namelen,
1025                         lsd.lsd_uuid + old_namelen,
1026                         sizeof(lsd.lsd_uuid) - old_namelen);
1027         else if (old_namelen < new_namelen)
1028                 memmove(lsd.lsd_uuid + new_namelen,
1029                         lsd.lsd_uuid + old_namelen,
1030                         sizeof(lsd.lsd_uuid) - new_namelen);
1031         memcpy(lsd.lsd_uuid, ldd->ldd_fsname, new_namelen);
1032         ret = write(fd, &lsd, sizeof(lsd));
1033         if (ret != sizeof(lsd)) {
1034                 if (errno != 0)
1035                         ret = errno;
1036                 fprintf(stderr, "Unable to write %s: %s\n",
1037                         filepnm, strerror(ret));
1038                 close(fd);
1039                 return ret;
1040         }
1041
1042         close(fd);
1043
1044 config:
1045         snprintf(cfg_dir, sizeof(cfg_dir), "%s/%s", mntpt, MOUNT_CONFIGS_DIR);
1046         dir = opendir(cfg_dir);
1047         if (!dir) {
1048                 if (errno != 0)
1049                         ret = errno;
1050                 else
1051                         ret = EINVAL;
1052                 fprintf(stderr, "Unable to opendir %s: %s\n",
1053                         cfg_dir, strerror(ret));
1054                 return ret;
1055         }
1056
1057         while ((dirent = readdir64(dir)) != NULL) {
1058                 char *ptr;
1059
1060                 if (strlen(dirent->d_name) <= old_namelen)
1061                         continue;
1062
1063                 ptr = strrchr(dirent->d_name, '-');
1064                 if (!ptr || (ptr - dirent->d_name) != old_namelen)
1065                         continue;
1066
1067                 if (strncmp(dirent->d_name, oldname, old_namelen) != 0)
1068                         continue;
1069
1070                 lce = lustre_cfg_entry_init(dirent->d_name);
1071                 if (!lce) {
1072                         if (errno != 0)
1073                                 ret = errno;
1074                         else
1075                                 ret = EINVAL;
1076
1077                         fprintf(stderr, "Fail to init item for %s: %s\n",
1078                                 dirent->d_name, strerror(ret));
1079                         goto out;
1080                 }
1081
1082                 list_add(&lce->lce_list, &cfg_list);
1083         }
1084
1085         closedir(dir);
1086         dir = NULL;
1087         ret = 0;
1088
1089         while (!list_empty(&cfg_list) && ret == 0) {
1090                 lce = list_entry(cfg_list.next, struct lustre_cfg_entry,
1091                                  lce_list);
1092                 list_del(&lce->lce_list);
1093                 snprintf(filepnm, sizeof(filepnm), "%s/%s", cfg_dir,
1094                          lce->lce_name);
1095                 if (IS_MGS(ldd))
1096                         /* Store the new fsname in the XATTR_TARGET_RENAME EA.
1097                          * When the MGS start, it will scan config logs, and
1098                          * for the ones which have the XATTR_TARGET_RENAME EA,
1099                          * it will replace old fsname with the new fsname in
1100                          * the config log by some shared kernel level config
1101                          * logs {fork,erase} functionalities automatically. */
1102                         ret = setxattr(filepnm, XATTR_TARGET_RENAME,
1103                                        ldd->ldd_fsname,
1104                                        strlen(ldd->ldd_fsname), 0);
1105                 else
1106                         ret = unlink(filepnm);
1107
1108                 if (ret) {
1109                         if (errno != 0)
1110                                 ret = errno;
1111
1112                         fprintf(stderr, "Fail to %s %s: %s\n",
1113                                 IS_MGS(ldd) ? "setxattr" : "unlink",
1114                                 filepnm, strerror(ret));
1115                 }
1116
1117                 lustre_cfg_entry_fini(lce);
1118         }
1119
1120 out:
1121         if (dir)
1122                 closedir(dir);
1123
1124         while (!list_empty(&cfg_list)) {
1125                 lce = list_entry(cfg_list.next, struct lustre_cfg_entry,
1126                                  lce_list);
1127                 list_del(&lce->lce_list);
1128                 lustre_cfg_entry_fini(lce);
1129         }
1130
1131         return ret;
1132 }
1133
1134 #ifdef HAVE_GSS
1135 #ifdef HAVE_OPENSSL_SSK
1136 int load_shared_keys(struct mount_opts *mop)
1137 {
1138         DIR *dir;
1139         struct dirent *dentry;
1140         struct stat sbuf;
1141         char fullpath[PATH_MAX];
1142         char *path = mop->mo_skpath;
1143         int rc;
1144
1145         /* init logging */
1146         sk_init_logging(NULL, 1, 1);
1147
1148         rc = stat(path, &sbuf);
1149         if (rc < 0) {
1150                 fprintf(stderr, "stat() failed for key %s: %s\n", path,
1151                         strerror(errno));
1152                 return -errno;
1153         }
1154
1155         /* Load individual keys or a directory of them */
1156         if (S_ISREG(sbuf.st_mode)) {
1157                 return sk_load_keyfile(path);
1158         } else if (!S_ISDIR(sbuf.st_mode)) {
1159                 fprintf(stderr, "Invalid shared key path: %s\n", path);
1160                 return -ENOKEY;
1161         }
1162
1163         dir = opendir(path);
1164         if (dir == NULL) {
1165                 fprintf(stderr, "Unable to open shared key directory: %s\n",
1166                         path);
1167                 return -ENOENT;
1168         }
1169
1170         /* Loop through the files in the directory attempting to load them.
1171          * Any issue with loading the keyfile is treated as an error although
1172          * the loop continues until all files have been attempted.  This will
1173          * allow all errors be reported at once rather then requiring
1174          * incremental corrections to fix each one and try again. */
1175         while ((dentry = readdir(dir)) != NULL) {
1176                 if (strcmp(".", dentry->d_name) == 0 ||
1177                     strcmp("..", dentry->d_name) == 0)
1178                         continue;
1179
1180                 rc = snprintf(fullpath, PATH_MAX, "%s/%s", path,
1181                               dentry->d_name);
1182                 if (rc >= PATH_MAX) {
1183                         fprintf(stderr, "Path too long for %s/%s\n",
1184                                 path, dentry->d_name);
1185                         rc = -ENAMETOOLONG;
1186                         continue;
1187                 }
1188
1189                 rc = stat(fullpath, &sbuf);
1190                 if (rc < 0) {
1191                         fprintf(stderr, "Unable to stat %s: %s\n", fullpath,
1192                                 strerror(errno));
1193                         rc = -errno;
1194                         continue;
1195                 }
1196
1197                 if (!S_ISREG(sbuf.st_mode))
1198                         continue;
1199
1200                 rc = sk_load_keyfile(fullpath);
1201                 if (rc) {
1202                         fprintf(stderr, "Failed to load key %s\n", fullpath);
1203                 }
1204         }
1205         closedir(dir);
1206
1207         return rc;
1208 }
1209 #endif /* HAVE_OPENSSL_SSK */
1210 #endif /* HAVE_GSS */