Home | History | Annotate | Line # | Download | only in newfs_ext2fs
      1 /*	$NetBSD: newfs_ext2fs.c,v 1.13 2026/05/03 17:49:58 kre 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.13 2026/05/03 17:49:58 kre 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
    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 	const char *s1, *special;
    130 	char *s2;
    131 	const char *opstring;
    132 	int byte_sized;
    133 	uint blocks;			/* number of blocks */
    134 
    135 	fsi = fso = -1;
    136 	Fflag = Iflag = Zflag = 0;
    137 	verbosity = -1;
    138 	opstring = "D:FINO:S:V:Zb:f:i:l:m:n:s:v:";
    139 	byte_sized = 0;
    140 	while ((ch = getopt(argc, argv, opstring)) != -1)
    141 		switch (ch) {
    142 		case 'D':
    143 			inodesize = (uint16_t)strtol(optarg, &s2, 0);
    144 			if (*s2 || (inodesize != 128 && inodesize != 256))
    145 				errx(1, "Bad inode size %d "
    146 				    "(only 128 and 256 supported)", inodesize);
    147 			break;
    148 		case 'F':
    149 			Fflag = 1;
    150 			break;
    151 		case 'I':
    152 			Iflag = 1;
    153 			break;
    154 		case 'N':
    155 			Nflag = 1;
    156 			if (verbosity == -1)
    157 				verbosity = DEFAULT_VERBOSITY;
    158 			break;
    159 		case 'O':
    160 			Oflag = strsuftoi64("format", optarg, 0, 1, NULL);
    161 			break;
    162 		case 'S':
    163 			/*
    164 			 * XXX:
    165 			 * non-512 byte sectors almost certainly don't work.
    166 			 */
    167 			sectorsize = strsuftoi64("sector size",
    168 			    optarg, 512, 65536, NULL);
    169 			if (!powerof2(sectorsize))
    170 				errx(EXIT_FAILURE,
    171 				    "sector size `%s' is not a power of 2.",
    172 				    optarg);
    173 			break;
    174 		case 'V':
    175 			verbosity = strsuftoi64("verbose", optarg, 0, 4, NULL);
    176 			break;
    177 		case 'Z':
    178 			Zflag = 1;
    179 			break;
    180 		case 'b':
    181 			bsize = strsuftoi64("block size",
    182 			    optarg, MINBSIZE, EXT2_MAXBSIZE, NULL);
    183 			break;
    184 		case 'f':
    185 			fsize = strsuftoi64("fragment size",
    186 			    optarg, MINBSIZE, EXT2_MAXBSIZE, NULL);
    187 			break;
    188 		case 'i':
    189 			density = strsuftoi64("bytes per inode",
    190 			    optarg, 1, INT_MAX, NULL);
    191 			break;
    192 		case 'm':
    193 			minfree = strsuftoi64("free space %",
    194 			    optarg, 0, 99, NULL);
    195 			break;
    196 		case 'n':
    197 			num_inodes = strsuftoi64("number of inodes",
    198 			    optarg, 1, INT_MAX, NULL);
    199 			break;
    200 		case 's':
    201 			fssize = strsuftoi64("file system size",
    202 			    optarg, INT64_MIN, INT64_MAX, &byte_sized);
    203 			break;
    204 		case 'v':
    205 			volname = optarg;
    206 			if (volname[0] == '\0')
    207 				errx(EXIT_FAILURE,
    208 				    "Volume name cannot be zero length");
    209 			break;
    210 		case '?':
    211 		default:
    212 			usage();
    213 		}
    214 	argc -= optind;
    215 	argv += optind;
    216 
    217 	if (verbosity == -1)
    218 		/* Default to showing cg info */
    219 		verbosity = DEFAULT_VERBOSITY;
    220 
    221 	if (argc != 1)
    222 		usage();
    223 
    224 	memset(&sb, 0, sizeof(sb));
    225 	memset(&dkw, 0, sizeof(dkw));
    226 	special = argv[0];
    227 	if (Fflag) {
    228 		int fl;
    229 		/*
    230 		 * It's a file system image
    231 		 * no label, use fixed default for sectorsize.
    232 		 */
    233 		if (sectorsize == 0)
    234 			sectorsize = DFL_SECSIZE;
    235 
    236 		/* creating image in a regular file */
    237 		if (Nflag)
    238 			fl = O_RDONLY;
    239 		else {
    240 			if (fssize > 0)
    241 				fl = O_RDWR | O_CREAT;
    242 			else
    243 				fl = O_RDWR;
    244 		}
    245 		fsi = open(special, fl, 0777);
    246 		if (fsi == -1)
    247 			err(EXIT_FAILURE, "can't open file %s", special);
    248 		if (fstat(fsi, &sb) == -1)
    249 			err(EXIT_FAILURE, "can't fstat opened %s", special);
    250 		if (!Nflag)
    251 			fso = fsi;
    252 	} else {	/* !Fflag */
    253 		special = findspecial(special, 1);
    254 		fsi = opendisk(special, O_RDONLY, device, sizeof(device), 0);
    255 		special = device;
    256 		if (fsi < 0 || fstat(fsi, &sb) == -1)
    257 			err(EXIT_FAILURE, "%s: open for read", special);
    258 
    259 		if (!Nflag) {
    260 			fso = open(special, O_WRONLY, 0);
    261 			if (fso < 0)
    262 				err(EXIT_FAILURE,
    263 				    "%s: open for write", special);
    264 
    265 			/* Bail if target special is mounted */
    266 			n = getmntinfo(&mp, MNT_NOWAIT);
    267 			if (n == 0)
    268 				err(EXIT_FAILURE, "%s: getmntinfo", special);
    269 
    270 			len = sizeof(_PATH_DEV) - 1;
    271 			s1 = special;
    272 			if (strncmp(_PATH_DEV, s1, len) == 0)
    273 				s1 += len;
    274 
    275 			while (--n >= 0) {
    276 				s2 = mp->f_mntfromname;
    277 				if (strncmp(_PATH_DEV, s2, len) == 0) {
    278 					s2 += len - 1;
    279 					*s2 = 'r';
    280 				}
    281 				if (strcmp(s1, s2) == 0 ||
    282 				    strcmp(s1, &s2[1]) == 0)
    283 					errx(EXIT_FAILURE,
    284 					    "%s is mounted on %s",
    285 					    special, mp->f_mntonname);
    286 				++mp;
    287 			}
    288 		}
    289 
    290 		if (getdiskinfo(special, fsi, disktype, &geo, &dkw) == -1)
    291 			errx(EXIT_FAILURE, lmsg, special);
    292 
    293 		if (sectorsize == 0) {
    294 			sectorsize = geo.dg_secsize;
    295 			if (sectorsize <= 0)
    296 				errx(EXIT_FAILURE, "no default sector size");
    297 		}
    298 
    299 		if (dkw.dkw_parent[0]) {
    300 			if (dkw.dkw_size == 0)
    301 				errx(EXIT_FAILURE,
    302 				    "%s partition is unavailable", special);
    303 
    304 			if (!Iflag) {
    305 				static const char m[] =
    306 				    "%s partition type is not `%s' (or use -I)";
    307 				if (strcmp(dkw.dkw_ptype, DKW_PTYPE_EXT2FS))
    308 					errx(EXIT_FAILURE, m,
    309 					    special, "Linux Ext2");
    310 			}
    311 		}
    312 	}
    313 
    314 	if (byte_sized)
    315 		fssize /= sectorsize;
    316 	if (fssize <= 0) {
    317 		if (sb.st_size != 0)
    318 			fssize += sb.st_size / sectorsize;
    319 		else
    320 			fssize += dkw.dkw_size;
    321 		if (fssize <= 0)
    322 			errx(EXIT_FAILURE,
    323 			    "Unable to determine file system size");
    324 	}
    325 
    326 	if (dkw.dkw_parent[0] && fssize > dkw.dkw_size)
    327 		errx(EXIT_FAILURE,
    328 		    "size %" PRIu64 " exceeds maximum file system size on "
    329 		    "`%s' of %" PRIu64 " sectors",
    330 		    fssize, special, dkw.dkw_size);
    331 
    332 	/* XXXLUKEM: only ftruncate() regular files ? (dsl: or at all?) */
    333 	if (Fflag && fso != -1
    334 	    && ftruncate(fso, (off_t)fssize * sectorsize) == -1)
    335 		err(1, "can't ftruncate %s to %" PRId64, special, fssize);
    336 
    337 	if (Zflag && fso != -1) {	/* pre-zero (and de-sparse) the file */
    338 		char *buf;
    339 		int bufsize, i;
    340 		off_t bufrem;
    341 		struct statvfs sfs;
    342 
    343 		if (fstatvfs(fso, &sfs) == -1) {
    344 			warn("can't fstatvfs `%s'", special);
    345 			bufsize = 8192;
    346 		} else
    347 			bufsize = sfs.f_iosize;
    348 
    349 		if ((buf = calloc(1, bufsize)) == NULL)
    350 			err(1, "can't malloc buffer of %d",
    351 			bufsize);
    352 		bufrem = fssize * sectorsize;
    353 		if (verbosity > 0)
    354 			printf("Creating file system image in `%s', "
    355 			    "size %" PRId64 " bytes, in %d byte chunks.\n",
    356 			    special, bufrem, bufsize);
    357 		while (bufrem > 0) {
    358 			i = write(fso, buf, MIN(bufsize, bufrem));
    359 			if (i == -1)
    360 				err(1, "writing image");
    361 			bufrem -= i;
    362 		}
    363 		free(buf);
    364 	}
    365 
    366 	/* Sort out fragment and block sizes */
    367 	if (bsize == 0) {
    368 		bsize = fsize;
    369 		if (bsize == 0) {
    370 			if (fssize < SMALL_FSSIZE)
    371 				bsize = S_DFL_BSIZE;
    372 			else if (fssize < MEDIUM_FSSIZE)
    373 				bsize = M_DFL_BSIZE;
    374 			else
    375 				bsize = L_DFL_BSIZE;
    376 		}
    377 	}
    378 	if (fsize == 0)
    379 		fsize = bsize;
    380 
    381 	blocks = fssize * sectorsize / bsize;
    382 
    383 	if (num_inodes == 0) {
    384 		if (density != 0)
    385 			num_inodes = fssize / density;
    386 		else {
    387 			if (fssize < SMALL_FSSIZE)
    388 				num_inodes = S_DFL_NINODE(blocks);
    389 			else if (fssize < MEDIUM_FSSIZE)
    390 				num_inodes = M_DFL_NINODE(blocks);
    391 			else
    392 				num_inodes = L_DFL_NINODE(blocks);
    393 		}
    394 	}
    395 	mke2fs(special, fsi, fso);
    396 
    397 	if (fsi != -1)
    398 		close(fsi);
    399 	if (fso != -1 && fso != fsi)
    400 		close(fso);
    401 	exit(EXIT_SUCCESS);
    402 }
    403 
    404 static int64_t
    405 strsuftoi64(const char *desc, const char *arg, int64_t min, int64_t max,
    406     int *num_suffix)
    407 {
    408 	int64_t result, r1;
    409 	int shift = 0;
    410 	char *ep;
    411 
    412 	errno = 0;
    413 	r1 = strtoll(arg, &ep, 10);
    414 	if (ep[0] != '\0' && ep[1] != '\0')
    415 		errx(EXIT_FAILURE,
    416 		    "%s `%s' is not a valid number.", desc, arg);
    417 	switch (ep[0]) {
    418 	case '\0':
    419 	case 's':
    420 	case 'S':
    421 		if (num_suffix != NULL)
    422 			*num_suffix = 0;
    423 		break;
    424 	case 'g':
    425 	case 'G':
    426 		shift += 10;
    427 		/* FALLTHROUGH */
    428 	case 'm':
    429 	case 'M':
    430 		shift += 10;
    431 		/* FALLTHROUGH */
    432 	case 'k':
    433 	case 'K':
    434 		shift += 10;
    435 		/* FALLTHROUGH */
    436 	case 'b':
    437 	case 'B':
    438 		if (num_suffix != NULL)
    439 			*num_suffix = 1;
    440 		break;
    441 	default:
    442 		errx(EXIT_FAILURE,
    443 		    "`%s' is not a valid suffix for %s.", ep, desc);
    444 	}
    445 	result = r1 << shift;
    446 	if (errno == ERANGE || result >> shift != r1)
    447 		errx(EXIT_FAILURE,
    448 		    "%s `%s' is too large to convert.", desc, arg);
    449 	if (result < min)
    450 		errx(EXIT_FAILURE,
    451 		    "%s `%s' (%" PRId64 ") is less than the minimum (%"
    452 		    PRId64 ").", desc, arg, result, min);
    453 	if (result > max)
    454 		errx(EXIT_FAILURE,
    455 		    "%s `%s' (%" PRId64 ") is greater than the maximum (%"
    456 		    PRId64 ").", desc, arg, result, max);
    457 	return result;
    458 }
    459 
    460 static const char help_strings[] =
    461 	"\t-b bsize\tblock size\n"
    462 	"\t-D inodesize\tsize of an inode in bytes (128 or 256)\n"
    463 	"\t-F \t\tcreate file system image in regular file\n"
    464 	"\t-f fsize\tfragment size\n"
    465 	"\t-I \t\tdo not check that the file system type is `Linux Ext2'\n"
    466 	"\t-i density\tnumber of bytes per inode\n"
    467 	"\t-m minfree\tminimum free space %\n"
    468 	"\t-N \t\tdo not create file system, just print out parameters\n"
    469 	"\t-n inodes\tnumber of inodes (overrides -i density)\n"
    470 	"\t-O N\t\tfilesystem revision: 0 ==> REV0, 1 ==> REV1 (default 0)\n"
    471 	"\t-S secsize\tsector size\n"
    472 	"\t-s fssize\tfile system size (sectors)\n"
    473 	"\t-V verbose\toutput verbosity: 0 ==> none, 4 ==> max\n"
    474 	"\t-v volname\text2fs volume name\n"
    475 	"\t-Z \t\tpre-zero the image file\n";
    476 
    477 static void
    478 usage(void)
    479 {
    480 
    481 	fprintf(stderr,
    482 	    "usage: %s [ fsoptions ] special-device\n", getprogname());
    483 	fprintf(stderr, "where fsoptions are:\n");
    484 	fprintf(stderr, "%s", help_strings);
    485 
    486 	exit(EXIT_FAILURE);
    487 }
    488