xref: /netbsd-src/sbin/newfs_ext2fs/mke2fs.c (revision a314b8f31d720d5f80071a443e3c11bd4c66ace0)
1 /*	$NetBSD: mke2fs.c,v 1.28 2025/01/05 22:11:18 andvar Exp $	*/
2 
3 /*-
4  * Copyright (c) 2007 Izumi Tsutsui.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 /*
28  * Copyright (c) 1980, 1989, 1993
29  *	The Regents of the University of California.  All rights reserved.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 3. Neither the name of the University nor the names of its contributors
40  *    may be used to endorse or promote products derived from this software
41  *    without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  */
55 
56 /*
57  * Copyright (c) 1997 Manuel Bouyer.
58  *
59  * Redistribution and use in source and binary forms, with or without
60  * modification, are permitted provided that the following conditions
61  * are met:
62  * 1. Redistributions of source code must retain the above copyright
63  *	notice, this list of conditions and the following disclaimer.
64  * 2. Redistributions in binary form must reproduce the above copyright
65  *	notice, this list of conditions and the following disclaimer in the
66  *	documentation and/or other materials provided with the distribution.
67  *
68  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
69  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
70  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
71  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
72  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
73  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
74  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
75  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
76  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
77  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
78  */
79 
80 /*
81  * mke2fs.c: "re-invent (dumb but non-GPLed) wheel as a fun project"
82  *
83  *	In spite of this name, there is no piece of code
84  *	derived from GPLed e2fsprogs written for Linux.
85  *	I referred them only to see how each structure
86  *	member should be initialized.
87  *
88  * Reference:
89  *	- All NetBSD sources under src/sys/ufs/ext2fs and src/sbin/fsck_ext2fs
90  *	- Ext2fs Home Page
91  *		https://e2fsprogs.sourceforge.net/ext2.html
92  *	- Design and Implementation of the Second Extended Filesystem
93  *		https://e2fsprogs.sourceforge.net/ext2intro.html
94  *	- Linux Documentation "The Second Extended Filesystem"
95  *		https://www.kernel.org/doc/Documentation/filesystems/ext2.txt
96  */
97 
98 #include <sys/cdefs.h>
99 #ifndef lint
100 #if 0
101 static char sccsid[] = "@(#)mkfs.c	8.11 (Berkeley) 5/3/95";
102 #else
103 __RCSID("$NetBSD: mke2fs.c,v 1.28 2025/01/05 22:11:18 andvar Exp $");
104 #endif
105 #endif /* not lint */
106 
107 #include <sys/param.h>
108 #include <sys/mman.h>
109 #include <sys/time.h>
110 #include <ufs/ext2fs/ext2fs_dinode.h>
111 #include <ufs/ext2fs/ext2fs_dir.h>
112 #include <ufs/ext2fs/ext2fs.h>
113 #include <sys/ioctl.h>
114 
115 #include <err.h>
116 #include <errno.h>
117 #include <string.h>
118 #include <unistd.h>
119 #include <stdlib.h>
120 #include <stddef.h>
121 #include <stdio.h>
122 #include <uuid.h>
123 
124 #include "extern.h"
125 
126 static void initcg(uint);
127 static void zap_old_sblock(int);
128 static uint cgoverhead(uint);
129 static int fsinit(const struct timeval *);
130 static int makedir(struct ext2fs_direct *, int);
131 static void copy_dir(struct ext2fs_direct *, struct ext2fs_direct *);
132 static void init_resizeino(const struct timeval *);
133 static uint32_t alloc(uint32_t, uint16_t);
134 static void iput(struct ext2fs_dinode *, ino_t);
135 static void rdfs(daddr_t, int, void *);
136 static void wtfs(daddr_t, int, void *);
137 static int ilog2(uint);
138 static int skpc(int, size_t, uint8_t *);
139 
140 /* XXX: some of these macro should be into <ufs/ext2fs/ext2fs.h>? */
141 #define EXT2_DEF_MAX_MNT_COUNT	20
142 #define EXT2_DEF_FSCKINTV	(180 * 24 * 60 * 60)	/* 180 days */
143 #define EXT2_RESERVED_INODES	(EXT2_FIRSTINO - 1)
144 #define EXT2_UMASK		0755
145 
146 #define EXT2_INO_INDEX(ino)	((ino) - 1)		/* no inode zero */
147 
148 #define EXT2_LOSTFOUNDSIZE	16384
149 #define EXT2_LOSTFOUNDINO	EXT2_FIRSTINO		/* XXX: not quite */
150 #define EXT2_LOSTFOUNDUMASK	0700
151 
152 #define EXT2_RESIZEINOUMASK	0600
153 
154 #define NBLOCK_SUPERBLOCK	1
155 #define NBLOCK_BLOCK_BITMAP	1
156 #define NBLOCK_INODE_BITMAP	1
157 
158 #define cgbase(fs, c)	\
159 	((fs)->e2fs.e2fs_first_dblock + (fs)->e2fs.e2fs_bpg * (c))
160 
161 
162 /*
163  * ext2fs super block and group descriptor structures
164  *
165  *   We don't have to use or setup whole in-memory m_ext2fs structure,
166  *   but prepare it to use several macro defined in kernel headers.
167  */
168 union {
169 	struct m_ext2fs m_ext2fs;
170 	char pad[SBSIZE];
171 } ext2fsun;
172 #define sblock	ext2fsun.m_ext2fs
173 #define gd	ext2fsun.m_ext2fs.e2fs_gd
174 
175 static uint8_t *iobuf;		/* for superblock and group descriptors */
176 static int iobufsize;
177 
178 static uint8_t buf[MAXBSIZE];	/* for initcg() and makedir() ops */
179 
180 static int fsi, fso;
181 
182 void
183 mke2fs(const char *fsys, int fi, int fo)
184 {
185 	struct timeval tv;
186 	int64_t minfssize;
187 	uint bcount, fbcount, ficount;
188 	uint blocks_gd, blocks_per_cg, inodes_per_cg, iblocks_per_cg;
189 	uint minblocks_per_cg, blocks_lastcg;
190 	uint ncg, cylno, sboff;
191 	uuid_t uuid;
192 	uint32_t uustat;
193 	int i, len, col, delta, fld_width, max_cols;
194 	struct winsize winsize;
195 
196 	gettimeofday(&tv, NULL);
197 	fsi = fi;
198 	fso = fo;
199 
200 	/*
201 	 * collect and verify the block and fragment sizes
202 	 */
203 	if (!powerof2(bsize)) {
204 		errx(EXIT_FAILURE,
205 		    "block size must be a power of 2, not %u",
206 		    bsize);
207 	}
208 	if (!powerof2(fsize)) {
209 		errx(EXIT_FAILURE,
210 		    "fragment size must be a power of 2, not %u",
211 		    fsize);
212 	}
213 	if (fsize < sectorsize) {
214 		errx(EXIT_FAILURE,
215 		    "fragment size %u is too small, minimum is %u",
216 		    fsize, sectorsize);
217 	}
218 	if (bsize < MINBSIZE) {
219 		errx(EXIT_FAILURE,
220 		    "block size %u is too small, minimum is %u",
221 		    bsize, MINBSIZE);
222 	}
223 	if (bsize > EXT2_MAXBSIZE) {
224 		errx(EXIT_FAILURE,
225 		    "block size %u is too large, maximum is %u",
226 		    bsize, MAXBSIZE);
227 	}
228 	if (bsize != fsize) {
229 		/*
230 		 * There is no fragment support on current ext2fs (yet?),
231 		 * but some kernel code refers fsize or fpg as bsize or bpg
232 		 * and Linux seems to set the same values to them.
233 		 */
234 		errx(EXIT_FAILURE,
235 		    "block size (%u) can't be different from "
236 		    "fragment size (%u)",
237 		    bsize, fsize);
238 	}
239 
240 	/* variable inodesize is REV1 feature */
241 	if (Oflag == 0 && inodesize != EXT2_REV0_DINODE_SIZE) {
242 		errx(EXIT_FAILURE, "GOOD_OLD_REV file system format"
243 		    " doesn't support %d byte inode", inodesize);
244 	}
245 
246 	sblock.e2fs.e2fs_log_bsize = ilog2(bsize) - LOG_MINBSIZE;
247 	/* Umm, why not e2fs_log_fsize? */
248 	sblock.e2fs.e2fs_fsize = ilog2(fsize) - LOG_MINBSIZE;
249 
250 	sblock.e2fs_bsize = bsize;
251 	sblock.e2fs_bshift = sblock.e2fs.e2fs_log_bsize + LOG_MINBSIZE;
252 	sblock.e2fs_qbmask = sblock.e2fs_bsize - 1;
253 	sblock.e2fs_bmask = ~sblock.e2fs_qbmask;
254 	sblock.e2fs_fsbtodb = ilog2(sblock.e2fs_bsize) - ilog2(sectorsize);
255 	sblock.e2fs_ipb = sblock.e2fs_bsize / inodesize;
256 
257 	/*
258 	 * Ext2fs preserves BBSIZE (1024 bytes) space at the top for
259 	 * bootloader (though it is not enough at all for our bootloader).
260 	 * If bsize == BBSIZE we have to preserve one block.
261 	 * If bsize > BBSIZE, the first block already contains BBSIZE space
262 	 * before superblock because superblock is allocated at SBOFF and
263 	 * bsize is a power of two (i.e. 2048 bytes or more).
264 	 */
265 	sblock.e2fs.e2fs_first_dblock = (sblock.e2fs_bsize > BBSIZE) ? 0 : 1;
266 	minfssize = EXT2_FSBTODB(&sblock,
267 	    sblock.e2fs.e2fs_first_dblock +
268 	    NBLOCK_SUPERBLOCK +
269 	    1 /* at least one group descriptor */ +
270 	    NBLOCK_BLOCK_BITMAP	+
271 	    NBLOCK_INODE_BITMAP +
272 	    1 /* at least one inode table block */ +
273 	    1 /* at least one data block for rootdir */ +
274 	    1 /* at least one data block for data */
275 	    );			/* XXX and more? */
276 
277 	if (fssize < minfssize)
278 		errx(EXIT_FAILURE, "Filesystem size %" PRId64
279 		    " < minimum size of %" PRId64, fssize, minfssize);
280 
281 	bcount = EXT2_DBTOFSB(&sblock, fssize);
282 
283 	/*
284 	 * While many people claim that ext2fs is a (bad) clone of ufs/ffs,
285 	 * it isn't actual ffs so maybe we should call it "block group"
286 	 * as their native name rather than ffs derived "cylinder group."
287 	 * But we'll use the latter here since other kernel sources use it.
288 	 * (I also agree "cylinder" based allocation is obsolete though)
289 	 */
290 
291 	/* maybe "simple is the best" */
292 	blocks_per_cg = sblock.e2fs_bsize * NBBY;
293 
294 	ncg = howmany(bcount - sblock.e2fs.e2fs_first_dblock, blocks_per_cg);
295 	blocks_gd = howmany(sizeof(struct ext2_gd) * ncg, bsize);
296 
297 	/* check range of inode number */
298 	if (num_inodes < EXT2_FIRSTINO)
299 		num_inodes = EXT2_FIRSTINO;	/* needs reserved inodes + 1 */
300 	if (num_inodes > UINT16_MAX * ncg)
301 		num_inodes = UINT16_MAX * ncg;	/* ext2bgd_nifree is uint16_t */
302 
303 	inodes_per_cg = num_inodes / ncg;
304 	iblocks_per_cg = howmany(inodesize * inodes_per_cg, bsize);
305 
306 	/* Check that the last cylinder group has enough space for inodes */
307 	minblocks_per_cg =
308 	    NBLOCK_BLOCK_BITMAP +
309 	    NBLOCK_INODE_BITMAP +
310 	    iblocks_per_cg +
311 	    1;	/* at least one data block */
312 	if (Oflag == 0 || cg_has_sb(ncg - 1) != 0)
313 		minblocks_per_cg += NBLOCK_SUPERBLOCK + blocks_gd;
314 
315 	blocks_lastcg = bcount - sblock.e2fs.e2fs_first_dblock -
316 	    blocks_per_cg * (ncg - 1);
317 	if (blocks_lastcg < minblocks_per_cg) {
318 		/*
319 		 * Since we make all the cylinder groups the same size, the
320 		 * last will only be small if there are more than one
321 		 * cylinder groups. If the last one is too small to store
322 		 * filesystem data, just kill it.
323 		 *
324 		 * XXX: Does fsck_ext2fs(8) properly handle this case?
325 		 */
326 		bcount -= blocks_lastcg;
327 		ncg--;
328 		blocks_lastcg = blocks_per_cg;
329 		blocks_gd = howmany(sizeof(struct ext2_gd) * ncg, bsize);
330 		inodes_per_cg = num_inodes / ncg;
331 	}
332 	/* roundup inodes_per_cg to make it use whole inode table blocks */
333 	inodes_per_cg = roundup(inodes_per_cg, sblock.e2fs_ipb);
334 	num_inodes = inodes_per_cg * ncg;
335 	iblocks_per_cg = inodes_per_cg / sblock.e2fs_ipb;
336 
337 	/* XXX: probably we should check these adjusted values again */
338 
339 	sblock.e2fs.e2fs_bcount = bcount;
340 	sblock.e2fs.e2fs_icount = num_inodes;
341 
342 	sblock.e2fs_ncg = ncg;
343 	sblock.e2fs_ngdb = blocks_gd;
344 	sblock.e2fs_itpg = iblocks_per_cg;
345 
346 	sblock.e2fs.e2fs_rbcount = sblock.e2fs.e2fs_bcount * minfree / 100;
347 	/* e2fs_fbcount will be accounted later */
348 	/* e2fs_ficount will be accounted later */
349 
350 	sblock.e2fs.e2fs_bpg = blocks_per_cg;
351 	sblock.e2fs.e2fs_fpg = blocks_per_cg;
352 
353 	sblock.e2fs.e2fs_ipg = inodes_per_cg;
354 
355 	sblock.e2fs.e2fs_mtime = 0;
356 	sblock.e2fs.e2fs_wtime = tv.tv_sec;
357 	sblock.e2fs.e2fs_mnt_count = 0;
358 	/* XXX: should add some entropy to avoid checking all fs at once? */
359 	sblock.e2fs.e2fs_max_mnt_count = EXT2_DEF_MAX_MNT_COUNT;
360 
361 	sblock.e2fs.e2fs_magic = E2FS_MAGIC;
362 	sblock.e2fs.e2fs_state = E2FS_ISCLEAN;
363 	sblock.e2fs.e2fs_beh = E2FS_BEH_DEFAULT;
364 	sblock.e2fs.e2fs_minrev = 0;
365 	sblock.e2fs.e2fs_lastfsck = tv.tv_sec;
366 	sblock.e2fs.e2fs_fsckintv = EXT2_DEF_FSCKINTV;
367 
368 	/*
369 	 * Maybe we can use E2FS_OS_FREEBSD here and it would be more proper,
370 	 * but the purpose of this newfs_ext2fs(8) command is to provide
371 	 * a filesystem which can be recognized by firmware on some
372 	 * Linux based appliances that can load bootstrap files only from
373 	 * (their native) ext2fs, and anyway we will (and should) try to
374 	 * act like them as much as possible.
375 	 *
376 	 * Anyway, I hope that all newer such boxes will keep their support
377 	 * for the "GOOD_OLD_REV" ext2fs.
378 	 */
379 	sblock.e2fs.e2fs_creator = E2FS_OS_LINUX;
380 
381 	if (Oflag == 0) {
382 		sblock.e2fs.e2fs_rev = E2FS_REV0;
383 		sblock.e2fs.e2fs_features_compat   = 0;
384 		sblock.e2fs.e2fs_features_incompat = 0;
385 		sblock.e2fs.e2fs_features_rocompat = 0;
386 	} else {
387 		sblock.e2fs.e2fs_rev = E2FS_REV1;
388 		/*
389 		 * e2fsprogs say "REV1" is "dynamic" so
390 		 * it isn't quite a version and maybe it means
391 		 * "extended from REV0 so check compat features."
392 		 *
393 		 * XXX: We don't have any native tool to activate
394 		 *      the EXT2F_COMPAT_RESIZE feature and
395 		 *      fsck_ext2fs(8) might not fix structures for it.
396 		 */
397 		sblock.e2fs.e2fs_features_compat   = EXT2F_COMPAT_RESIZE;
398 		sblock.e2fs.e2fs_features_incompat = EXT2F_INCOMPAT_FTYPE;
399 		sblock.e2fs.e2fs_features_rocompat =
400 		    EXT2F_ROCOMPAT_SPARSESUPER | EXT2F_ROCOMPAT_LARGEFILE;
401 	}
402 
403 	sblock.e2fs.e2fs_ruid = geteuid();
404 	sblock.e2fs.e2fs_rgid = getegid();
405 
406 	sblock.e2fs.e2fs_first_ino = EXT2_FIRSTINO;
407 	sblock.e2fs.e2fs_inode_size = inodesize;
408 
409 	/* e2fs_block_group_nr is set on writing superblock to each group */
410 
411 	uuid_create(&uuid, &uustat);
412 	if (uustat != uuid_s_ok)
413 		errx(EXIT_FAILURE, "Failed to generate uuid");
414 	uuid_enc_le(sblock.e2fs.e2fs_uuid, &uuid);
415 	if (volname != NULL) {
416 		if (strlen(volname) > sizeof(sblock.e2fs.e2fs_vname))
417 			errx(EXIT_FAILURE, "Volume name is too long");
418 		strlcpy(sblock.e2fs.e2fs_vname, volname,
419 		    sizeof(sblock.e2fs.e2fs_vname));
420 	}
421 
422 	sblock.e2fs.e2fs_fsmnt[0] = '\0';
423 	sblock.e2fs_fsmnt[0] = '\0';
424 
425 	sblock.e2fs.e2fs_algo = 0;		/* XXX unsupported? */
426 	sblock.e2fs.e2fs_prealloc = 0;		/* XXX unsupported? */
427 	sblock.e2fs.e2fs_dir_prealloc = 0;	/* XXX unsupported? */
428 
429 	/* calculate blocks for reserved group descriptors for resize */
430 	sblock.e2fs.e2fs_reserved_ngdb = 0;
431 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
432 	    (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0) {
433 		uint64_t target_blocks;
434 		uint target_ncg, target_ngdb, reserved_ngdb;
435 
436 		/* reserve descriptors for size as 1024 times as current */
437 		target_blocks =
438 		    (sblock.e2fs.e2fs_bcount - sblock.e2fs.e2fs_first_dblock)
439 		    * 1024ULL;
440 		/* number of blocks must be in uint32_t */
441 		if (target_blocks > UINT32_MAX)
442 			target_blocks = UINT32_MAX;
443 		target_ncg = howmany(target_blocks, sblock.e2fs.e2fs_bpg);
444 		target_ngdb = howmany(sizeof(struct ext2_gd) * target_ncg,
445 		    sblock.e2fs_bsize);
446 		/*
447 		 * Reserved group descriptor blocks are preserved as
448 		 * the second level double indirect reference blocks in
449 		 * the EXT2_RESIZEINO inode, so the maximum number of
450 		 * the blocks is EXT2_NINDIR(fs).
451 		 * (see also descriptions in init_resizeino() function)
452 		 *
453 		 * We check a number including current e2fs_ngdb here
454 		 * because they will be moved into reserved gdb on
455 		 * possible future size shrink, though e2fsprogs don't
456 		 * seem to care about it.
457 		 */
458 		if (target_ngdb > EXT2_NINDIR(&sblock))
459 			target_ngdb = EXT2_NINDIR(&sblock);
460 
461 		reserved_ngdb = target_ngdb - sblock.e2fs_ngdb;
462 
463 		/* make sure reserved_ngdb fits in the last cg */
464 		if (reserved_ngdb >= blocks_lastcg - cgoverhead(ncg - 1))
465 			reserved_ngdb = blocks_lastcg - cgoverhead(ncg - 1);
466 		if (reserved_ngdb == 0) {
467 			/* if no space for reserved gdb, disable the feature */
468 			sblock.e2fs.e2fs_features_compat &=
469 			    ~EXT2F_COMPAT_RESIZE;
470 		}
471 		sblock.e2fs.e2fs_reserved_ngdb = reserved_ngdb;
472 	}
473 
474 	/*
475 	 * Initialize group descriptors
476 	 */
477 	gd = malloc(sblock.e2fs_ngdb * bsize);
478 	if (gd == NULL)
479 		errx(EXIT_FAILURE, "Can't allocate descriptors buffer");
480 	memset(gd, 0, sblock.e2fs_ngdb * bsize);
481 
482 	fbcount = 0;
483 	ficount = 0;
484 	for (cylno = 0; cylno < ncg; cylno++) {
485 		uint boffset;
486 
487 		boffset = cgbase(&sblock, cylno);
488 		if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
489 		    (sblock.e2fs.e2fs_features_rocompat &
490 		     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
491 		    cg_has_sb(cylno)) {
492 			boffset += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
493 			if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
494 			    (sblock.e2fs.e2fs_features_compat &
495 			     EXT2F_COMPAT_RESIZE) != 0)
496 				boffset += sblock.e2fs.e2fs_reserved_ngdb;
497 		}
498 		gd[cylno].ext2bgd_b_bitmap = h2fs32(boffset);
499 		boffset += NBLOCK_BLOCK_BITMAP;
500 		gd[cylno].ext2bgd_i_bitmap = h2fs32(boffset);
501 		boffset += NBLOCK_INODE_BITMAP;
502 		gd[cylno].ext2bgd_i_tables = h2fs32(boffset);
503 		if (cylno == (ncg - 1))
504 			gd[cylno].ext2bgd_nbfree = h2fs16(
505 			    blocks_lastcg - cgoverhead(cylno));
506 		else
507 			gd[cylno].ext2bgd_nbfree = h2fs16(
508 			    sblock.e2fs.e2fs_bpg - cgoverhead(cylno));
509 		fbcount += fs2h16(gd[cylno].ext2bgd_nbfree);
510 		if (cylno == 0) {
511 			/* take reserved inodes off nifree */
512 			gd[cylno].ext2bgd_nifree = h2fs16(
513 			    sblock.e2fs.e2fs_ipg-EXT2_RESERVED_INODES);
514 		} else {
515 			gd[cylno].ext2bgd_nifree =
516 			    h2fs16(sblock.e2fs.e2fs_ipg);
517 		}
518 		ficount += fs2h16(gd[cylno].ext2bgd_nifree);
519 		gd[cylno].ext2bgd_ndirs = 0;
520 	}
521 	sblock.e2fs.e2fs_fbcount = fbcount;
522 	sblock.e2fs.e2fs_ficount = ficount;
523 
524 	/*
525 	 * Dump out summary information about file system.
526 	 */
527 	if (verbosity > 0) {
528 		printf("%s: %u.%1uMB (%" PRId64 " sectors) "
529 		    "block size %u, fragment size %u\n",
530 		    fsys,
531 		    (uint)(((uint64_t)bcount * bsize) / (1024 * 1024)),
532 		    (uint)((uint64_t)bcount * bsize -
533 		    rounddown((uint64_t)bcount * bsize, 1024 * 1024))
534 		    / 1024 / 100,
535 		    fssize, bsize, fsize);
536 		printf("\tusing %u block groups of %u.0MB, %u blks, "
537 		    "%u inodes.\n",
538 		    ncg, bsize * sblock.e2fs.e2fs_bpg / (1024 * 1024),
539 		    sblock.e2fs.e2fs_bpg, sblock.e2fs.e2fs_ipg);
540 	}
541 
542 	/*
543 	 * allocate space for superblock and group descriptors
544 	 */
545 	iobufsize = (NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb) * sblock.e2fs_bsize;
546 	iobuf = mmap(0, iobufsize, PROT_READ|PROT_WRITE,
547 	    MAP_ANON|MAP_PRIVATE, -1, 0);
548 	if (iobuf == NULL)
549 		errx(EXIT_FAILURE, "Cannot allocate I/O buffer");
550 	memset(iobuf, 0, iobufsize);
551 
552 	/*
553 	 * We now start writing to the filesystem
554 	 */
555 
556 	if (!Nflag) {
557 		static const uint pbsize[] = { 1024, 2048, 4096, 0 };
558 		uint pblock;
559 		/*
560 		 * Validate the given file system size.
561 		 * Verify that its last block can actually be accessed.
562 		 * Convert to file system fragment sized units.
563 		 */
564 		if (fssize <= 0)
565 			errx(EXIT_FAILURE, "Preposterous size %" PRId64,
566 			    fssize);
567 		wtfs(fssize - 1, sectorsize, iobuf);
568 
569 		/*
570 		 * Ensure there is nothing that looks like a filesystem
571 		 * superblock anywhere other than where ours will be.
572 		 *
573 		 * Ext2fs superblock is always placed at the same SBOFF,
574 		 * so we just zap possible first backups.
575 		 */
576 		for (i = 0; pbsize[i] != 0; i++) {
577  			pblock = (pbsize[i] > BBSIZE) ? 0 : 1;	/* 1st dblk */
578 			pblock += pbsize[i] * NBBY;		/* next bg */
579 			/* zap first backup */
580 			zap_old_sblock(pblock * pbsize[i]);
581 		}
582 		/*
583 		 * Also zap possible FFS magic leftover to prevent
584 		 * kernel vfs_mountroot() and bootloaders from mis-recognizing
585 		 * this file system as FFS.
586 		 */
587 		zap_old_sblock(8192);	/* SBLOCK_UFS1 */
588 		zap_old_sblock(65536);	/* SBLOCK_UFS2 */
589 	}
590 
591 	if (verbosity >= 3)
592 		printf("super-block backups (for fsck_ext2fs -b #) at:\n");
593 	/* If we are printing more than one line of numbers, line up columns */
594 	fld_width = verbosity < 4 ? 1 : snprintf(NULL, 0, "%" PRIu64,
595 	    (uint64_t)cgbase(&sblock, ncg - 1));
596 	/* Get terminal width */
597 	if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) == 0 &&
598 	    winsize.ws_col != 0)
599 		max_cols = winsize.ws_col;
600 	else
601 		max_cols = 80;
602 	if (Nflag && verbosity == 3)
603 		/* Leave space to add " ..." after one row of numbers */
604 		max_cols -= 4;
605 #define BASE 0x10000	/* For some fixed-point maths */
606 	col = 0;
607 	delta = verbosity > 2 ? 0 : max_cols * BASE / ncg;
608 	for (cylno = 0; cylno < ncg; cylno++) {
609 		fflush(stdout);
610 		initcg(cylno);
611 		if (verbosity < 2)
612 			continue;
613 		/* the first one is a master, not backup */
614 		if (cylno == 0)
615 			continue;
616 		/* skip if this cylinder doesn't have a backup */
617 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
618 		    (sblock.e2fs.e2fs_features_rocompat &
619 		     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
620 		    cg_has_sb(cylno) == 0)
621 			continue;
622 
623 		if (delta > 0) {
624 			if (Nflag)
625 				/* No point doing dots for -N */
626 				break;
627 			/* Print dots scaled to end near RH margin */
628 			for (col += delta; col > BASE; col -= BASE)
629 				printf(".");
630 			continue;
631 		}
632 		/* Print superblock numbers */
633 		len = printf("%s%*" PRIu64 ",", (col ? " " : ""), fld_width,
634 		    (uint64_t)cgbase(&sblock, cylno));
635 		col += len;
636 		if (col + len < max_cols)
637 			/* Next number fits */
638 			continue;
639 		/* Next number won't fit, need a newline */
640 		if (verbosity <= 3) {
641 			/* Print dots for subsequent cylinder groups */
642 			delta = sblock.e2fs_ncg - cylno - 1;
643 			if (delta != 0) {
644 				if (Nflag) {
645 					printf(" ...");
646 					break;
647 				}
648 				delta = max_cols * BASE / delta;
649 			}
650 		}
651 		col = 0;
652 		printf("\n");
653 	}
654 #undef BASE
655 	if (col > 0)
656 		printf("\n");
657 	if (Nflag)
658 		return;
659 
660 	/*
661 	 * Now construct the initial file system,
662 	 */
663 	if (fsinit(&tv) == 0)
664 		errx(EXIT_FAILURE, "Error making filesystem");
665 	/*
666 	 * Write out the superblock and group descriptors
667 	 */
668 	sblock.e2fs.e2fs_block_group_nr = 0;
669 	sboff = 0;
670 	if (cgbase(&sblock, 0) == 0) {
671 		/*
672 		 * If the first block contains the boot block sectors,
673 		 * (i.e. in case of sblock.e2fs.e2fs_bsize > BBSIZE)
674 		 * we have to preserve data in it.
675 		 */
676 		sboff = SBOFF;
677 	}
678 	e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
679 	e2fs_cgsave(gd, (struct ext2_gd *)(iobuf + sblock.e2fs_bsize),
680 	   sizeof(struct ext2_gd) * sblock.e2fs_ncg);
681 	wtfs(EXT2_FSBTODB(&sblock, cgbase(&sblock, 0)) + sboff / sectorsize,
682 	    iobufsize - sboff, iobuf + sboff);
683 
684 	munmap(iobuf, iobufsize);
685 }
686 
687 /*
688  * Initialize a cylinder (block) group.
689  */
690 void
691 initcg(uint cylno)
692 {
693 	uint nblcg, i, j, sboff;
694 	struct ext2fs_dinode *dp;
695 
696 	/*
697 	 * Make a copy of the superblock and group descriptors.
698 	 */
699 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
700 	    (sblock.e2fs.e2fs_features_rocompat &
701 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
702 	    cg_has_sb(cylno)) {
703 		sblock.e2fs.e2fs_block_group_nr = cylno;
704 		sboff = 0;
705 		if (cgbase(&sblock, cylno) == 0) {
706 			/* preserve data in bootblock in cg0 */
707 			sboff = SBOFF;
708 		}
709 		e2fs_sbsave(&sblock.e2fs, (struct ext2fs *)(iobuf + sboff));
710 		e2fs_cgsave(gd, (struct ext2_gd *)(iobuf +
711 		    sblock.e2fs_bsize * NBLOCK_SUPERBLOCK),
712 		    sizeof(struct ext2_gd) * sblock.e2fs_ncg);
713 		/* write superblock and group descriptor backups */
714 		wtfs(EXT2_FSBTODB(&sblock, cgbase(&sblock, cylno)) +
715 		    sboff / sectorsize, iobufsize - sboff, iobuf + sboff);
716 	}
717 
718 	/*
719 	 * Initialize block bitmap.
720 	 */
721 	memset(buf, 0, sblock.e2fs_bsize);
722 	if (cylno == (sblock.e2fs_ncg - 1)) {
723 		/* The last group could have less blocks than e2fs_bpg. */
724 		nblcg = sblock.e2fs.e2fs_bcount -
725 		    cgbase(&sblock, sblock.e2fs_ncg - 1);
726 		for (i = nblcg; i < roundup(nblcg, NBBY); i++)
727 			setbit(buf, i);
728 		memset(&buf[i / NBBY], ~0U, sblock.e2fs.e2fs_bpg - i);
729 	}
730 	/* set overhead (superblock, group descriptor etc.) blocks used */
731 	for (i = 0; i < cgoverhead(cylno) / NBBY; i++)
732 		buf[i] = ~0;
733 	i = i * NBBY;
734 	for (; i < cgoverhead(cylno); i++)
735 		setbit(buf, i);
736 	wtfs(EXT2_FSBTODB(&sblock, fs2h32(gd[cylno].ext2bgd_b_bitmap)),
737 	    sblock.e2fs_bsize, buf);
738 
739 	/*
740 	 * Initialize inode bitmap.
741 	 *
742 	 *  Assume e2fs_ipg is a multiple of NBBY since
743 	 *  it's a multiple of e2fs_ipb (as we did above).
744 	 *  Note even (possibly smaller) the last group has the same e2fs_ipg.
745 	 */
746 	i = sblock.e2fs.e2fs_ipg / NBBY;
747 	memset(buf, 0, i);
748 	memset(buf + i, ~0U, sblock.e2fs_bsize - i);
749 	if (cylno == 0) {
750 		/* mark reserved inodes */
751 		for (i = 1; i < EXT2_FIRSTINO; i++)
752 			setbit(buf, EXT2_INO_INDEX(i));
753 	}
754 	wtfs(EXT2_FSBTODB(&sblock, fs2h32(gd[cylno].ext2bgd_i_bitmap)),
755 	    sblock.e2fs_bsize, buf);
756 
757 	/*
758 	 * Initialize inode tables.
759 	 *
760 	 *  Just initialize generation numbers for NFS security.
761 	 *  XXX: sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_valloc() seems
762 	 *       to override these generated numbers.
763 	 */
764 	memset(buf, 0, sblock.e2fs_bsize);
765 	for (i = 0; i < sblock.e2fs_itpg; i++) {
766 		for (j = 0; j < sblock.e2fs_ipb; j++) {
767 			dp = (struct ext2fs_dinode *)(buf + inodesize * j);
768 			/* h2fs32() just for consistency */
769 			dp->e2di_gen = h2fs32(arc4random());
770 		}
771 		wtfs(EXT2_FSBTODB(&sblock, fs2h32(gd[cylno].ext2bgd_i_tables) + i),
772 		    sblock.e2fs_bsize, buf);
773 	}
774 }
775 
776 /*
777  * Zap possible lingering old superblock data
778  */
779 static void
780 zap_old_sblock(int sblkoff)
781 {
782 	static int cg0_data;
783 	uint32_t oldfs[SBSIZE / sizeof(uint32_t)];
784 	static const struct fsm {
785 		uint32_t offset;
786 		uint32_t magic;
787 		uint32_t mask;
788 	} fs_magics[] = {
789 		{offsetof(struct ext2fs, e2fs_magic) / 4, E2FS_MAGIC, 0xffff},
790 		{offsetof(struct ext2fs, e2fs_magic) / 4,
791 		    E2FS_MAGIC << 16, 0xffff0000},
792 		{14, 0xef530000, 0xffff0000},	/* EXT2FS (big) */
793 		{0x55c / 4, 0x00011954, ~0U},	/* FS_UFS1_MAGIC */
794 		{0x55c / 4, 0x19540119, ~0U},	/* FS_UFS2_MAGIC */
795 		{0, 0x70162, ~0U},		/* LFS_MAGIC */
796 		{.offset = ~0U},
797 	};
798 	const struct fsm *fsm;
799 
800 	if (Nflag)
801 		return;
802 
803 	/* don't override data before superblock */
804 	if (sblkoff < SBOFF)
805 		return;
806 
807 	if (cg0_data == 0) {
808 		cg0_data =
809 		    ((daddr_t)sblock.e2fs.e2fs_first_dblock + cgoverhead(0)) *
810 		    sblock.e2fs_bsize;
811 	}
812 
813 	/* Ignore anything that is beyond our filesystem */
814 	if (sblkoff / sectorsize >= fssize)
815 		return;
816 	/* Zero anything inside our filesystem... */
817 	if (sblkoff >= sblock.e2fs.e2fs_first_dblock * bsize) {
818 		/* ...unless we will write that area anyway */
819 		if (sblkoff >= cg0_data)
820 			/* assume iobuf is zero'ed here */
821 			wtfs(sblkoff / sectorsize,
822 			    roundup(SBSIZE, sectorsize), iobuf);
823 		return;
824 	}
825 
826 	/*
827 	 * The sector might contain boot code, so we must validate it
828 	 *
829 	 * XXX: ext2fs won't preserve data after SBOFF,
830 	 *      but first_dblock could have a different value.
831 	 */
832 	rdfs(sblkoff / sectorsize, sizeof(oldfs), &oldfs);
833 	for (fsm = fs_magics;; fsm++) {
834 		uint32_t v;
835 		if (fsm->mask == 0)
836 			return;
837 		v = oldfs[fsm->offset];
838 		if ((v & fsm->mask) == fsm->magic ||
839 		    (bswap32(v) & fsm->mask) == fsm->magic)
840 			break;
841 	}
842 
843 	/* Just zap the magic number */
844 	oldfs[fsm->offset] = 0;
845 	wtfs(sblkoff / sectorsize, sizeof(oldfs), &oldfs);
846 }
847 
848 /*
849  * uint cgoverhead(uint c)
850  *
851  * 	Return a number of reserved blocks on the specified group.
852  * 	XXX: should be shared with src/sbin/fsck_ext2fs/setup.c
853  */
854 uint
855 cgoverhead(uint c)
856 {
857 	uint overh;
858 
859 	overh = NBLOCK_BLOCK_BITMAP + NBLOCK_INODE_BITMAP + sblock.e2fs_itpg;
860 
861 	if (sblock.e2fs.e2fs_rev == E2FS_REV0 ||
862 	    (sblock.e2fs.e2fs_features_rocompat &
863 	     EXT2F_ROCOMPAT_SPARSESUPER) == 0 ||
864 	    cg_has_sb(c) != 0) {
865 		overh += NBLOCK_SUPERBLOCK + sblock.e2fs_ngdb;
866 
867 		if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
868 		    (sblock.e2fs.e2fs_features_compat &
869 		     EXT2F_COMPAT_RESIZE) != 0)
870 			overh += sblock.e2fs.e2fs_reserved_ngdb;
871 	}
872 
873 	return overh;
874 }
875 
876 /*
877  * Initialize the file system
878  */
879 
880 #define LOSTDIR		/* e2fsck complains if there is no lost+found */
881 
882 #define	PREDEFDIR	2
883 
884 #ifdef LOSTDIR
885 #define	PREDEFROOTDIR	(PREDEFDIR + 1)
886 #else
887 #define	PREDEFROOTDIR	PREDEFDIR
888 #endif
889 
890 struct ext2fs_direct root_dir[] = {
891 	{ EXT2_ROOTINO, 0, 1, 0, "." },
892 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
893 #ifdef LOSTDIR
894 	{ EXT2_LOSTFOUNDINO, 0, 10, 0, "lost+found" },
895 #endif
896 };
897 
898 #ifdef LOSTDIR
899 struct ext2fs_direct lost_found_dir[] = {
900 	{ EXT2_LOSTFOUNDINO, 0, 1, 0, "." },
901 	{ EXT2_ROOTINO, 0, 2, 0, ".." },
902 };
903 struct ext2fs_direct pad_dir = { 0, sizeof(struct ext2fs_direct), 0, 0, "" };
904 #endif
905 
906 int
907 fsinit(const struct timeval *tv)
908 {
909 	struct ext2fs_dinode node;
910 #ifdef LOSTDIR
911 	uint i, nblks_lostfound, blk;
912 #endif
913 
914 	/*
915 	 * Initialize the inode for the resizefs feature
916 	 */
917 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
918 	    (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0)
919 		init_resizeino(tv);
920 
921 	/*
922 	 * Initialize the node
923 	 */
924 
925 #ifdef LOSTDIR
926 	/*
927 	 * Create the lost+found directory
928 	 */
929 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
930 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
931 		lost_found_dir[0].e2d_type = EXT2_FT_DIR;
932 		lost_found_dir[1].e2d_type = EXT2_FT_DIR;
933 	}
934 	(void)makedir(lost_found_dir, __arraycount(lost_found_dir));
935 
936 	/* prepare a bit large directory for preserved files */
937 	nblks_lostfound = EXT2_LOSTFOUNDSIZE / sblock.e2fs_bsize;
938 	/* ...but only with direct blocks */
939 	if (nblks_lostfound > EXT2FS_NDADDR)
940 		nblks_lostfound = EXT2FS_NDADDR;
941 
942 	memset(&node, 0, sizeof(node));
943 	node.e2di_mode = EXT2_IFDIR | EXT2_LOSTFOUNDUMASK;
944 	node.e2di_uid = geteuid();
945 	node.e2di_size = sblock.e2fs_bsize * nblks_lostfound;
946 	node.e2di_atime = tv->tv_sec;
947 	node.e2di_ctime = tv->tv_sec;
948 	node.e2di_mtime = tv->tv_sec;
949 	node.e2di_gid = getegid();
950 	node.e2di_nlink = PREDEFDIR;
951 	/* e2di_nblock is a number of disk blocks, not ext2fs blocks */
952 	node.e2di_nblock = EXT2_FSBTODB(&sblock, nblks_lostfound);
953 	node.e2di_blocks[0] = alloc(sblock.e2fs_bsize, node.e2di_mode);
954 	if (node.e2di_blocks[0] == 0) {
955 		printf("%s: can't allocate block for lost+found\n", __func__);
956 		return 0;
957 	}
958 	for (i = 1; i < nblks_lostfound; i++) {
959 		blk = alloc(sblock.e2fs_bsize, 0);
960 		if (blk == 0) {
961 			printf("%s: can't allocate blocks for lost+found\n",
962 			    __func__);
963 			return 0;
964 		}
965 		node.e2di_blocks[i] = blk;
966 	}
967 	wtfs(EXT2_FSBTODB(&sblock, node.e2di_blocks[0]),
968 	    sblock.e2fs_bsize, buf);
969 	pad_dir.e2d_reclen = sblock.e2fs_bsize;
970 	for (i = 1; i < nblks_lostfound; i++) {
971 		memset(buf, 0, sblock.e2fs_bsize);
972 		copy_dir(&pad_dir, (struct ext2fs_direct *)buf);
973 		wtfs(EXT2_FSBTODB(&sblock, node.e2di_blocks[i]),
974 		    sblock.e2fs_bsize, buf);
975 	}
976 	iput(&node, EXT2_LOSTFOUNDINO);
977 #endif
978 	/*
979 	 * create the root directory
980 	 */
981 	memset(&node, 0, sizeof(node));
982 	if (sblock.e2fs.e2fs_rev > E2FS_REV0 &&
983 	    sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) {
984 		root_dir[0].e2d_type = EXT2_FT_DIR;
985 		root_dir[1].e2d_type = EXT2_FT_DIR;
986 #ifdef LOSTDIR
987 		root_dir[2].e2d_type = EXT2_FT_DIR;
988 #endif
989 	}
990 	node.e2di_mode = EXT2_IFDIR | EXT2_UMASK;
991 	node.e2di_uid = geteuid();
992 	node.e2di_size = makedir(root_dir, __arraycount(root_dir));
993 	node.e2di_atime = tv->tv_sec;
994 	node.e2di_ctime = tv->tv_sec;
995 	node.e2di_mtime = tv->tv_sec;
996 	node.e2di_gid = getegid();
997 	node.e2di_nlink = PREDEFROOTDIR;
998 	/* e2di_nblock is a number of disk block, not ext2fs block */
999 	node.e2di_nblock = EXT2_FSBTODB(&sblock, 1);
1000 	node.e2di_blocks[0] = alloc(node.e2di_size, node.e2di_mode);
1001 	if (node.e2di_blocks[0] == 0) {
1002 		printf("%s: can't allocate block for root dir\n", __func__);
1003 		return 0;
1004 	}
1005 	wtfs(EXT2_FSBTODB(&sblock, node.e2di_blocks[0]),
1006 	    sblock.e2fs_bsize, buf);
1007 	iput(&node, EXT2_ROOTINO);
1008 	return 1;
1009 }
1010 
1011 /*
1012  * Construct a set of directory entries in "buf".
1013  * return size of directory.
1014  */
1015 int
1016 makedir(struct ext2fs_direct *protodir, int entries)
1017 {
1018 	uint8_t *cp;
1019 	uint i, spcleft;
1020 	uint dirblksiz;
1021 
1022 	dirblksiz = sblock.e2fs_bsize;
1023 	memset(buf, 0, dirblksiz);
1024 	spcleft = dirblksiz;
1025 	for (cp = buf, i = 0; i < entries - 1; i++) {
1026 		protodir[i].e2d_reclen = EXT2FS_DIRSIZ(protodir[i].e2d_namlen);
1027 		copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1028 		cp += protodir[i].e2d_reclen;
1029 		spcleft -= protodir[i].e2d_reclen;
1030 	}
1031 	protodir[i].e2d_reclen = spcleft;
1032 	copy_dir(&protodir[i], (struct ext2fs_direct *)cp);
1033 	return dirblksiz;
1034 }
1035 
1036 /*
1037  * Copy a direntry to a buffer, in fs byte order
1038  */
1039 static void
1040 copy_dir(struct ext2fs_direct *dir, struct ext2fs_direct *dbuf)
1041 {
1042 
1043 	memcpy(dbuf, dir, EXT2FS_DIRSIZ(dir->e2d_namlen));
1044 	dbuf->e2d_ino = h2fs32(dir->e2d_ino);
1045 	dbuf->e2d_reclen = h2fs16(dir->e2d_reclen);
1046 }
1047 
1048 /*
1049  * void init_resizeino(const struct timeval *tv);
1050  *
1051  *	Initialize the EXT2_RESEIZE_INO inode to preserve
1052  *	reserved group descriptor blocks for future growth of this ext2fs.
1053  */
1054 void
1055 init_resizeino(const struct timeval *tv)
1056 {
1057 	struct ext2fs_dinode node;
1058 	uint64_t isize;
1059 	uint32_t *dindir_block, *reserved_gdb;
1060 	uint nblock, i, cylno, n;
1061 
1062 	memset(&node, 0, sizeof(node));
1063 
1064 	/*
1065 	 * Note this function only prepares required structures for
1066 	 * future resize. It's a quite different work to implement
1067 	 * a utility like resize_ext2fs(8) which handles actual
1068 	 * resize ops even on offline.
1069 	 *
1070 	 * Anyway, I'm not sure if there is any documentation about
1071 	 * this resize ext2fs feature and related data structures,
1072 	 * and I've written this function based on things what I see
1073 	 * on some existing implementation and real file system data
1074 	 * created by existing tools. To be honest, they are not
1075 	 * so easy to read, so I will try to implement it here without
1076 	 * any dumb optimization for people who would eventually
1077 	 * work on "yet another wheel" like resize_ext2fs(8).
1078 	 */
1079 
1080 	/*
1081 	 * I'm not sure what type is appropriate for this inode.
1082 	 * The release notes of e2fsprogs says they changed e2fsck to allow
1083 	 * IFREG for RESIZEINO since a certain resize tool used it. Hmm.
1084 	 */
1085 	node.e2di_mode = EXT2_IFREG | EXT2_RESIZEINOUMASK;
1086 	node.e2di_uid = geteuid();
1087 	node.e2di_atime = tv->tv_sec;
1088 	node.e2di_ctime = tv->tv_sec;
1089 	node.e2di_mtime = tv->tv_sec;
1090 	node.e2di_gid = getegid();
1091 	node.e2di_nlink = 1;
1092 
1093 	/*
1094 	 * To preserve the reserved group descriptor blocks,
1095 	 * EXT2_RESIZEINO uses only double indirect reference
1096 	 * blocks in its inode entries.
1097 	 *
1098 	 * All entries for direct, single indirect and triple
1099 	 * indirect references are left zero'ed. Maybe it's safe
1100 	 * because no write operation will happen with this inode.
1101 	 *
1102 	 * We have to allocate a block for the first level double
1103 	 * indirect reference block. Indexes of inode entries in
1104 	 * this first level dindirect block are corresponding to
1105 	 * indexes of group descriptors including both used (e2fs_ngdb)
1106 	 * and reserved (e2fs_reserved_ngdb) group descriptor blocks.
1107 	 *
1108 	 * Inode entries of indexes for used (e2fs_ngdb) descriptors are
1109 	 * left zero'ed. Entries for reserved (e2fs_reserved_ngdb) ones
1110 	 * have block numbers of actual reserved group descriptors
1111 	 * allocated at block group zero. This means e2fs_reserved_ngdb
1112 	 * blocks are reserved as the second level dindirect reference
1113 	 * blocks, and they actually contain block numbers of indirect
1114 	 * references. It may be safe since they don't have to keep any
1115 	 * data yet.
1116 	 *
1117 	 * Each these second dindirect blocks (i.e. reserved group
1118 	 * descriptor blocks in the first block group) should have
1119 	 * block numbers of its backups in all other block groups.
1120 	 * I.e. reserved_ngdb[0] block in block group 0 contains block
1121 	 * numbers of resreved_ngdb[0] from group 1 through (e2fs_ncg - 1).
1122 	 * The number of backups can be determined by the
1123 	 * EXT2_ROCOMPAT_SPARSESUPER feature and cg_has_sb() macro
1124 	 * as done in the above initcg() function.
1125 	 */
1126 
1127 	/* set e2di_size which occupies whole blocks through DINDIR blocks */
1128 	isize = (uint64_t)sblock.e2fs_bsize * EXT2FS_NDADDR +
1129 	    (uint64_t)sblock.e2fs_bsize * EXT2_NINDIR(&sblock) +
1130 	    (uint64_t)sblock.e2fs_bsize * EXT2_NINDIR(&sblock) *
1131 	    EXT2_NINDIR(&sblock);
1132 	if (isize > UINT32_MAX &&
1133 	    (sblock.e2fs.e2fs_features_rocompat &
1134 	     EXT2F_ROCOMPAT_LARGEFILE) == 0) {
1135 		/* XXX should enable it here and update all backups? */
1136 		errx(EXIT_FAILURE, "%s: large_file rocompat feature is "
1137 		    "required to enable resize feature for this filesystem",
1138 		    __func__);
1139 	}
1140 	/* upper 32bit is stored into e2di_size_high on REV1 feature */
1141 	node.e2di_size 	    = isize & UINT32_MAX;
1142 	node.e2di_size_high = isize >> 32;
1143 
1144 #define SINGLE	0	/* index of single indirect block */
1145 #define DOUBLE	1	/* index of double indirect block */
1146 #define TRIPLE	2	/* index of triple indirect block */
1147 
1148 	/* zero out entries for direct references */
1149 	for (i = 0; i < EXT2FS_NDADDR; i++)
1150 		node.e2di_blocks[i] = 0;
1151 	/* also zero out entries for single and triple indirect references */
1152 	node.e2di_blocks[EXT2FS_NDADDR + SINGLE] = 0;
1153 	node.e2di_blocks[EXT2FS_NDADDR + TRIPLE] = 0;
1154 
1155 	/* allocate a block for the first level double indirect reference */
1156 	node.e2di_blocks[EXT2FS_NDADDR + DOUBLE] =
1157 	    alloc(sblock.e2fs_bsize, node.e2di_mode);
1158 	if (node.e2di_blocks[EXT2FS_NDADDR + DOUBLE] == 0)
1159 		errx(EXIT_FAILURE, "%s: Can't allocate a dindirect block",
1160 		    __func__);
1161 
1162 	/* account this first block */
1163 	nblock = EXT2_FSBTODB(&sblock, 1);
1164 
1165 	/* allocate buffer to set data in the dindirect block */
1166 	dindir_block = malloc(sblock.e2fs_bsize);
1167 	if (dindir_block == NULL)
1168 		errx(EXIT_FAILURE,
1169 		    "%s: Can't allocate buffer for a dindirect block",
1170 		    __func__);
1171 
1172 	/* allocate buffer to set data in the group descriptor blocks */
1173 	reserved_gdb = malloc(sblock.e2fs_bsize);
1174 	if (reserved_gdb == NULL)
1175 		errx(EXIT_FAILURE,
1176 		    "%s: Can't allocate buffer for group descriptor blocks",
1177 		    __func__);
1178 
1179 	/*
1180 	 * Setup block entries in the first level dindirect blocks
1181 	 */
1182 	for (i = 0; i < sblock.e2fs_ngdb; i++) {
1183 		/* no need to handle used group descriptor blocks */
1184 		dindir_block[i] = 0;
1185 	}
1186 	for (; i < sblock.e2fs_ngdb + sblock.e2fs.e2fs_reserved_ngdb; i++) {
1187 		/*
1188 		 * point reserved group descriptor block in the first
1189 		 * (i.e. master) block group
1190 		 *
1191 		 * XXX: e2fsprogs seem to use "(i % EXT2_NINDIR(&sblock))" here
1192 		 *      to store maximum EXT2_NINDIR(&sblock) reserved gdbs.
1193 		 *      I'm not sure what will be done on future filesystem
1194 		 *      shrink in that case on their way.
1195 		 */
1196 		if (i >= EXT2_NINDIR(&sblock))
1197 			errx(EXIT_FAILURE, "%s: too many reserved "
1198 			    "group descriptors (%u) for resize inode",
1199 			    __func__, sblock.e2fs.e2fs_reserved_ngdb);
1200 		dindir_block[i] =
1201 		    h2fs32(cgbase(&sblock, 0) + NBLOCK_SUPERBLOCK + i);
1202 
1203 		/*
1204 		 * Setup block entries in the second dindirect blocks
1205 		 * (which are primary reserved group descriptor blocks)
1206 		 * to point their backups.
1207 		 */
1208 		for (n = 0, cylno = 1; cylno < sblock.e2fs_ncg; cylno++) {
1209 			/* skip block groups without backup */
1210 			if ((sblock.e2fs.e2fs_features_rocompat &
1211 			     EXT2F_ROCOMPAT_SPARSESUPER) != 0 &&
1212 			    cg_has_sb(cylno) == 0)
1213 				continue;
1214 
1215 			if (n >= EXT2_NINDIR(&sblock))
1216 				errx(EXIT_FAILURE, "%s: too many block groups "
1217 				    "for the resize feature", __func__);
1218 			/*
1219 			 * These blocks are already reserved in
1220 			 * initcg() so no need to use alloc() here.
1221 			 */
1222 			reserved_gdb[n++] = h2fs32(cgbase(&sblock, cylno) +
1223 			    NBLOCK_SUPERBLOCK + i);
1224 			nblock += EXT2_FSBTODB(&sblock, 1);
1225 		}
1226 		for (; n < EXT2_NINDIR(&sblock); n++)
1227 			reserved_gdb[n] = 0;
1228 
1229 		/* write group descriptor block as the second dindirect refs */
1230 		wtfs(EXT2_FSBTODB(&sblock, fs2h32(dindir_block[i])),
1231 		    sblock.e2fs_bsize, reserved_gdb);
1232 		nblock += EXT2_FSBTODB(&sblock, 1);
1233 	}
1234 	for (; i < EXT2_NINDIR(&sblock); i++) {
1235 		/* leave trailing entries unallocated */
1236 		dindir_block[i] = 0;
1237 	}
1238 	free(reserved_gdb);
1239 
1240 	/* finally write the first level dindirect block */
1241 	wtfs(EXT2_FSBTODB(&sblock, node.e2di_blocks[EXT2FS_NDADDR + DOUBLE]),
1242 	    sblock.e2fs_bsize, dindir_block);
1243 	free(dindir_block);
1244 
1245 	node.e2di_nblock = nblock;
1246 	iput(&node, EXT2_RESIZEINO);
1247 }
1248 
1249 /*
1250  * uint32_t alloc(uint32_t size, uint16_t mode)
1251  *
1252  *	Allocate a block (from cylinder group 0)
1253  *	Reference: src/sys/ufs/ext2fs/ext2fs_alloc.c:ext2fs_alloccg()
1254  */
1255 uint32_t
1256 alloc(uint32_t size, uint16_t mode)
1257 {
1258 	uint32_t loc, bno;
1259 	uint8_t *bbp;
1260 	uint len, map, i;
1261 
1262 	if (gd[0].ext2bgd_nbfree == 0)
1263 		return 0;
1264 
1265 	if (size > sblock.e2fs_bsize)
1266 		return 0;
1267 
1268 	bbp = malloc(sblock.e2fs_bsize);
1269 	if (bbp == NULL)
1270 		return 0;
1271 	rdfs(EXT2_FSBTODB(&sblock, fs2h32(gd[0].ext2bgd_b_bitmap)),
1272 	    sblock.e2fs_bsize, bbp);
1273 
1274 	/* XXX: kernel uses e2fs_fpg here */
1275 	len = sblock.e2fs.e2fs_bpg / NBBY;
1276 
1277 #if 0	/* no need block allocation for root or lost+found dir */
1278 	for (loc = 0; loc < len; loc++) {
1279 		if (bbp[loc] == 0) {
1280 			bno = loc * NBBY;
1281 			goto gotit;
1282 		}
1283 	}
1284 #endif
1285 
1286 	loc = skpc(~0U, len, bbp);
1287 	if (loc == 0) {
1288 		free(bbp);
1289 		return 0;
1290 	}
1291 	loc = len - loc;
1292 	map = bbp[loc];
1293 	bno = loc * NBBY;
1294 	for (i = 0; i < NBBY; i++, bno++) {
1295 		if ((map & (1 << i)) == 0)
1296 			goto gotit;
1297 	}
1298 	free(bbp);
1299 	return 0;
1300 
1301  gotit:
1302 	if (isset(bbp, bno))
1303 		errx(EXIT_FAILURE, "%s: inconsistent bitmap", __func__);
1304 
1305 	setbit(bbp, bno);
1306 	wtfs(EXT2_FSBTODB(&sblock, fs2h32(gd[0].ext2bgd_b_bitmap)),
1307 	    sblock.e2fs_bsize, bbp);
1308 	free(bbp);
1309 	/* XXX: modified group descriptors won't be written into backups */
1310 	gd[0].ext2bgd_nbfree = h2fs16(fs2h16(gd[0].ext2bgd_nbfree)-1);
1311 	if ((mode & EXT2_IFDIR) != 0)
1312 		gd[0].ext2bgd_ndirs = h2fs16(fs2h16(gd[0].ext2bgd_ndirs)+1);
1313 	sblock.e2fs.e2fs_fbcount--;
1314 
1315 	return sblock.e2fs.e2fs_first_dblock + bno;
1316 }
1317 
1318 /*
1319  * void iput(struct ext2fs_dinode *ip, ino_t ino)
1320  *
1321  *	Put an inode entry into the corresponding table.
1322  */
1323 static void
1324 iput(struct ext2fs_dinode *ip, ino_t ino)
1325 {
1326 	daddr_t d;
1327 	uint c, i;
1328 	struct ext2fs_dinode *dp;
1329 	uint8_t *bp;
1330 
1331 	bp = malloc(sblock.e2fs_bsize);
1332 	if (bp == NULL)
1333 		errx(EXIT_FAILURE, "%s: can't allocate buffer for inode",
1334 		    __func__);
1335 
1336 	/*
1337 	 * Reserved inodes are allocated and accounted in initcg()
1338 	 * so skip checks of the bitmap and allocation for them.
1339 	 */
1340 	if (ino >= EXT2_FIRSTINO) {
1341 		c = ino_to_cg(&sblock, ino);
1342 
1343 		/* sanity check */
1344 		if (gd[c].ext2bgd_nifree == 0)
1345 			errx(EXIT_FAILURE,
1346 			    "%s: no free inode %" PRIu64 " in block group %u",
1347 			    __func__, (uint64_t)ino, c);
1348 
1349 		/* update inode bitmap */
1350 		rdfs(EXT2_FSBTODB(&sblock, fs2h32(gd[0].ext2bgd_i_bitmap)),
1351 		    sblock.e2fs_bsize, bp);
1352 
1353 		/* more sanity */
1354 		if (isset(bp, EXT2_INO_INDEX(ino)))
1355 			errx(EXIT_FAILURE, "%s: inode %" PRIu64
1356 			    " already in use", __func__, (uint64_t)ino);
1357 		setbit(bp, EXT2_INO_INDEX(ino));
1358 		wtfs(EXT2_FSBTODB(&sblock, fs2h32(gd[0].ext2bgd_i_bitmap)),
1359 		    sblock.e2fs_bsize, bp);
1360 		gd[c].ext2bgd_nifree = h2fs16(fs2h16(gd[c].ext2bgd_nifree)-1);
1361 		sblock.e2fs.e2fs_ficount--;
1362 	}
1363 
1364 	if (ino >= sblock.e2fs.e2fs_ipg * sblock.e2fs_ncg)
1365 		errx(EXIT_FAILURE, "%s: inode value out of range (%" PRIu64
1366 		    ")", __func__, (uint64_t)ino);
1367 
1368 	/* update an inode entry in the table */
1369 	d = EXT2_FSBTODB(&sblock, ino_to_fsba(&sblock, ino));
1370 	rdfs(d, sblock.e2fs_bsize, bp);
1371 
1372 	dp = (struct ext2fs_dinode *)(bp +
1373 	    inodesize * ino_to_fsbo(&sblock, ino));
1374 	e2fs_isave(ip, dp, EXT2_DINODE_SIZE(&sblock));
1375 	/* e2fs_i_bswap() doesn't swap e2di_blocks addrs */
1376 	if ((ip->e2di_mode & EXT2_IFMT) != EXT2_IFLNK) {
1377 		for (i = 0; i < EXT2FS_NDADDR + EXT2FS_NIADDR; i++)
1378 			dp->e2di_blocks[i] = h2fs32(ip->e2di_blocks[i]);
1379 	}
1380 	/* h2fs32() just for consistency */
1381 	dp->e2di_gen = h2fs32(arc4random());
1382 
1383 	wtfs(d, sblock.e2fs_bsize, bp);
1384 	free(bp);
1385 }
1386 
1387 /*
1388  * Read a block from the file system
1389  */
1390 void
1391 rdfs(daddr_t bno, int size, void *bf)
1392 {
1393 	int n;
1394 	off_t offset;
1395 
1396 	offset = bno;
1397 	n = pread(fsi, bf, size, offset * sectorsize);
1398 	if (n != size)
1399 		err(EXIT_FAILURE, "%s: read error for sector %" PRId64,
1400 		    __func__, (int64_t)bno);
1401 }
1402 
1403 /*
1404  * Write a block to the file system
1405  */
1406 void
1407 wtfs(daddr_t bno, int size, void *bf)
1408 {
1409 	int n;
1410 	off_t offset;
1411 
1412 	if (Nflag)
1413 		return;
1414 	offset = bno;
1415 	n = pwrite(fso, bf, size, offset * sectorsize);
1416 	if (n != size)
1417 		err(EXIT_FAILURE, "%s: write error for sector %" PRId64,
1418 		    __func__, (int64_t)bno);
1419 }
1420 
1421 int
1422 ilog2(uint val)
1423 {
1424 
1425 	if (val == 0 || !powerof2(val))
1426 		errx(EXIT_FAILURE, "%s: %u is not a power of 2",
1427 		    __func__, val);
1428 
1429 	return ffs(val) - 1;
1430 }
1431 
1432 /*
1433  * int skpc(int mask, size_t size, uint8_t *cp)
1434  *
1435  *	Locate an unsigned character of value mask inside cp[].
1436  * 	(from src/sys/lib/libkern/skpc.c)
1437  */
1438 int
1439 skpc(int mask, size_t size, uint8_t *cp)
1440 {
1441 	uint8_t *end;
1442 
1443 	end = &cp[size];
1444 	while (cp < end && *cp == (uint8_t)mask)
1445 		cp++;
1446 
1447 	return end - cp;
1448 }
1449