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