]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/mdmfs/mdmfs.c
MFC r344218: mdmfs(8): use -o reserve with malloc-backed md(4)
[FreeBSD/FreeBSD.git] / sbin / mdmfs / mdmfs.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2001 Dima Dorfman.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 /*
30  * mdmfs (md/MFS) is a wrapper around mdconfig(8),
31  * newfs(8), and mount(8) that mimics the command line option set of
32  * the deprecated mount_mfs(8).
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/linker.h>
40 #include <sys/mdioctl.h>
41 #include <sys/module.h>
42 #include <sys/mount.h>
43 #include <sys/stat.h>
44 #include <sys/wait.h>
45
46 #include <assert.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <grp.h>
51 #include <inttypes.h>
52 #include <paths.h>
53 #include <pwd.h>
54 #include <stdarg.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <ctype.h>
59 #include <unistd.h>
60
61 typedef enum { false, true } bool;
62
63 struct mtpt_info {
64         uid_t            mi_uid;
65         bool             mi_have_uid;
66         gid_t            mi_gid;
67         bool             mi_have_gid;
68         mode_t           mi_mode;
69         bool             mi_have_mode;
70         bool             mi_forced_pw;
71 };
72
73 static  bool debug;             /* Emit debugging information? */
74 static  bool loudsubs;          /* Suppress output from helper programs? */
75 static  bool norun;             /* Actually run the helper programs? */
76 static  int unit;               /* The unit we're working with. */
77 static  const char *mdname;     /* Name of memory disk device (e.g., "md"). */
78 static  const char *mdsuffix;   /* Suffix of memory disk device (e.g., ".uzip"). */
79 static  size_t mdnamelen;       /* Length of mdname. */
80 static  const char *path_mdconfig =_PATH_MDCONFIG;
81
82 static void      argappend(char **, const char *, ...) __printflike(2, 3);
83 static void      debugprintf(const char *, ...) __printflike(1, 2);
84 static void      do_mdconfig_attach(const char *, const enum md_types);
85 static void      do_mdconfig_attach_au(const char *, const enum md_types);
86 static void      do_mdconfig_detach(void);
87 static void      do_mount_md(const char *, const char *);
88 static void      do_mount_tmpfs(const char *, const char *);
89 static void      do_mtptsetup(const char *, struct mtpt_info *);
90 static void      do_newfs(const char *);
91 static void      extract_ugid(const char *, struct mtpt_info *);
92 static int       run(int *, const char *, ...) __printflike(2, 3);
93 static void      usage(void);
94
95 int
96 main(int argc, char **argv)
97 {
98         struct mtpt_info mi;            /* Mountpoint info. */
99         intmax_t mdsize;
100         char *mdconfig_arg, *newfs_arg, /* Args to helper programs. */
101             *mount_arg;
102         enum md_types mdtype;           /* The type of our memory disk. */
103         bool have_mdtype, mlmac;
104         bool detach, softdep, autounit, newfs;
105         const char *mtpoint, *size_arg, *unitstr;
106         char *p;
107         int ch, idx;
108         void *set;
109         unsigned long ul;
110
111         /* Misc. initialization. */
112         (void)memset(&mi, '\0', sizeof(mi));
113         detach = true;
114         softdep = true;
115         autounit = false;
116         mlmac = false;
117         newfs = true;
118         have_mdtype = false;
119         mdtype = MD_SWAP;
120         mdname = MD_NAME;
121         mdnamelen = strlen(mdname);
122         mdsize = 0;
123         /*
124          * Can't set these to NULL.  They may be passed to the
125          * respective programs without modification.  I.e., we may not
126          * receive any command-line options which will caused them to
127          * be modified.
128          */
129         mdconfig_arg = strdup("");
130         newfs_arg = strdup("");
131         mount_arg = strdup("");
132         size_arg = NULL;
133
134         /* If we were started as mount_mfs or mfs, imply -C. */
135         if (strcmp(getprogname(), "mount_mfs") == 0 ||
136             strcmp(getprogname(), "mfs") == 0) {
137                 /* Make compatibility assumptions. */
138                 mi.mi_mode = 01777;
139                 mi.mi_have_mode = true;
140         }
141
142         while ((ch = getopt(argc, argv,
143             "a:b:Cc:Dd:E:e:F:f:hi:LlMm:NnO:o:Pp:Ss:tT:Uv:w:X")) != -1)
144                 switch (ch) {
145                 case 'a':
146                         argappend(&newfs_arg, "-a %s", optarg);
147                         break;
148                 case 'b':
149                         argappend(&newfs_arg, "-b %s", optarg);
150                         break;
151                 case 'C':
152                         /* Ignored for compatibility. */
153                         break;
154                 case 'c':
155                         argappend(&newfs_arg, "-c %s", optarg);
156                         break;
157                 case 'D':
158                         detach = false;
159                         break;
160                 case 'd':
161                         argappend(&newfs_arg, "-d %s", optarg);
162                         break;
163                 case 'E':
164                         path_mdconfig = optarg;
165                         break;
166                 case 'e':
167                         argappend(&newfs_arg, "-e %s", optarg);
168                         break;
169                 case 'F':
170                         if (have_mdtype)
171                                 usage();
172                         mdtype = MD_VNODE;
173                         have_mdtype = true;
174                         argappend(&mdconfig_arg, "-f %s", optarg);
175                         break;
176                 case 'f':
177                         argappend(&newfs_arg, "-f %s", optarg);
178                         break;
179                 case 'h':
180                         usage();
181                         break;
182                 case 'i':
183                         argappend(&newfs_arg, "-i %s", optarg);
184                         break;
185                 case 'L':
186                         loudsubs = true;
187                         break;
188                 case 'l':
189                         mlmac = true;
190                         argappend(&newfs_arg, "-l");
191                         break;
192                 case 'M':
193                         if (have_mdtype)
194                                 usage();
195                         mdtype = MD_MALLOC;
196                         have_mdtype = true;
197                         argappend(&mdconfig_arg, "-o reserve");
198                         break;
199                 case 'm':
200                         argappend(&newfs_arg, "-m %s", optarg);
201                         break;
202                 case 'N':
203                         norun = true;
204                         break;
205                 case 'n':
206                         argappend(&newfs_arg, "-n");
207                         break;
208                 case 'O':
209                         argappend(&newfs_arg, "-o %s", optarg);
210                         break;
211                 case 'o':
212                         argappend(&mount_arg, "-o %s", optarg);
213                         break;
214                 case 'P':
215                         newfs = false;
216                         break;
217                 case 'p':
218                         if ((set = setmode(optarg)) == NULL)
219                                 usage();
220                         mi.mi_mode = getmode(set, S_IRWXU | S_IRWXG | S_IRWXO);
221                         mi.mi_have_mode = true;
222                         mi.mi_forced_pw = true;
223                         free(set);
224                         break;
225                 case 'S':
226                         softdep = false;
227                         break;
228                 case 's':
229                         size_arg = optarg;
230                         break;
231                 case 't':
232                         argappend(&newfs_arg, "-t");
233                         break;
234                 case 'T':
235                         argappend(&mount_arg, "-t %s", optarg);
236                         break;
237                 case 'U':
238                         softdep = true;
239                         break;
240                 case 'v':
241                         argappend(&newfs_arg, "-O %s", optarg);
242                         break;
243                 case 'w':
244                         extract_ugid(optarg, &mi);
245                         mi.mi_forced_pw = true;
246                         break;
247                 case 'X':
248                         debug = true;
249                         break;
250                 default:
251                         usage();
252                 }
253         argc -= optind;
254         argv += optind;
255         if (argc < 2)
256                 usage();
257
258         /*
259          * Historically our size arg was passed directly to mdconfig, which
260          * treats a number without a suffix as a count of 512-byte sectors;
261          * tmpfs would treat it as a count of bytes.  To get predictable
262          * behavior for 'auto' we document that the size always uses mdconfig
263          * rules.  To make that work, decode the size here so it can be passed
264          * to either tmpfs or mdconfig as a count of bytes.
265          */
266         if (size_arg != NULL) {
267                 mdsize = (intmax_t)strtoumax(size_arg, &p, 0);
268                 if (p == size_arg || (p[0] != 0 && p[1] != 0) || mdsize < 0)
269                         errx(1, "invalid size '%s'", size_arg);
270                 switch (*p) {
271                 case 'p':
272                 case 'P':
273                         mdsize *= 1024;
274                 case 't':
275                 case 'T':
276                         mdsize *= 1024;
277                 case 'g':
278                 case 'G':
279                         mdsize *= 1024;
280                 case 'm':
281                 case 'M':
282                         mdsize *= 1024;
283                 case 'k':
284                 case 'K':
285                         mdsize *= 1024;
286                 case 'b':
287                 case 'B':
288                         break;
289                 case '\0':
290                         mdsize *= 512;
291                         break;
292                 default:
293                         errx(1, "invalid size suffix on '%s'", size_arg);
294                 }
295         }
296
297         /*
298          * Based on the command line 'md-device' either mount a tmpfs filesystem
299          * or configure the md device then format and mount a filesystem on it.
300          * If the device is 'auto' use tmpfs if it is available and there is no
301          * request for multilabel MAC (which tmpfs does not support).
302          */
303         unitstr = argv[0];
304         mtpoint = argv[1];
305
306         if (strcmp(unitstr, "auto") == 0) {
307                 if (mlmac)
308                         idx = -1; /* Must use md for mlmac. */
309                 else if ((idx = modfind("tmpfs")) == -1)
310                         idx = kldload("tmpfs");
311                 if (idx == -1)
312                         unitstr = "md";
313                 else
314                         unitstr = "tmpfs";
315         }
316
317         if (strcmp(unitstr, "tmpfs") == 0) {
318                 if (size_arg != NULL && mdsize != 0)
319                         argappend(&mount_arg, "-o size=%jd", mdsize);
320                 do_mount_tmpfs(mount_arg, mtpoint); 
321         } else {
322                 if (size_arg != NULL)
323                         argappend(&mdconfig_arg, "-s %jdB", mdsize);
324                 if (strncmp(unitstr, "/dev/", 5) == 0)
325                         unitstr += 5;
326                 if (strncmp(unitstr, mdname, mdnamelen) == 0)
327                         unitstr += mdnamelen;
328                 if (!isdigit(*unitstr)) {
329                         autounit = true;
330                         unit = -1;
331                         mdsuffix = unitstr;
332                 } else {
333                         ul = strtoul(unitstr, &p, 10);
334                         if (ul == ULONG_MAX)
335                                 errx(1, "bad device unit: %s", unitstr);
336                         unit = ul;
337                         mdsuffix = p;   /* can be empty */
338                 }
339         
340                 if (!have_mdtype)
341                         mdtype = MD_SWAP;
342                 if (softdep)
343                         argappend(&newfs_arg, "-U");
344                 if (mdtype != MD_VNODE && !newfs)
345                         errx(1, "-P requires a vnode-backed disk");
346         
347                 /* Do the work. */
348                 if (detach && !autounit)
349                         do_mdconfig_detach();
350                 if (autounit)
351                         do_mdconfig_attach_au(mdconfig_arg, mdtype);
352                 else
353                         do_mdconfig_attach(mdconfig_arg, mdtype);
354                 if (newfs)
355                         do_newfs(newfs_arg);
356                 do_mount_md(mount_arg, mtpoint);
357         }
358
359         do_mtptsetup(mtpoint, &mi);
360
361         return (0);
362 }
363
364 /*
365  * Append the expansion of 'fmt' to the buffer pointed to by '*dstp';
366  * reallocate as required.
367  */
368 static void
369 argappend(char **dstp, const char *fmt, ...)
370 {
371         char *old, *new;
372         va_list ap;
373
374         old = *dstp;
375         assert(old != NULL);
376
377         va_start(ap, fmt);
378         if (vasprintf(&new, fmt,ap) == -1)
379                 errx(1, "vasprintf");
380         va_end(ap);
381
382         *dstp = new;
383         if (asprintf(&new, "%s %s", old, new) == -1)
384                 errx(1, "asprintf");
385         free(*dstp);
386         free(old);
387
388         *dstp = new;
389 }
390
391 /*
392  * If run-time debugging is enabled, print the expansion of 'fmt'.
393  * Otherwise, do nothing.
394  */
395 static void
396 debugprintf(const char *fmt, ...)
397 {
398         va_list ap;
399
400         if (!debug)
401                 return;
402         fprintf(stderr, "DEBUG: ");
403         va_start(ap, fmt);
404         vfprintf(stderr, fmt, ap);
405         va_end(ap);
406         fprintf(stderr, "\n");
407         fflush(stderr);
408 }
409
410 /*
411  * Attach a memory disk with a known unit.
412  */
413 static void
414 do_mdconfig_attach(const char *args, const enum md_types mdtype)
415 {
416         int rv;
417         const char *ta;         /* Type arg. */
418
419         switch (mdtype) {
420         case MD_SWAP:
421                 ta = "-t swap";
422                 break;
423         case MD_VNODE:
424                 ta = "-t vnode";
425                 break;
426         case MD_MALLOC:
427                 ta = "-t malloc";
428                 break;
429         default:
430                 abort();
431         }
432         rv = run(NULL, "%s -a %s%s -u %s%d", path_mdconfig, ta, args,
433             mdname, unit);
434         if (rv)
435                 errx(1, "mdconfig (attach) exited with error code %d", rv);
436 }
437
438 /*
439  * Attach a memory disk with an unknown unit; use autounit.
440  */
441 static void
442 do_mdconfig_attach_au(const char *args, const enum md_types mdtype)
443 {
444         const char *ta;         /* Type arg. */
445         char *linep;
446         char linebuf[12];       /* 32-bit unit (10) + '\n' (1) + '\0' (1) */
447         int fd;                 /* Standard output of mdconfig invocation. */
448         FILE *sfd;
449         int rv;
450         char *p;
451         size_t linelen;
452         unsigned long ul;
453
454         switch (mdtype) {
455         case MD_SWAP:
456                 ta = "-t swap";
457                 break;
458         case MD_VNODE:
459                 ta = "-t vnode";
460                 break;
461         case MD_MALLOC:
462                 ta = "-t malloc";
463                 break;
464         default:
465                 abort();
466         }
467         rv = run(&fd, "%s -a %s%s", path_mdconfig, ta, args);
468         if (rv)
469                 errx(1, "mdconfig (attach) exited with error code %d", rv);
470
471         /* Receive the unit number. */
472         if (norun) {    /* Since we didn't run, we can't read.  Fake it. */
473                 unit = 0;
474                 return;
475         }
476         sfd = fdopen(fd, "r");
477         if (sfd == NULL)
478                 err(1, "fdopen");
479         linep = fgetln(sfd, &linelen);
480         /* If the output format changes, we want to know about it. */
481         if (linep == NULL || linelen <= mdnamelen + 1 ||
482             linelen - mdnamelen >= sizeof(linebuf) ||
483             strncmp(linep, mdname, mdnamelen) != 0)
484                 errx(1, "unexpected output from mdconfig (attach)");
485         linep += mdnamelen;
486         linelen -= mdnamelen;
487         /* Can't use strlcpy because linep is not NULL-terminated. */
488         strncpy(linebuf, linep, linelen);
489         linebuf[linelen] = '\0';
490         ul = strtoul(linebuf, &p, 10);
491         if (ul == ULONG_MAX || *p != '\n')
492                 errx(1, "unexpected output from mdconfig (attach)");
493         unit = ul;
494
495         fclose(sfd);
496 }
497
498 /*
499  * Detach a memory disk.
500  */
501 static void
502 do_mdconfig_detach(void)
503 {
504         int rv;
505
506         rv = run(NULL, "%s -d -u %s%d", path_mdconfig, mdname, unit);
507         if (rv && debug)        /* This is allowed to fail. */
508                 warnx("mdconfig (detach) exited with error code %d (ignored)",
509                     rv);
510 }
511
512 /*
513  * Mount the configured memory disk.
514  */
515 static void
516 do_mount_md(const char *args, const char *mtpoint)
517 {
518         int rv;
519
520         rv = run(NULL, "%s%s /dev/%s%d%s %s", _PATH_MOUNT, args,
521             mdname, unit, mdsuffix, mtpoint);
522         if (rv)
523                 errx(1, "mount exited with error code %d", rv);
524 }
525
526 /*
527  * Mount the configured tmpfs.
528  */
529 static void
530 do_mount_tmpfs(const char *args, const char *mtpoint)
531 {
532         int rv;
533
534         rv = run(NULL, "%s -t tmpfs %s tmp %s", _PATH_MOUNT, args, mtpoint);
535         if (rv)
536                 errx(1, "tmpfs mount exited with error code %d", rv);
537 }
538
539 /*
540  * Various configuration of the mountpoint.  Mostly, enact 'mip'.
541  */
542 static void
543 do_mtptsetup(const char *mtpoint, struct mtpt_info *mip)
544 {
545         struct statfs sfs;
546
547         if (!mip->mi_have_mode && !mip->mi_have_uid && !mip->mi_have_gid)
548                 return;
549
550         if (!norun) {
551                 if (statfs(mtpoint, &sfs) == -1) {
552                         warn("statfs: %s", mtpoint);
553                         return;
554                 }
555                 if ((sfs.f_flags & MNT_RDONLY) != 0) {
556                         if (mip->mi_forced_pw) {
557                                 warnx(
558         "Not changing mode/owner of %s since it is read-only",
559                                     mtpoint);
560                         } else {
561                                 debugprintf(
562         "Not changing mode/owner of %s since it is read-only",
563                                     mtpoint);
564                         }
565                         return;
566                 }
567         }
568
569         if (mip->mi_have_mode) {
570                 debugprintf("changing mode of %s to %o.", mtpoint,
571                     mip->mi_mode);
572                 if (!norun)
573                         if (chmod(mtpoint, mip->mi_mode) == -1)
574                                 err(1, "chmod: %s", mtpoint);
575         }
576         /*
577          * We have to do these separately because the user may have
578          * only specified one of them.
579          */
580         if (mip->mi_have_uid) {
581                 debugprintf("changing owner (user) or %s to %u.", mtpoint,
582                     mip->mi_uid);
583                 if (!norun)
584                         if (chown(mtpoint, mip->mi_uid, -1) == -1)
585                                 err(1, "chown %s to %u (user)", mtpoint,
586                                     mip->mi_uid);
587         }
588         if (mip->mi_have_gid) {
589                 debugprintf("changing owner (group) or %s to %u.", mtpoint,
590                     mip->mi_gid);
591                 if (!norun)
592                         if (chown(mtpoint, -1, mip->mi_gid) == -1)
593                                 err(1, "chown %s to %u (group)", mtpoint,
594                                     mip->mi_gid);
595         }
596 }
597
598 /*
599  * Put a file system on the memory disk.
600  */
601 static void
602 do_newfs(const char *args)
603 {
604         int rv;
605
606         rv = run(NULL, "%s%s /dev/%s%d", _PATH_NEWFS, args, mdname, unit);
607         if (rv)
608                 errx(1, "newfs exited with error code %d", rv);
609 }
610
611 /*
612  * 'str' should be a user and group name similar to the last argument
613  * to chown(1); i.e., a user, followed by a colon, followed by a
614  * group.  The user and group in 'str' may be either a [ug]id or a
615  * name.  Upon return, the uid and gid fields in 'mip' will contain
616  * the uid and gid of the user and group name in 'str', respectively.
617  *
618  * In other words, this derives a user and group id from a string
619  * formatted like the last argument to chown(1).
620  *
621  * Notice: At this point we don't support only a username or only a
622  * group name. do_mtptsetup already does, so when this feature is
623  * desired, this is the only routine that needs to be changed.
624  */
625 static void
626 extract_ugid(const char *str, struct mtpt_info *mip)
627 {
628         char *ug;                       /* Writable 'str'. */
629         char *user, *group;             /* Result of extracton. */
630         struct passwd *pw;
631         struct group *gr;
632         char *p;
633         uid_t *uid;
634         gid_t *gid;
635
636         uid = &mip->mi_uid;
637         gid = &mip->mi_gid;
638         mip->mi_have_uid = mip->mi_have_gid = false;
639
640         /* Extract the user and group from 'str'.  Format above. */
641         ug = strdup(str);
642         assert(ug != NULL);
643         group = ug;
644         user = strsep(&group, ":");
645         if (user == NULL || group == NULL || *user == '\0' || *group == '\0')
646                 usage();
647
648         /* Derive uid. */
649         *uid = strtoul(user, &p, 10);
650         if (*uid == (uid_t)ULONG_MAX)
651                 usage();
652         if (*p != '\0') {
653                 pw = getpwnam(user);
654                 if (pw == NULL)
655                         errx(1, "invalid user: %s", user);
656                 *uid = pw->pw_uid;
657         }
658         mip->mi_have_uid = true;
659
660         /* Derive gid. */
661         *gid = strtoul(group, &p, 10);
662         if (*gid == (gid_t)ULONG_MAX)
663                 usage();
664         if (*p != '\0') {
665                 gr = getgrnam(group);
666                 if (gr == NULL)
667                         errx(1, "invalid group: %s", group);
668                 *gid = gr->gr_gid;
669         }
670         mip->mi_have_gid = true;
671
672         free(ug);
673 }
674
675 /*
676  * Run a process with command name and arguments pointed to by the
677  * formatted string 'cmdline'.  Since system(3) is not used, the first
678  * space-delimited token of 'cmdline' must be the full pathname of the
679  * program to run.  The return value is the return code of the process
680  * spawned.  If 'ofd' is non-NULL, it is set to the standard output of
681  * the program spawned (i.e., you can read from ofd and get the output
682  * of the program).
683  */
684 static int
685 run(int *ofd, const char *cmdline, ...)
686 {
687         char **argv, **argvp;           /* Result of splitting 'cmd'. */
688         int argc;
689         char *cmd;                      /* Expansion of 'cmdline'. */
690         int pid, status;                /* Child info. */
691         int pfd[2];                     /* Pipe to the child. */
692         int nfd;                        /* Null (/dev/null) file descriptor. */
693         bool dup2dn;                    /* Dup /dev/null to stdout? */
694         va_list ap;
695         char *p;
696         int rv, i;
697
698         dup2dn = true;
699         va_start(ap, cmdline);
700         rv = vasprintf(&cmd, cmdline, ap);
701         if (rv == -1)
702                 err(1, "vasprintf");
703         va_end(ap);
704
705         /* Split up 'cmd' into 'argv' for use with execve. */
706         for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
707                 argc++;         /* 'argc' generation loop. */
708         argv = (char **)malloc(sizeof(*argv) * (argc + 1));
709         assert(argv != NULL);
710         for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
711                 if (**argvp != '\0')
712                         if (++argvp >= &argv[argc]) {
713                                 *argvp = NULL;
714                                 break;
715                         }
716         assert(*argv);
717         /* The argv array ends up NULL-terminated here. */
718
719         /* Make sure the above loop works as expected. */
720         if (debug) {
721                 /*
722                  * We can't, but should, use debugprintf here.  First,
723                  * it appends a trailing newline to the output, and
724                  * second it prepends "DEBUG: " to the output.  The
725                  * former is a problem for this would-be first call,
726                  * and the latter for the would-be call inside the
727                  * loop.
728                  */
729                 (void)fprintf(stderr, "DEBUG: running:");
730                 /* Should be equivalent to 'cmd' (before strsep, of course). */
731                 for (i = 0; argv[i] != NULL; i++)
732                         (void)fprintf(stderr, " %s", argv[i]);
733                 (void)fprintf(stderr, "\n");
734         }
735
736         /* Create a pipe if necessary and fork the helper program. */
737         if (ofd != NULL) {
738                 if (pipe(&pfd[0]) == -1)
739                         err(1, "pipe");
740                 *ofd = pfd[0];
741                 dup2dn = false;
742         }
743         pid = fork();
744         switch (pid) {
745         case 0:
746                 /* XXX can we call err() in here? */
747                 if (norun)
748                         _exit(0);
749                 if (ofd != NULL)
750                         if (dup2(pfd[1], STDOUT_FILENO) < 0)
751                                 err(1, "dup2");
752                 if (!loudsubs) {
753                         nfd = open(_PATH_DEVNULL, O_RDWR);
754                         if (nfd == -1)
755                                 err(1, "open: %s", _PATH_DEVNULL);
756                         if (dup2(nfd, STDIN_FILENO) < 0)
757                                 err(1, "dup2");
758                         if (dup2dn)
759                                 if (dup2(nfd, STDOUT_FILENO) < 0)
760                                    err(1, "dup2");
761                         if (dup2(nfd, STDERR_FILENO) < 0)
762                                 err(1, "dup2");
763                 }
764
765                 (void)execv(argv[0], argv);
766                 warn("exec: %s", argv[0]);
767                 _exit(-1);
768         case -1:
769                 err(1, "fork");
770         }
771
772         free(cmd);
773         free(argv);
774         while (waitpid(pid, &status, 0) != pid)
775                 ;
776         return (WEXITSTATUS(status));
777 }
778
779 static void
780 usage(void)
781 {
782
783         fprintf(stderr,
784 "usage: %s [-DLlMNnPStUX] [-a maxcontig] [-b block-size]\n"
785 "\t[-c blocks-per-cylinder-group][-d max-extent-size] [-E path-mdconfig]\n"
786 "\t[-e maxbpg] [-F file] [-f frag-size] [-i bytes] [-m percent-free]\n"
787 "\t[-O optimization] [-o mount-options]\n"
788 "\t[-p permissions] [-s size] [-v version] [-w user:group]\n"
789 "\tmd-device mount-point\n", getprogname());
790         exit(1);
791 }