xref: /netbsd-src/sbin/newfs_ext2fs/newfs_ext2fs.c (revision f84252b4612a59cf9d1931a2c23c67a12766b0d5)
1 /*	$NetBSD: newfs_ext2fs.c,v 1.11 2022/04/16 18:15:21 andvar Exp $	*/
2 
3 /*
4  * Copyright (c) 1983, 1989, 1993, 1994
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) 1983, 1989, 1993, 1994\
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.13 (Berkeley) 5/1/95";
41 #else
42 __RCSID("$NetBSD: newfs_ext2fs.c,v 1.11 2022/04/16 18:15:21 andvar Exp $");
43 #endif
44 #endif /* not lint */
45 
46 /*
47  * newfs: friendly front end to mke2fs
48  */
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
51 #include <sys/disklabel.h>
52 #include <sys/disk.h>
53 #include <sys/file.h>
54 #include <sys/mount.h>
55 
56 #include <ufs/ext2fs/ext2fs.h>
57 #include <ufs/ext2fs/ext2fs_dinode.h>
58 
59 #include <disktab.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <limits.h>
63 #include <paths.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <util.h>
69 #include <mntopts.h>
70 
71 #include "extern.h"
72 #include "partutil.h"
73 
74 static int64_t strsuftoi64(const char *, const char *, int64_t, int64_t, int *);
75 static void usage(void) __dead;
76 
77 /*
78  * For file systems smaller than SMALL_FSSIZE we use the S_DFL_* defaults,
79  * otherwise if less than MEDIUM_FSSIZE use M_DFL_*, otherwise use
80  * L_DFL_*.
81  */
82 #define SMALL_FSSIZE	((4 * 1024 * 1024) / sectorsize)	/* 4MB */
83 #define S_DFL_BSIZE	1024
84 #define MEDIUM_FSSIZE	((512 * 1024 * 1024) / sectorsize)	/* 512MB */
85 #define M_DFL_BSIZE	1024
86 #define L_DFL_BSIZE	4096
87 
88 /*
89  * Each file system has a number of inodes statically allocated.
90  * We allocate one inode slot per 2, 4, or 8 blocks, expecting this
91  * to be far more than we will ever need.
92  */
93 #define S_DFL_NINODE(blocks)	((blocks) / 8)
94 #define M_DFL_NINODE(blocks)	((blocks) / 4)
95 #define L_DFL_NINODE(blocks)	((blocks) / 2)
96 
97 /*
98  * Default sector size.
99  */
100 #define	DFL_SECSIZE	512
101 
102 int	Nflag;			/* run without writing file system */
103 int	Oflag = 1;		/* format as REV1 by default */
104 int	verbosity;		/* amount of printf() output */
105 #define DEFAULT_VERBOSITY 3	/* 4 is traditional behavior of newfs(8) */
106 int64_t fssize;			/* file system size */
107 uint	sectorsize;		/* bytes/sector */
108 uint16_t inodesize = EXT2_REV0_DINODE_SIZE;	/* inode size */
109 uint	fsize = 0;		/* fragment size */
110 uint	bsize = 0;		/* block size */
111 uint	minfree = MINFREE;	/* free space threshold */
112 uint	density;		/* number of bytes per inode */
113 uint	num_inodes;		/* number of inodes (overrides density) */
114 char	*volname = NULL;	/* volume name */
115 
116 static char *disktype = NULL;
117 static char device[MAXPATHLEN];
118 
119 static const char lmsg[] = "%s: can't read disk label";
120 
121 int
main(int argc,char * argv[])122 main(int argc, char *argv[])
123 {
124 	struct disk_geom geo;
125 	struct dkwedge_info dkw;
126 	struct statvfs *mp;
127 	struct stat sb;
128 	int ch, fsi, fso, len, n, Fflag, Iflag, Zflag;
129 	char *s1, *s2, *special;
130 	const char *opstring;
131 	int byte_sized;
132 	uint blocks;			/* number of blocks */
133 
134 	fsi = fso = -1;
135 	Fflag = Iflag = Zflag = 0;
136 	verbosity = -1;
137 	opstring = "D:FINO:S:V:Zb:f:i:l:m:n:s:v:";
138 	byte_sized = 0;
139 	while ((ch = getopt(argc, argv, opstring)) != -1)
140 		switch (ch) {
141 		case 'D':
142 			inodesize = (uint16_t)strtol(optarg, &s1, 0);
143 			if (*s1 || (inodesize != 128 && inodesize != 256))
144 				errx(1, "Bad inode size %d "
145 				    "(only 128 and 256 supported)", inodesize);
146 			break;
147 		case 'F':
148 			Fflag = 1;
149 			break;
150 		case 'I':
151 			Iflag = 1;
152 			break;
153 		case 'N':
154 			Nflag = 1;
155 			if (verbosity == -1)
156 				verbosity = DEFAULT_VERBOSITY;
157 			break;
158 		case 'O':
159 			Oflag = strsuftoi64("format", optarg, 0, 1, NULL);
160 			break;
161 		case 'S':
162 			/*
163 			 * XXX:
164 			 * non-512 byte sectors almost certainly don't work.
165 			 */
166 			sectorsize = strsuftoi64("sector size",
167 			    optarg, 512, 65536, NULL);
168 			if (!powerof2(sectorsize))
169 				errx(EXIT_FAILURE,
170 				    "sector size `%s' is not a power of 2.",
171 				    optarg);
172 			break;
173 		case 'V':
174 			verbosity = strsuftoi64("verbose", optarg, 0, 4, NULL);
175 			break;
176 		case 'Z':
177 			Zflag = 1;
178 			break;
179 		case 'b':
180 			bsize = strsuftoi64("block size",
181 			    optarg, MINBSIZE, EXT2_MAXBSIZE, NULL);
182 			break;
183 		case 'f':
184 			fsize = strsuftoi64("fragment size",
185 			    optarg, MINBSIZE, EXT2_MAXBSIZE, NULL);
186 			break;
187 		case 'i':
188 			density = strsuftoi64("bytes per inode",
189 			    optarg, 1, INT_MAX, NULL);
190 			break;
191 		case 'm':
192 			minfree = strsuftoi64("free space %",
193 			    optarg, 0, 99, NULL);
194 			break;
195 		case 'n':
196 			num_inodes = strsuftoi64("number of inodes",
197 			    optarg, 1, INT_MAX, NULL);
198 			break;
199 		case 's':
200 			fssize = strsuftoi64("file system size",
201 			    optarg, INT64_MIN, INT64_MAX, &byte_sized);
202 			break;
203 		case 'v':
204 			volname = optarg;
205 			if (volname[0] == '\0')
206 				errx(EXIT_FAILURE,
207 				    "Volume name cannot be zero length");
208 			break;
209 		case '?':
210 		default:
211 			usage();
212 		}
213 	argc -= optind;
214 	argv += optind;
215 
216 	if (verbosity == -1)
217 		/* Default to showing cg info */
218 		verbosity = DEFAULT_VERBOSITY;
219 
220 	if (argc != 1)
221 		usage();
222 
223 	memset(&sb, 0, sizeof(sb));
224 	memset(&dkw, 0, sizeof(dkw));
225 	special = argv[0];
226 	if (Fflag) {
227 		int fl;
228 		/*
229 		 * It's a file system image
230 		 * no label, use fixed default for sectorsize.
231 		 */
232 		if (sectorsize == 0)
233 			sectorsize = DFL_SECSIZE;
234 
235 		/* creating image in a regular file */
236 		if (Nflag)
237 			fl = O_RDONLY;
238 		else {
239 			if (fssize > 0)
240 				fl = O_RDWR | O_CREAT;
241 			else
242 				fl = O_RDWR;
243 		}
244 		fsi = open(special, fl, 0777);
245 		if (fsi == -1)
246 			err(EXIT_FAILURE, "can't open file %s", special);
247 		if (fstat(fsi, &sb) == -1)
248 			err(EXIT_FAILURE, "can't fstat opened %s", special);
249 		if (!Nflag)
250 			fso = fsi;
251 	} else {	/* !Fflag */
252 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
253 		special = device;
254 		if (fsi < 0 || fstat(fsi, &sb) == -1)
255 			err(EXIT_FAILURE, "%s: open for read", special);
256 
257 		if (!Nflag) {
258 			fso = open(special, O_WRONLY, 0);
259 			if (fso < 0)
260 				err(EXIT_FAILURE,
261 				    "%s: open for write", special);
262 
263 			/* Bail if target special is mounted */
264 			n = getmntinfo(&mp, MNT_NOWAIT);
265 			if (n == 0)
266 				err(EXIT_FAILURE, "%s: getmntinfo", special);
267 
268 			len = sizeof(_PATH_DEV) - 1;
269 			s1 = special;
270 			if (strncmp(_PATH_DEV, s1, len) == 0)
271 				s1 += len;
272 
273 			while (--n >= 0) {
274 				s2 = mp->f_mntfromname;
275 				if (strncmp(_PATH_DEV, s2, len) == 0) {
276 					s2 += len - 1;
277 					*s2 = 'r';
278 				}
279 				if (strcmp(s1, s2) == 0 ||
280 				    strcmp(s1, &s2[1]) == 0)
281 					errx(EXIT_FAILURE,
282 					    "%s is mounted on %s",
283 					    special, mp->f_mntonname);
284 				++mp;
285 			}
286 		}
287 
288 		if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
289 			errx(EXIT_FAILURE, lmsg, special);
290 
291 		if (sectorsize == 0) {
292 			sectorsize = geo.dg_secsize;
293 			if (sectorsize <= 0)
294 				errx(EXIT_FAILURE, "no default sector size");
295 		}
296 
297 		if (dkw.dkw_parent[0]) {
298 			if (dkw.dkw_size == 0)
299 				errx(EXIT_FAILURE,
300 				    "%s partition is unavailable", special);
301 
302 			if (!Iflag) {
303 				static const char m[] =
304 				    "%s partition type is not `%s' (or use -I)";
305 				if (strcmp(dkw.dkw_ptype, DKW_PTYPE_EXT2FS))
306 					errx(EXIT_FAILURE, m,
307 					    special, "Linux Ext2");
308 			}
309 		}
310 	}
311 
312 	if (byte_sized)
313 		fssize /= sectorsize;
314 	if (fssize <= 0) {
315 		if (sb.st_size != 0)
316 			fssize += sb.st_size / sectorsize;
317 		else
318 			fssize += dkw.dkw_size;
319 		if (fssize <= 0)
320 			errx(EXIT_FAILURE,
321 			    "Unable to determine file system size");
322 	}
323 
324 	if (dkw.dkw_parent[0] && fssize > dkw.dkw_size)
325 		errx(EXIT_FAILURE,
326 		    "size %" PRIu64 " exceeds maximum file system size on "
327 		    "`%s' of %" PRIu64 " sectors",
328 		    fssize, special, dkw.dkw_size);
329 
330 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
331 	if (Fflag && fso != -1
332 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
333 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
334 
335 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparse) the file */
336 		char *buf;
337 		int bufsize, i;
338 		off_t bufrem;
339 		struct statvfs sfs;
340 
341 		if (fstatvfs(fso, &sfs) == -1) {
342 			warn("can't fstatvfs `%s'", special);
343 			bufsize = 8192;
344 		} else
345 			bufsize = sfs.f_iosize;
346 
347 		if ((buf = calloc(1, bufsize)) == NULL)
348 			err(1, "can't malloc buffer of %d",
349 			bufsize);
350 		bufrem = fssize * sectorsize;
351 		if (verbosity > 0)
352 			printf("Creating file system image in `%s', "
353 			    "size %" PRId64 " bytes, in %d byte chunks.\n",
354 			    special, bufrem, bufsize);
355 		while (bufrem > 0) {
356 			i = write(fso, buf, MIN(bufsize, bufrem));
357 			if (i == -1)
358 				err(1, "writing image");
359 			bufrem -= i;
360 		}
361 		free(buf);
362 	}
363 
364 	/* Sort out fragment and block sizes */
365 	if (bsize == 0) {
366 		bsize = fsize;
367 		if (bsize == 0) {
368 			if (fssize < SMALL_FSSIZE)
369 				bsize = S_DFL_BSIZE;
370 			else if (fssize < MEDIUM_FSSIZE)
371 				bsize = M_DFL_BSIZE;
372 			else
373 				bsize = L_DFL_BSIZE;
374 		}
375 	}
376 	if (fsize == 0)
377 		fsize = bsize;
378 
379 	blocks = fssize * sectorsize / bsize;
380 
381 	if (num_inodes == 0) {
382 		if (density != 0)
383 			num_inodes = fssize / density;
384 		else {
385 			if (fssize < SMALL_FSSIZE)
386 				num_inodes = S_DFL_NINODE(blocks);
387 			else if (fssize < MEDIUM_FSSIZE)
388 				num_inodes = M_DFL_NINODE(blocks);
389 			else
390 				num_inodes = L_DFL_NINODE(blocks);
391 		}
392 	}
393 	mke2fs(special, fsi, fso);
394 
395 	if (fsi != -1)
396 		close(fsi);
397 	if (fso != -1 && fso != fsi)
398 		close(fso);
399 	exit(EXIT_SUCCESS);
400 }
401 
402 static int64_t
strsuftoi64(const char * desc,const char * arg,int64_t min,int64_t max,int * num_suffix)403 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max,
404     int *num_suffix)
405 {
406 	int64_t result, r1;
407 	int shift = 0;
408 	char *ep;
409 
410 	errno = 0;
411 	r1 = strtoll(arg, &ep, 10);
412 	if (ep[0] != '\0' && ep[1] != '\0')
413 		errx(EXIT_FAILURE,
414 		    "%s `%s' is not a valid number.", desc, arg);
415 	switch (ep[0]) {
416 	case '\0':
417 	case 's':
418 	case 'S':
419 		if (num_suffix != NULL)
420 			*num_suffix = 0;
421 		break;
422 	case 'g':
423 	case 'G':
424 		shift += 10;
425 		/* FALLTHROUGH */
426 	case 'm':
427 	case 'M':
428 		shift += 10;
429 		/* FALLTHROUGH */
430 	case 'k':
431 	case 'K':
432 		shift += 10;
433 		/* FALLTHROUGH */
434 	case 'b':
435 	case 'B':
436 		if (num_suffix != NULL)
437 			*num_suffix = 1;
438 		break;
439 	default:
440 		errx(EXIT_FAILURE,
441 		    "`%s' is not a valid suffix for %s.", ep, desc);
442 	}
443 	result = r1 << shift;
444 	if (errno == ERANGE || result >> shift != r1)
445 		errx(EXIT_FAILURE,
446 		    "%s `%s' is too large to convert.", desc, arg);
447 	if (result < min)
448 		errx(EXIT_FAILURE,
449 		    "%s `%s' (%" PRId64 ") is less than the minimum (%"
450 		    PRId64 ").", desc, arg, result, min);
451 	if (result > max)
452 		errx(EXIT_FAILURE,
453 		    "%s `%s' (%" PRId64 ") is greater than the maximum (%"
454 		    PRId64 ").", desc, arg, result, max);
455 	return result;
456 }
457 
458 static const char help_strings[] =
459 	"\t-b bsize\tblock size\n"
460 	"\t-D inodesize\tsize of an inode in bytes (128 or 256)\n"
461 	"\t-F \t\tcreate file system image in regular file\n"
462 	"\t-f fsize\tfragment size\n"
463 	"\t-I \t\tdo not check that the file system type is `Linux Ext2'\n"
464 	"\t-i density\tnumber of bytes per inode\n"
465 	"\t-m minfree\tminimum free space %\n"
466 	"\t-N \t\tdo not create file system, just print out parameters\n"
467 	"\t-n inodes\tnumber of inodes (overrides -i density)\n"
468 	"\t-O N\t\tfilesystem revision: 0 ==> REV0, 1 ==> REV1 (default 0)\n"
469 	"\t-S secsize\tsector size\n"
470 	"\t-s fssize\tfile system size (sectors)\n"
471 	"\t-V verbose\toutput verbosity: 0 ==> none, 4 ==> max\n"
472 	"\t-v volname\text2fs volume name\n"
473 	"\t-Z \t\tpre-zero the image file\n";
474 
475 static void
usage(void)476 usage(void)
477 {
478 
479 	fprintf(stderr,
480 	    "usage: %s [ fsoptions ] special-device\n", getprogname());
481 	fprintf(stderr, "where fsoptions are:\n");
482 	fprintf(stderr, "%s", help_strings);
483 
484 	exit(EXIT_FAILURE);
485 }
486