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