1 /*        $NetBSD: newfs.c,v 1.30 2015/10/15 06:24:33 dholland Exp $  */
2 
3 /*-
4  * Copyright (c) 1989, 1992, 1993
5  *        The Regents of the University of California.  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  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1989, 1992, 1993\
35  The Regents of the University of California.  All rights reserved.");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)newfs.c     8.5 (Berkeley) 5/24/95";
41 #else
42 __RCSID("$NetBSD: newfs.c,v 1.30 2015/10/15 06:24:33 dholland Exp $");
43 #endif
44 #endif /* not lint */
45 
46 /*
47  * newfs: friendly front end to mkfs
48  */
49 #include <sys/param.h>
50 #include <sys/ucred.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/file.h>
54 #include <sys/mount.h>
55 #include <sys/sysctl.h>
56 #include <sys/time.h>
57 #include <sys/disk.h>
58 
59 #include <ufs/lfs/lfs.h>
60 
61 #include <err.h>
62 #include <errno.h>
63 #include <unistd.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <ctype.h>
67 #include <string.h>
68 #include <paths.h>
69 #include <util.h>
70 #include "config.h"
71 #include "extern.h"
72 #include "bufcache.h"
73 #include "partutil.h"
74 
75 #define   COMPAT                        /* allow non-labeled disks */
76 
77 #ifdef COMPAT
78 const char lmsg[] = "%s: can't read disk label; disk type must be specified";
79 #else
80 const char lmsg[] = "%s: can't read disk label";
81 #endif
82 
83 int       Nflag = 0;                    /* run without writing file system */
84 int       fssize;                       /* file system size */
85 int       sectorsize;                   /* bytes/sector */
86 int       fsize = 0;                    /* fragment size */
87 int       bsize = 0;                    /* block size */
88 int       ibsize = 0;                   /* inode block size */
89 int       interleave = 0;               /* segment interleave */
90 int       minfree = MINFREE;  /* free space threshold */
91 int     minfreeseg = 0;         /* segments not counted in bfree total */
92 int     resvseg = 0;            /* free segments reserved for the cleaner */
93 u_int32_t roll_id = 0;                  /* roll-forward id */
94 u_long    memleft;            /* virtual memory available */
95 caddr_t   membase;            /* start address of memory based filesystem */
96 #ifdef COMPAT
97 char      *disktype;
98 #endif
99 int       preen = 0;                    /* Coexistence with fsck_lfs */
100 
101 char      device[MAXPATHLEN];
102 char      *progname, *special;
103 
104 extern long         dev_bsize;                    /* device block size */
105 
106 static int64_t strsuftoi64(const char *, const char *, int64_t, int64_t, int *);
107 static int strtoint(const char *, const char *, int, int);
108 static void usage(void);
109 
110 /* CHUNKSIZE should be larger than MAXPHYS */
111 #define CHUNKSIZE (1024 * 1024)
112 
113 static size_t
auto_segsize(int fd,off_t len,int version)114 auto_segsize(int fd, off_t len, int version)
115 {
116           off_t off, bw;
117           time_t start, finish;
118           char buf[CHUNKSIZE];
119           long seeks;
120           size_t final;
121           int i;
122 
123           /* First, get sequential access bandwidth */
124           time(&start);
125           finish = start;
126           for (off = 0; finish - start < 10; off += CHUNKSIZE) {
127                     if (pread(fd, buf, CHUNKSIZE, off) < 0)
128                               break;
129                     time(&finish);
130           }
131           /* Bandwidth = bytes / sec */
132           /* printf("%ld bytes in %ld seconds\n", (long)off, (long)(finish - start)); */
133           bw = off / (finish - start);
134 
135           /* Second, seek time */
136           time(&start);
137           finish = start; /* structure copy */
138           for (seeks = 0; finish - start < 10; ) {
139                     off = (((double)rand()) * (btodb(len))) / ((off_t)RAND_MAX + 1);
140                     if (pread(fd, buf, dbtob(1), dbtob(off)) < 0)
141                               err(1, "pread");
142                     time(&finish);
143                     ++seeks;
144           }
145           /* printf("%ld seeks in %ld seconds\n", (long)seeks, (long)(finish - start)); */
146           /* Seek time in units/sec */
147           seeks /= (finish - start);
148           if (seeks == 0)
149                     seeks = 1;
150 
151           printf("bw = %ld B/s, seek time %ld ms (%ld seeks/s)\n",
152                     (long)bw, 1000/seeks, seeks);
153           final = dbtob(btodb(4 * bw / seeks));
154           if (version == 1) {
155                     for (i = 0; final; final >>= 1, i++)
156                               ;
157                     final = 1 << i;
158           }
159           printf("using initial segment size %ld\n", (long)final);
160           return final;
161 }
162 
163 int
main(int argc,char ** argv)164 main(int argc, char **argv)
165 {
166           int version, ch;
167           struct disk_geom geo;
168           struct dkwedge_info dkw;
169           struct stat st;
170           int debug, force, fsi, fso, lfs_segsize, maxpartitions, bitwidth;
171           uint secsize = 0;
172           daddr_t start;
173           const char *opstring;
174           int byte_sized = 0;
175           int r;
176 
177           version = DFL_VERSION;                  /* what version of lfs to make */
178 
179           if ((progname = strrchr(*argv, '/')) != NULL)
180                     ++progname;
181           else
182                     progname = *argv;
183 
184           maxpartitions = getmaxpartitions();
185           if (maxpartitions > 26)
186                     fatal("insane maxpartitions value %d", maxpartitions);
187 
188           opstring = "AB:b:DFf:I:i:LM:m:NO:R:r:S:s:v:w:";
189 
190           start = debug = force = lfs_segsize = bitwidth = 0;
191           while ((ch = getopt(argc, argv, opstring)) != -1)
192                     switch(ch) {
193                     case 'A': /* Adaptively configure segment size */
194                               lfs_segsize = -1;
195                               break;
196                     case 'B': /* LFS segment size */
197                             lfs_segsize = strsuftoi64("segment size", optarg, LFS_MINSEGSIZE, INT64_MAX, NULL);
198                               break;
199                     case 'D':
200                               debug = 1;
201                               break;
202                     case 'F':
203                               force = 1;
204                               break;
205                     case 'I':
206                             interleave = strsuftoi64("interleave", optarg, 0, INT64_MAX, NULL);
207                               break;
208                     case 'L': /* Compatibility only */
209                               break;
210                     case 'M':
211                               minfreeseg = strsuftoi64("minfreeseg", optarg, 0, INT64_MAX, NULL);
212                               break;
213                     case 'N':
214                               Nflag++;
215                               break;
216                     case 'O':
217                               start = strsuftoi64("start", optarg, 0, INT64_MAX, NULL);
218                               break;
219                     case 'R':
220                               resvseg = strsuftoi64("resvseg", optarg, 0, INT64_MAX, NULL);
221                               break;
222                     case 'S':
223                               secsize = strsuftoi64("sector size", optarg, 1, INT64_MAX, NULL);
224                               if (secsize <= 0 || (secsize & (secsize - 1)))
225                                         fatal("%s: bad sector size", optarg);
226                               break;
227 #ifdef COMPAT
228                     case 'T':
229                               disktype = optarg;
230                               break;
231 #endif
232                     case 'b':
233                               bsize = strsuftoi64("block size", optarg, LFS_MINBLOCKSIZE, INT64_MAX, NULL);
234                               break;
235                     case 'f':
236                               fsize = strsuftoi64("fragment size", optarg, LFS_MINBLOCKSIZE, INT64_MAX, NULL);
237                               break;
238                     case 'i':
239                               ibsize = strsuftoi64("inode block size", optarg, LFS_MINBLOCKSIZE, INT64_MAX, NULL);
240                               break;
241                     case 'm':
242                               minfree = strsuftoi64("free space %", optarg, 0, 99, NULL);
243                               break;
244                     case 'r':
245                               roll_id = strsuftoi64("roll-forward id", optarg, 1, UINT_MAX, NULL);
246                               break;
247                     case 's':
248                             fssize = strsuftoi64("file system size", optarg, 0, INT64_MAX, &byte_sized);
249                               break;
250                     case 'v':
251                             version = strsuftoi64("file system version", optarg, 1, LFS_VERSION, NULL);
252                               break;
253                     case 'w':
254                               bitwidth = strtoint("bit width", optarg, 32, 64);
255                               break;
256                     case '?':
257                     default:
258                               usage();
259                     }
260           argc -= optind;
261           argv += optind;
262 
263           if (argc != 2 && argc != 1)
264                     usage();
265 
266           if (bitwidth != 32 && bitwidth != 64 && bitwidth != 0) {
267                     errx(1, "bit width %d is not sensible; please use 32 or 64",
268                          bitwidth);
269           }
270           if (bitwidth == 64 && version < 2) {
271                     errx(1, "Cannot make a 64-bit version 1 volume");
272           }
273 
274           /*
275            * If the -N flag isn't specified, open the output file.  If no path
276            * prefix, try /dev/r%s and then /dev/%s.
277            */
278           special = argv[0];
279           if (strchr(special, '/') == NULL) {
280                     (void)snprintf(device, sizeof(device), "%sr%s", _PATH_DEV,
281                         special);
282                     if (stat(device, &st) == -1)
283                               (void)snprintf(device, sizeof(device), "%s%s",
284                                   _PATH_DEV, special);
285                     special = device;
286           }
287           if (!Nflag) {
288                     fso = open(special, O_RDWR, DEFFILEMODE);
289                     if (debug && fso < 0) {
290                               /* Create a file of the requested size. */
291                               fso = open(special, O_CREAT | O_RDWR, DEFFILEMODE);
292                               if (fso >= 0) {
293                                         char buf[512];
294                                         int i;
295                                         for (i = 0; i < fssize; i++)
296                                                   write(fso, buf, sizeof(buf));
297                                         lseek(fso, 0, SEEK_SET);
298                               }
299                     }
300                     if (fso < 0)
301                               fatal("%s: %s", special, strerror(errno));
302           } else
303                     fso = -1;
304 
305           /* Open the input file. */
306           fsi = open(special, O_RDONLY);
307           if (fsi < 0)
308                     fatal("%s: %s", special, strerror(errno));
309           if (fstat(fsi, &st) < 0)
310                     fatal("%s: %s", special, strerror(errno));
311 
312 
313           if (!S_ISCHR(st.st_mode)) {
314                     if (!S_ISREG(st.st_mode)) {
315                               fatal("%s: neither a character special device "
316                                     "nor a regular file", special);
317                     }
318                     (void)strcpy(dkw.dkw_ptype, DKW_PTYPE_LFS);
319                     if (secsize == 0)
320                               secsize = 512;
321                     dkw.dkw_size = st.st_size / secsize;
322           } else {
323 #ifdef COMPAT
324                     if (disktype == NULL)
325                               disktype = argv[1];
326 #endif
327                     if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
328                               errx(1, lmsg, special);
329 
330                     if (dkw.dkw_size == 0)
331                               fatal("%s: is zero sized", argv[0]);
332                     if (!force && strcmp(dkw.dkw_ptype, DKW_PTYPE_LFS) != 0)
333                               fatal("%s: is not `%s', but `%s'", argv[0],
334                                   DKW_PTYPE_LFS, dkw.dkw_ptype);
335           }
336 
337           if (secsize == 0)
338                     secsize = geo.dg_secsize;
339 
340           /* Make device block size available to low level routines */
341           dev_bsize = secsize;
342 
343           /* From here on out fssize is in sectors */
344           if (byte_sized) {
345                     fssize /= secsize;
346           }
347 
348           /* If force, make the partition look like an LFS */
349           if (force) {
350                     (void)strcpy(dkw.dkw_ptype, DKW_PTYPE_LFS);
351                     if (fssize) {
352                               dkw.dkw_size = fssize;
353                     }
354           } else
355                     if (fssize != 0 && fssize < dkw.dkw_size)
356                               dkw.dkw_size = fssize;
357 
358           /*
359            * default to 64-bit for large volumes; note that we test for
360            * 2^31 sectors and not 2^32, because block numbers (daddr_t)
361            * are signed and negative values can/will cause interesting
362            * complications.
363            */
364           if (bitwidth == 0) {
365                     if (dkw.dkw_size > 0x7fffffff) {
366                               bitwidth = 64;
367                     } else {
368                               bitwidth = 32;
369                     }
370           }
371 
372           if (dkw.dkw_size > 0x7fffffff && bitwidth == 32) {
373                     if (dkw.dkw_size >= 0xfffffffe) {
374                               /* block numbers -1 and -2 are magic; must not exist */
375                               errx(1, "This volume is too large for a 32-bit LFS.");
376                     }
377                     /* User does this at own risk */
378                     warnx("Using negative block numbers; not recommended. "
379                           "You should probably use -w 64.");
380           }
381 
382           /* Try autoconfiguring segment size, if asked to */
383           if (lfs_segsize == -1) {
384                     if (!S_ISCHR(st.st_mode)) {
385                               warnx("%s is not a character special device, ignoring -A", special);
386                               lfs_segsize = 0;
387                     } else
388                               lfs_segsize = auto_segsize(fsi, dkw.dkw_size / secsize,
389                                   version);
390           }
391 
392           /* If we're making a LFS, we break out here */
393           r = make_lfs(fso, secsize, &dkw, minfree, bsize, fsize, lfs_segsize,
394               minfreeseg, resvseg, version, start, ibsize, interleave, roll_id,
395               bitwidth);
396           if (debug)
397                     bufstats();
398           exit(r);
399 }
400 
401 static int64_t
strsuftoi64(const char * desc,const char * arg,int64_t min,int64_t max,int * num_suffix)402 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max, int *num_suffix)
403 {
404           int64_t result, r1;
405           int shift = 0;
406           char      *ep;
407 
408           errno = 0;
409           r1 = strtoll(arg, &ep, 10);
410           if (ep[0] != '\0' && ep[1] != '\0')
411                     errx(1, "%s `%s' is not a valid number.", desc, arg);
412           switch (ep[0]) {
413           case '\0':
414           case 's': case 'S':
415                     if (num_suffix != NULL)
416                               *num_suffix = 0;
417                     break;
418           case 'g': case 'G':
419                     shift += 10;
420                     /* FALLTHROUGH */
421           case 'm': case 'M':
422                     shift += 10;
423                     /* FALLTHROUGH */
424           case 'k': case 'K':
425                     shift += 10;
426                     /* FALLTHROUGH */
427           case 'b': case 'B':
428                     if (num_suffix != NULL)
429                               *num_suffix = 1;
430                     break;
431           default:
432                     errx(1, "`%s' is not a valid suffix for %s.", ep, desc);
433           }
434           result = r1 << shift;
435           if (errno == ERANGE || result >> shift != r1)
436                     errx(1, "%s `%s' is too large to convert.", desc, arg);
437           if (result < min)
438                     errx(1, "%s `%s' (%" PRId64 ") is less than the minimum (%" PRId64 ").",
439                         desc, arg, result, min);
440           if (result > max)
441                     errx(1, "%s `%s' (%" PRId64 ") is greater than the maximum (%" PRId64 ").",
442                         desc, arg, result, max);
443           return result;
444 }
445 
446 static int
strtoint(const char * desc,const char * arg,int min,int max)447 strtoint(const char *desc, const char *arg, int min, int max)
448 {
449           long result;
450           char *s;
451 
452           errno = 0;
453           result = strtol(arg, &s, 10);
454           if (errno || *s != '\0') {
455                     errx(1, "%s `%s' is not a valid number.", desc, arg);
456           }
457 #if LONG_MAX > INT_MAX
458           if (result > INT_MAX || result < INT_MIN) {
459                     errx(1, "%s `%s' is out of range.", desc, arg);
460           }
461 #endif
462           if (result < min || result > max) {
463                     errx(1, "%s `%s' is out of range.", desc, arg);
464           }
465 
466           return (int)result;
467 }
468 
469 void
usage()470 usage()
471 {
472           fprintf(stderr, "usage: newfs_lfs [ -fsoptions ] special-device\n");
473           fprintf(stderr, "where fsoptions are:\n");
474           fprintf(stderr, "\t-A (autoconfigure segment size)\n");
475           fprintf(stderr, "\t-B segment size in bytes\n");
476           fprintf(stderr, "\t-D (debug)\n");
477           fprintf(stderr, "\t-M count of segments not counted in bfree\n");
478           fprintf(stderr,
479               "\t-N (do not create file system, just print out parameters)\n");
480           fprintf(stderr, "\t-O first segment offset in sectors\n");
481           fprintf(stderr, "\t-R count of segments reserved for the cleaner\n");
482           fprintf(stderr, "\t-b block size in bytes\n");
483           fprintf(stderr, "\t-f frag size in bytes\n");
484           fprintf(stderr, "\t-m minimum free space %%\n");
485           fprintf(stderr, "\t-s file system size in sectors\n");
486           fprintf(stderr, "\t-v version\n");
487           exit(1);
488 }
489