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