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