xref: /freebsd/sys/fs/ext2fs/ext2_alloc.c (revision e95923a2288fb2845c7be4822b1b92b2fc106d18)
1 /*-
2  *  modified for Lites 1.1
3  *
4  *  Aug 1995, Godmar Back (gback@cs.utah.edu)
5  *  University of Utah, Department of Computer Science
6  */
7 /*-
8  * SPDX-License-Identifier: BSD-3-Clause
9  *
10  * Copyright (c) 1982, 1986, 1989, 1993
11  *	The Regents of the University of California.  All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)ffs_alloc.c	8.8 (Berkeley) 2/21/94
38  * $FreeBSD$
39  */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/conf.h>
44 #include <sys/vnode.h>
45 #include <sys/stat.h>
46 #include <sys/mount.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 #include <sys/buf.h>
50 #include <sys/endian.h>
51 
52 #include <fs/ext2fs/fs.h>
53 #include <fs/ext2fs/inode.h>
54 #include <fs/ext2fs/ext2_mount.h>
55 #include <fs/ext2fs/ext2fs.h>
56 #include <fs/ext2fs/ext2_extern.h>
57 
58 static daddr_t	ext2_alloccg(struct inode *, int, daddr_t, int);
59 static daddr_t	ext2_clusteralloc(struct inode *, int, daddr_t, int);
60 static u_long	ext2_dirpref(struct inode *);
61 static e4fs_daddr_t ext2_hashalloc(struct inode *, int, long, int,
62     daddr_t (*)(struct inode *, int, daddr_t,
63 						int));
64 static daddr_t	ext2_nodealloccg(struct inode *, int, daddr_t, int);
65 static daddr_t  ext2_mapsearch(struct m_ext2fs *, char *, daddr_t);
66 
67 /*
68  * Allocate a block in the filesystem.
69  *
70  * A preference may be optionally specified. If a preference is given
71  * the following hierarchy is used to allocate a block:
72  *   1) allocate the requested block.
73  *   2) allocate a rotationally optimal block in the same cylinder.
74  *   3) allocate a block in the same cylinder group.
75  *   4) quadradically rehash into other cylinder groups, until an
76  *        available block is located.
77  * If no block preference is given the following hierarchy is used
78  * to allocate a block:
79  *   1) allocate a block in the cylinder group that contains the
80  *        inode for the file.
81  *   2) quadradically rehash into other cylinder groups, until an
82  *        available block is located.
83  */
84 int
85 ext2_alloc(struct inode *ip, daddr_t lbn, e4fs_daddr_t bpref, int size,
86     struct ucred *cred, e4fs_daddr_t *bnp)
87 {
88 	struct m_ext2fs *fs;
89 	struct ext2mount *ump;
90 	e4fs_daddr_t bno;
91 	int cg;
92 
93 	*bnp = 0;
94 	fs = ip->i_e2fs;
95 	ump = ip->i_ump;
96 	mtx_assert(EXT2_MTX(ump), MA_OWNED);
97 #ifdef INVARIANTS
98 	if ((u_int)size > fs->e2fs_bsize || blkoff(fs, size) != 0) {
99 		vn_printf(ip->i_devvp, "bsize = %lu, size = %d, fs = %s\n",
100 		    (long unsigned int)fs->e2fs_bsize, size, fs->e2fs_fsmnt);
101 		panic("ext2_alloc: bad size");
102 	}
103 	if (cred == NOCRED)
104 		panic("ext2_alloc: missing credential");
105 #endif		/* INVARIANTS */
106 	if (size == fs->e2fs_bsize && fs->e2fs_fbcount == 0)
107 		goto nospace;
108 	if (cred->cr_uid != 0 &&
109 	    fs->e2fs_fbcount < fs->e2fs_rbcount)
110 		goto nospace;
111 	if (bpref >= fs->e2fs_bcount)
112 		bpref = 0;
113 	if (bpref == 0)
114 		cg = ino_to_cg(fs, ip->i_number);
115 	else
116 		cg = dtog(fs, bpref);
117 	bno = (daddr_t)ext2_hashalloc(ip, cg, bpref, fs->e2fs_bsize,
118 	    ext2_alloccg);
119 	if (bno > 0) {
120 		/* set next_alloc fields as done in block_getblk */
121 		ip->i_next_alloc_block = lbn;
122 		ip->i_next_alloc_goal = bno;
123 
124 		ip->i_blocks += btodb(fs->e2fs_bsize);
125 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
126 		*bnp = bno;
127 		return (0);
128 	}
129 nospace:
130 	EXT2_UNLOCK(ump);
131 	ext2_fserr(fs, cred->cr_uid, "filesystem full");
132 	uprintf("\n%s: write failed, filesystem is full\n", fs->e2fs_fsmnt);
133 	return (ENOSPC);
134 }
135 
136 /*
137  * Allocate EA's block for inode.
138  */
139 e4fs_daddr_t
140 ext2_alloc_meta(struct inode *ip)
141 {
142 	struct m_ext2fs *fs;
143 	daddr_t blk;
144 
145 	fs = ip->i_e2fs;
146 
147 	EXT2_LOCK(ip->i_ump);
148 	blk = ext2_hashalloc(ip, ino_to_cg(fs, ip->i_number), 0, fs->e2fs_bsize,
149 	    ext2_alloccg);
150 	if (0 == blk)
151 		EXT2_UNLOCK(ip->i_ump);
152 
153 	return (blk);
154 }
155 
156 /*
157  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
158  *
159  * The vnode and an array of buffer pointers for a range of sequential
160  * logical blocks to be made contiguous is given. The allocator attempts
161  * to find a range of sequential blocks starting as close as possible to
162  * an fs_rotdelay offset from the end of the allocation for the logical
163  * block immediately preceding the current range. If successful, the
164  * physical block numbers in the buffer pointers and in the inode are
165  * changed to reflect the new allocation. If unsuccessful, the allocation
166  * is left unchanged. The success in doing the reallocation is returned.
167  * Note that the error return is not reflected back to the user. Rather
168  * the previous block allocation will be used.
169  */
170 
171 static SYSCTL_NODE(_vfs, OID_AUTO, ext2fs, CTLFLAG_RW, 0, "EXT2FS filesystem");
172 
173 static int doasyncfree = 1;
174 
175 SYSCTL_INT(_vfs_ext2fs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
176     "Use asychronous writes to update block pointers when freeing blocks");
177 
178 static int doreallocblks = 0;
179 
180 SYSCTL_INT(_vfs_ext2fs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
181 
182 int
183 ext2_reallocblks(struct vop_reallocblks_args *ap)
184 {
185 	struct m_ext2fs *fs;
186 	struct inode *ip;
187 	struct vnode *vp;
188 	struct buf *sbp, *ebp;
189 	uint32_t *bap, *sbap, *ebap;
190 	struct ext2mount *ump;
191 	struct cluster_save *buflist;
192 	struct indir start_ap[EXT2_NIADDR + 1], end_ap[EXT2_NIADDR + 1], *idp;
193 	e2fs_lbn_t start_lbn, end_lbn;
194 	int soff;
195 	e2fs_daddr_t newblk, blkno;
196 	int i, len, start_lvl, end_lvl, pref, ssize;
197 
198 	if (doreallocblks == 0)
199 		return (ENOSPC);
200 
201 	vp = ap->a_vp;
202 	ip = VTOI(vp);
203 	fs = ip->i_e2fs;
204 	ump = ip->i_ump;
205 
206 	if (fs->e2fs_contigsumsize <= 0 || ip->i_flag & IN_E4EXTENTS)
207 		return (ENOSPC);
208 
209 	buflist = ap->a_buflist;
210 	len = buflist->bs_nchildren;
211 	start_lbn = buflist->bs_children[0]->b_lblkno;
212 	end_lbn = start_lbn + len - 1;
213 #ifdef INVARIANTS
214 	for (i = 1; i < len; i++)
215 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
216 			panic("ext2_reallocblks: non-cluster");
217 #endif
218 	/*
219 	 * If the cluster crosses the boundary for the first indirect
220 	 * block, leave space for the indirect block. Indirect blocks
221 	 * are initially laid out in a position after the last direct
222 	 * block. Block reallocation would usually destroy locality by
223 	 * moving the indirect block out of the way to make room for
224 	 * data blocks if we didn't compensate here. We should also do
225 	 * this for other indirect block boundaries, but it is only
226 	 * important for the first one.
227 	 */
228 	if (start_lbn < EXT2_NDADDR && end_lbn >= EXT2_NDADDR)
229 		return (ENOSPC);
230 	/*
231 	 * If the latest allocation is in a new cylinder group, assume that
232 	 * the filesystem has decided to move and do not force it back to
233 	 * the previous cylinder group.
234 	 */
235 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
236 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
237 		return (ENOSPC);
238 	if (ext2_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
239 	    ext2_getlbns(vp, end_lbn, end_ap, &end_lvl))
240 		return (ENOSPC);
241 	/*
242 	 * Get the starting offset and block map for the first block.
243 	 */
244 	if (start_lvl == 0) {
245 		sbap = &ip->i_db[0];
246 		soff = start_lbn;
247 	} else {
248 		idp = &start_ap[start_lvl - 1];
249 		if (bread(vp, idp->in_lbn, (int)fs->e2fs_bsize, NOCRED, &sbp)) {
250 			brelse(sbp);
251 			return (ENOSPC);
252 		}
253 		sbap = (u_int *)sbp->b_data;
254 		soff = idp->in_off;
255 	}
256 	/*
257 	 * If the block range spans two block maps, get the second map.
258 	 */
259 	ebap = NULL;
260 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
261 		ssize = len;
262 	} else {
263 #ifdef INVARIANTS
264 		if (start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
265 			panic("ext2_reallocblks: start == end");
266 #endif
267 		ssize = len - (idp->in_off + 1);
268 		if (bread(vp, idp->in_lbn, (int)fs->e2fs_bsize, NOCRED, &ebp))
269 			goto fail;
270 		ebap = (u_int *)ebp->b_data;
271 	}
272 	/*
273 	 * Find the preferred location for the cluster.
274 	 */
275 	EXT2_LOCK(ump);
276 	pref = ext2_blkpref(ip, start_lbn, soff, sbap, 0);
277 	/*
278 	 * Search the block map looking for an allocation of the desired size.
279 	 */
280 	if ((newblk = (e2fs_daddr_t)ext2_hashalloc(ip, dtog(fs, pref), pref,
281 	    len, ext2_clusteralloc)) == 0) {
282 		EXT2_UNLOCK(ump);
283 		goto fail;
284 	}
285 	/*
286 	 * We have found a new contiguous block.
287 	 *
288 	 * First we have to replace the old block pointers with the new
289 	 * block pointers in the inode and indirect blocks associated
290 	 * with the file.
291 	 */
292 #ifdef DEBUG
293 	printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
294 	    (uintmax_t)ip->i_number, (intmax_t)start_lbn, (intmax_t)end_lbn);
295 #endif	/* DEBUG */
296 	blkno = newblk;
297 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->e2fs_fpb) {
298 		if (i == ssize) {
299 			bap = ebap;
300 			soff = -i;
301 		}
302 #ifdef INVARIANTS
303 		if (buflist->bs_children[i]->b_blkno != fsbtodb(fs, *bap))
304 			panic("ext2_reallocblks: alloc mismatch");
305 #endif
306 #ifdef DEBUG
307 		printf(" %d,", *bap);
308 #endif	/* DEBUG */
309 		*bap++ = blkno;
310 	}
311 	/*
312 	 * Next we must write out the modified inode and indirect blocks.
313 	 * For strict correctness, the writes should be synchronous since
314 	 * the old block values may have been written to disk. In practise
315 	 * they are almost never written, but if we are concerned about
316 	 * strict correctness, the `doasyncfree' flag should be set to zero.
317 	 *
318 	 * The test on `doasyncfree' should be changed to test a flag
319 	 * that shows whether the associated buffers and inodes have
320 	 * been written. The flag should be set when the cluster is
321 	 * started and cleared whenever the buffer or inode is flushed.
322 	 * We can then check below to see if it is set, and do the
323 	 * synchronous write only when it has been cleared.
324 	 */
325 	if (sbap != &ip->i_db[0]) {
326 		if (doasyncfree)
327 			bdwrite(sbp);
328 		else
329 			bwrite(sbp);
330 	} else {
331 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
332 		if (!doasyncfree)
333 			ext2_update(vp, 1);
334 	}
335 	if (ssize < len) {
336 		if (doasyncfree)
337 			bdwrite(ebp);
338 		else
339 			bwrite(ebp);
340 	}
341 	/*
342 	 * Last, free the old blocks and assign the new blocks to the buffers.
343 	 */
344 #ifdef DEBUG
345 	printf("\n\tnew:");
346 #endif	/* DEBUG */
347 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->e2fs_fpb) {
348 		ext2_blkfree(ip, dbtofsb(fs, buflist->bs_children[i]->b_blkno),
349 		    fs->e2fs_bsize);
350 		buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
351 #ifdef DEBUG
352 		printf(" %d,", blkno);
353 #endif	/* DEBUG */
354 	}
355 #ifdef DEBUG
356 	printf("\n");
357 #endif	/* DEBUG */
358 	return (0);
359 
360 fail:
361 	if (ssize < len)
362 		brelse(ebp);
363 	if (sbap != &ip->i_db[0])
364 		brelse(sbp);
365 	return (ENOSPC);
366 }
367 
368 /*
369  * Allocate an inode in the filesystem.
370  *
371  */
372 int
373 ext2_valloc(struct vnode *pvp, int mode, struct ucred *cred, struct vnode **vpp)
374 {
375 	struct timespec ts;
376 	struct m_ext2fs *fs;
377 	struct ext2mount *ump;
378 	struct inode *pip;
379 	struct inode *ip;
380 	struct vnode *vp;
381 	struct thread *td;
382 	ino_t ino, ipref;
383 	int error, cg;
384 
385 	*vpp = NULL;
386 	pip = VTOI(pvp);
387 	fs = pip->i_e2fs;
388 	ump = pip->i_ump;
389 
390 	EXT2_LOCK(ump);
391 	if (fs->e2fs->e2fs_ficount == 0)
392 		goto noinodes;
393 	/*
394 	 * If it is a directory then obtain a cylinder group based on
395 	 * ext2_dirpref else obtain it using ino_to_cg. The preferred inode is
396 	 * always the next inode.
397 	 */
398 	if ((mode & IFMT) == IFDIR) {
399 		cg = ext2_dirpref(pip);
400 		if (fs->e2fs_contigdirs[cg] < 255)
401 			fs->e2fs_contigdirs[cg]++;
402 	} else {
403 		cg = ino_to_cg(fs, pip->i_number);
404 		if (fs->e2fs_contigdirs[cg] > 0)
405 			fs->e2fs_contigdirs[cg]--;
406 	}
407 	ipref = cg * fs->e2fs->e2fs_ipg + 1;
408 	ino = (ino_t)ext2_hashalloc(pip, cg, (long)ipref, mode, ext2_nodealloccg);
409 	if (ino == 0)
410 		goto noinodes;
411 
412 	td = curthread;
413 	error = vfs_hash_get(ump->um_mountp, ino, LK_EXCLUSIVE, td, vpp, NULL, NULL);
414 	if (error || *vpp != NULL) {
415 		return (error);
416 	}
417 
418 	ip = malloc(sizeof(struct inode), M_EXT2NODE, M_WAITOK | M_ZERO);
419 	if (ip == NULL) {
420 		return (ENOMEM);
421 	}
422 
423 	/* Allocate a new vnode/inode. */
424 	if ((error = getnewvnode("ext2fs", ump->um_mountp, &ext2_vnodeops, &vp)) != 0) {
425 		free(ip, M_EXT2NODE);
426 		return (error);
427 	}
428 
429 	lockmgr(vp->v_vnlock, LK_EXCLUSIVE, NULL);
430 	vp->v_data = ip;
431 	ip->i_vnode = vp;
432 	ip->i_e2fs = fs = ump->um_e2fs;
433 	ip->i_ump = ump;
434 	ip->i_number = ino;
435 	ip->i_block_group = ino_to_cg(fs, ino);
436 	ip->i_next_alloc_block = 0;
437 	ip->i_next_alloc_goal = 0;
438 
439 	error = insmntque(vp, ump->um_mountp);
440 	if (error) {
441 		free(ip, M_EXT2NODE);
442 		return (error);
443 	}
444 
445 	error = vfs_hash_insert(vp, ino, LK_EXCLUSIVE, td, vpp, NULL, NULL);
446 	if (error || *vpp != NULL) {
447 		*vpp = NULL;
448 		free(ip, M_EXT2NODE);
449 		return (error);
450 	}
451 
452 	if ((error = ext2_vinit(ump->um_mountp, &ext2_fifoops, &vp)) != 0) {
453 		vput(vp);
454 		*vpp = NULL;
455 		free(ip, M_EXT2NODE);
456 		return (error);
457 	}
458 
459 	if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_EXTENTS)
460 	    && (S_ISREG(mode) || S_ISDIR(mode)))
461 		ext4_ext_tree_init(ip);
462 	else
463 		memset(ip->i_data, 0, sizeof(ip->i_data));
464 
465 
466 	/*
467 	 * Set up a new generation number for this inode.
468 	 * Avoid zero values.
469 	 */
470 	do {
471 		ip->i_gen = arc4random();
472 	} while (ip->i_gen == 0);
473 
474 	vfs_timestamp(&ts);
475 	ip->i_birthtime = ts.tv_sec;
476 	ip->i_birthnsec = ts.tv_nsec;
477 
478 	*vpp = vp;
479 
480 	return (0);
481 
482 noinodes:
483 	EXT2_UNLOCK(ump);
484 	ext2_fserr(fs, cred->cr_uid, "out of inodes");
485 	uprintf("\n%s: create/symlink failed, no inodes free\n", fs->e2fs_fsmnt);
486 	return (ENOSPC);
487 }
488 
489 /*
490  * 64-bit compatible getters and setters for struct ext2_gd from ext2fs.h
491  */
492 uint64_t
493 e2fs_gd_get_b_bitmap(struct ext2_gd *gd)
494 {
495 
496 	return (((uint64_t)(gd->ext4bgd_b_bitmap_hi) << 32) |
497 	    gd->ext2bgd_b_bitmap);
498 }
499 
500 uint64_t
501 e2fs_gd_get_i_bitmap(struct ext2_gd *gd)
502 {
503 
504 	return (((uint64_t)(gd->ext4bgd_i_bitmap_hi) << 32) |
505 	    gd->ext2bgd_i_bitmap);
506 }
507 
508 uint64_t
509 e2fs_gd_get_i_tables(struct ext2_gd *gd)
510 {
511 
512 	return (((uint64_t)(gd->ext4bgd_i_tables_hi) << 32) |
513 	    gd->ext2bgd_i_tables);
514 }
515 
516 static uint32_t
517 e2fs_gd_get_nbfree(struct ext2_gd *gd)
518 {
519 
520 	return (((uint32_t)(gd->ext4bgd_nbfree_hi) << 16) |
521 	    gd->ext2bgd_nbfree);
522 }
523 
524 static void
525 e2fs_gd_set_nbfree(struct ext2_gd *gd, uint32_t val)
526 {
527 
528 	gd->ext2bgd_nbfree = val & 0xffff;
529 	gd->ext4bgd_nbfree_hi = val >> 16;
530 }
531 
532 static uint32_t
533 e2fs_gd_get_nifree(struct ext2_gd *gd)
534 {
535 
536 	return (((uint32_t)(gd->ext4bgd_nifree_hi) << 16) |
537 	    gd->ext2bgd_nifree);
538 }
539 
540 static void
541 e2fs_gd_set_nifree(struct ext2_gd *gd, uint32_t val)
542 {
543 
544 	gd->ext2bgd_nifree = val & 0xffff;
545 	gd->ext4bgd_nifree_hi = val >> 16;
546 }
547 
548 uint32_t
549 e2fs_gd_get_ndirs(struct ext2_gd *gd)
550 {
551 
552 	return (((uint32_t)(gd->ext4bgd_ndirs_hi) << 16) |
553 	    gd->ext2bgd_ndirs);
554 }
555 
556 static void
557 e2fs_gd_set_ndirs(struct ext2_gd *gd, uint32_t val)
558 {
559 
560 	gd->ext2bgd_ndirs = val & 0xffff;
561 	gd->ext4bgd_ndirs_hi = val >> 16;
562 }
563 
564 static uint32_t
565 e2fs_gd_get_i_unused(struct ext2_gd *gd)
566 {
567 	return (((uint32_t)(gd->ext4bgd_i_unused_hi) << 16) |
568 	    gd->ext4bgd_i_unused);
569 }
570 
571 static void
572 e2fs_gd_set_i_unused(struct ext2_gd *gd, uint32_t val)
573 {
574 
575 	gd->ext4bgd_i_unused = val & 0xffff;
576 	gd->ext4bgd_i_unused_hi = val >> 16;
577 }
578 
579 /*
580  * Find a cylinder to place a directory.
581  *
582  * The policy implemented by this algorithm is to allocate a
583  * directory inode in the same cylinder group as its parent
584  * directory, but also to reserve space for its files inodes
585  * and data. Restrict the number of directories which may be
586  * allocated one after another in the same cylinder group
587  * without intervening allocation of files.
588  *
589  * If we allocate a first level directory then force allocation
590  * in another cylinder group.
591  *
592  */
593 static u_long
594 ext2_dirpref(struct inode *pip)
595 {
596 	struct m_ext2fs *fs;
597 	int cg, prefcg, cgsize;
598 	uint64_t avgbfree, minbfree;
599 	u_int avgifree, avgndir, curdirsize;
600 	u_int minifree, maxndir;
601 	u_int mincg, minndir;
602 	u_int dirsize, maxcontigdirs;
603 
604 	mtx_assert(EXT2_MTX(pip->i_ump), MA_OWNED);
605 	fs = pip->i_e2fs;
606 
607 	avgifree = fs->e2fs->e2fs_ficount / fs->e2fs_gcount;
608 	avgbfree = fs->e2fs_fbcount / fs->e2fs_gcount;
609 	avgndir = fs->e2fs_total_dir / fs->e2fs_gcount;
610 
611 	/*
612 	 * Force allocation in another cg if creating a first level dir.
613 	 */
614 	ASSERT_VOP_LOCKED(ITOV(pip), "ext2fs_dirpref");
615 	if (ITOV(pip)->v_vflag & VV_ROOT) {
616 		prefcg = arc4random() % fs->e2fs_gcount;
617 		mincg = prefcg;
618 		minndir = fs->e2fs_ipg;
619 		for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
620 			if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
621 			    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
622 			    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
623 				mincg = cg;
624 				minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
625 			}
626 		for (cg = 0; cg < prefcg; cg++)
627 			if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
628 			    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
629 			    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
630 				mincg = cg;
631 				minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
632 			}
633 		return (mincg);
634 	}
635 	/*
636 	 * Count various limits which used for
637 	 * optimal allocation of a directory inode.
638 	 */
639 	maxndir = min(avgndir + fs->e2fs_ipg / 16, fs->e2fs_ipg);
640 	minifree = avgifree - avgifree / 4;
641 	if (minifree < 1)
642 		minifree = 1;
643 	minbfree = avgbfree - avgbfree / 4;
644 	if (minbfree < 1)
645 		minbfree = 1;
646 	cgsize = fs->e2fs_fsize * fs->e2fs_fpg;
647 	dirsize = AVGDIRSIZE;
648 	curdirsize = avgndir ? (cgsize - avgbfree * fs->e2fs_bsize) / avgndir : 0;
649 	if (dirsize < curdirsize)
650 		dirsize = curdirsize;
651 	maxcontigdirs = min((avgbfree * fs->e2fs_bsize) / dirsize, 255);
652 	maxcontigdirs = min(maxcontigdirs, fs->e2fs_ipg / AFPDIR);
653 	if (maxcontigdirs == 0)
654 		maxcontigdirs = 1;
655 
656 	/*
657 	 * Limit number of dirs in one cg and reserve space for
658 	 * regular files, but only if we have no deficit in
659 	 * inodes or space.
660 	 */
661 	prefcg = ino_to_cg(fs, pip->i_number);
662 	for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
663 		if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
664 		    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
665 		    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
666 			if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
667 				return (cg);
668 		}
669 	for (cg = 0; cg < prefcg; cg++)
670 		if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
671 		    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
672 		    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
673 			if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
674 				return (cg);
675 		}
676 	/*
677 	 * This is a backstop when we have deficit in space.
678 	 */
679 	for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
680 		if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
681 			return (cg);
682 	for (cg = 0; cg < prefcg; cg++)
683 		if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
684 			break;
685 	return (cg);
686 }
687 
688 /*
689  * Select the desired position for the next block in a file.
690  *
691  * we try to mimic what Remy does in inode_getblk/block_getblk
692  *
693  * we note: blocknr == 0 means that we're about to allocate either
694  * a direct block or a pointer block at the first level of indirection
695  * (In other words, stuff that will go in i_db[] or i_ib[])
696  *
697  * blocknr != 0 means that we're allocating a block that is none
698  * of the above. Then, blocknr tells us the number of the block
699  * that will hold the pointer
700  */
701 e4fs_daddr_t
702 ext2_blkpref(struct inode *ip, e2fs_lbn_t lbn, int indx, e2fs_daddr_t *bap,
703     e2fs_daddr_t blocknr)
704 {
705 	struct m_ext2fs *fs;
706 	int tmp;
707 
708 	fs = ip->i_e2fs;
709 
710 	mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
711 
712 	/*
713 	 * If the next block is actually what we thought it is, then set the
714 	 * goal to what we thought it should be.
715 	 */
716 	if (ip->i_next_alloc_block == lbn && ip->i_next_alloc_goal != 0)
717 		return ip->i_next_alloc_goal;
718 
719 	/*
720 	 * Now check whether we were provided with an array that basically
721 	 * tells us previous blocks to which we want to stay close.
722 	 */
723 	if (bap)
724 		for (tmp = indx - 1; tmp >= 0; tmp--)
725 			if (bap[tmp])
726 				return bap[tmp];
727 
728 	/*
729 	 * Else lets fall back to the blocknr or, if there is none, follow
730 	 * the rule that a block should be allocated near its inode.
731 	 */
732 	return (blocknr ? blocknr :
733 	    (e2fs_daddr_t)(ip->i_block_group *
734 	    EXT2_BLOCKS_PER_GROUP(fs)) + fs->e2fs->e2fs_first_dblock);
735 }
736 
737 /*
738  * Implement the cylinder overflow algorithm.
739  *
740  * The policy implemented by this algorithm is:
741  *   1) allocate the block in its requested cylinder group.
742  *   2) quadradically rehash on the cylinder group number.
743  *   3) brute force search for a free block.
744  */
745 static e4fs_daddr_t
746 ext2_hashalloc(struct inode *ip, int cg, long pref, int size,
747     daddr_t (*allocator) (struct inode *, int, daddr_t, int))
748 {
749 	struct m_ext2fs *fs;
750 	e4fs_daddr_t result;
751 	int i, icg = cg;
752 
753 	mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
754 	fs = ip->i_e2fs;
755 	/*
756 	 * 1: preferred cylinder group
757 	 */
758 	result = (*allocator)(ip, cg, pref, size);
759 	if (result)
760 		return (result);
761 	/*
762 	 * 2: quadratic rehash
763 	 */
764 	for (i = 1; i < fs->e2fs_gcount; i *= 2) {
765 		cg += i;
766 		if (cg >= fs->e2fs_gcount)
767 			cg -= fs->e2fs_gcount;
768 		result = (*allocator)(ip, cg, 0, size);
769 		if (result)
770 			return (result);
771 	}
772 	/*
773 	 * 3: brute force search
774 	 * Note that we start at i == 2, since 0 was checked initially,
775 	 * and 1 is always checked in the quadratic rehash.
776 	 */
777 	cg = (icg + 2) % fs->e2fs_gcount;
778 	for (i = 2; i < fs->e2fs_gcount; i++) {
779 		result = (*allocator)(ip, cg, 0, size);
780 		if (result)
781 			return (result);
782 		cg++;
783 		if (cg == fs->e2fs_gcount)
784 			cg = 0;
785 	}
786 	return (0);
787 }
788 
789 static uint64_t
790 ext2_cg_number_gdb_nometa(struct m_ext2fs *fs, int cg)
791 {
792 
793 	if (!ext2_cg_has_sb(fs, cg))
794 		return (0);
795 
796 	if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG))
797 		return (fs->e2fs->e3fs_first_meta_bg);
798 
799 	return ((fs->e2fs_gcount + EXT2_DESCS_PER_BLOCK(fs) - 1) /
800 	    EXT2_DESCS_PER_BLOCK(fs));
801 }
802 
803 static uint64_t
804 ext2_cg_number_gdb_meta(struct m_ext2fs *fs, int cg)
805 {
806 	unsigned long metagroup;
807 	int first, last;
808 
809 	metagroup = cg / EXT2_DESCS_PER_BLOCK(fs);
810 	first = metagroup * EXT2_DESCS_PER_BLOCK(fs);
811 	last = first + EXT2_DESCS_PER_BLOCK(fs) - 1;
812 
813 	if (cg == first || cg == first + 1 || cg == last)
814 		return (1);
815 
816 	return (0);
817 }
818 
819 uint64_t
820 ext2_cg_number_gdb(struct m_ext2fs *fs, int cg)
821 {
822 	unsigned long first_meta_bg, metagroup;
823 
824 	first_meta_bg = fs->e2fs->e3fs_first_meta_bg;
825 	metagroup = cg / EXT2_DESCS_PER_BLOCK(fs);
826 
827 	if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
828 	    metagroup < first_meta_bg)
829 		return (ext2_cg_number_gdb_nometa(fs, cg));
830 
831 	return ext2_cg_number_gdb_meta(fs, cg);
832 }
833 
834 static int
835 ext2_number_base_meta_blocks(struct m_ext2fs *fs, int cg)
836 {
837 	int number;
838 
839 	number = ext2_cg_has_sb(fs, cg);
840 
841 	if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
842 	    cg < fs->e2fs->e3fs_first_meta_bg * EXT2_DESCS_PER_BLOCK(fs)) {
843 		if (number) {
844 			number += ext2_cg_number_gdb(fs, cg);
845 			number += fs->e2fs->e2fs_reserved_ngdb;
846 		}
847 	} else {
848 		number += ext2_cg_number_gdb(fs, cg);
849 	}
850 
851 	return (number);
852 }
853 
854 static void
855 ext2_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
856 {
857 	int i;
858 
859 	if (start_bit >= end_bit)
860 		return;
861 
862 	for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
863 		setbit(bitmap, i);
864 	if (i < end_bit)
865 		memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
866 }
867 
868 static int
869 ext2_get_group_number(struct m_ext2fs *fs, e4fs_daddr_t block)
870 {
871 
872 	return ((block - fs->e2fs->e2fs_first_dblock) / fs->e2fs_bsize);
873 }
874 
875 static int
876 ext2_block_in_group(struct m_ext2fs *fs, e4fs_daddr_t block, int cg)
877 {
878 
879 	return ((ext2_get_group_number(fs, block) == cg) ? 1 : 0);
880 }
881 
882 static int
883 ext2_cg_block_bitmap_init(struct m_ext2fs *fs, int cg, struct buf *bp)
884 {
885 	int bit, bit_max, inodes_per_block;
886 	uint64_t start, tmp;
887 
888 	if (!(fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_BLOCK_UNINIT))
889 		return (0);
890 
891 	memset(bp->b_data, 0, fs->e2fs_bsize);
892 
893 	bit_max = ext2_number_base_meta_blocks(fs, cg);
894 	if ((bit_max >> 3) >= fs->e2fs_bsize)
895 		return (EINVAL);
896 
897 	for (bit = 0; bit < bit_max; bit++)
898 		setbit(bp->b_data, bit);
899 
900 	start = (uint64_t)cg * fs->e2fs->e2fs_bpg + fs->e2fs->e2fs_first_dblock;
901 
902 	/* Set bits for block and inode bitmaps, and inode table. */
903 	tmp = e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg]);
904 	if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
905 	    ext2_block_in_group(fs, tmp, cg))
906 		setbit(bp->b_data, tmp - start);
907 
908 	tmp = e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg]);
909 	if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
910 	    ext2_block_in_group(fs, tmp, cg))
911 		setbit(bp->b_data, tmp - start);
912 
913 	tmp = e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]);
914 	inodes_per_block = fs->e2fs_bsize/EXT2_INODE_SIZE(fs);
915 	while( tmp < e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) +
916 	    fs->e2fs->e2fs_ipg / inodes_per_block ) {
917 		if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
918 		    ext2_block_in_group(fs, tmp, cg))
919 			setbit(bp->b_data, tmp - start);
920 		tmp++;
921 	}
922 
923 	/*
924 	 * Also if the number of blocks within the group is less than
925 	 * the blocksize * 8 ( which is the size of bitmap ), set rest
926 	 * of the block bitmap to 1
927 	 */
928 	ext2_mark_bitmap_end(fs->e2fs->e2fs_bpg, fs->e2fs_bsize * 8,
929 	    bp->b_data);
930 
931 	/* Clean the flag */
932 	fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_BLOCK_UNINIT;
933 
934 	return (0);
935 }
936 
937 static int
938 ext2_b_bitmap_validate(struct m_ext2fs *fs, struct buf *bp, int cg)
939 {
940 	struct ext2_gd *gd;
941 	uint64_t group_first_block;
942 	unsigned int offset, max_bit;
943 
944 	if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG)) {
945 		/*
946 		 * It is not possible to check block bitmap in case of this feature,
947 		 * because the inode and block bitmaps and inode table
948 		 * blocks may not be in the group at all.
949 		 * So, skip check in this case.
950 		 */
951 		return (0);
952 	}
953 
954 	gd = &fs->e2fs_gd[cg];
955 	max_bit = fs->e2fs_fpg;
956 	group_first_block = ((uint64_t)cg) * fs->e2fs->e2fs_fpg +
957 	    fs->e2fs->e2fs_first_dblock;
958 
959 	/* Check block bitmap block number */
960 	offset = e2fs_gd_get_b_bitmap(gd) - group_first_block;
961 	if (offset >= max_bit || !isset(bp->b_data, offset)) {
962 		printf("ext2fs: bad block bitmap, group %d\n", cg);
963 		return (EINVAL);
964 	}
965 
966 	/* Check inode bitmap block number */
967 	offset = e2fs_gd_get_i_bitmap(gd) - group_first_block;
968 	if (offset >= max_bit || !isset(bp->b_data, offset)) {
969 		printf("ext2fs: bad inode bitmap, group %d\n", cg);
970 		return (EINVAL);
971 	}
972 
973 	/* Check inode table */
974 	offset = e2fs_gd_get_i_tables(gd) - group_first_block;
975 	if (offset >= max_bit || offset + fs->e2fs_itpg >= max_bit) {
976 		printf("ext2fs: bad inode table, group %d\n", cg);
977 		return (EINVAL);
978 	}
979 
980 	return (0);
981 }
982 
983 /*
984  * Determine whether a block can be allocated.
985  *
986  * Check to see if a block of the appropriate size is available,
987  * and if it is, allocate it.
988  */
989 static daddr_t
990 ext2_alloccg(struct inode *ip, int cg, daddr_t bpref, int size)
991 {
992 	struct m_ext2fs *fs;
993 	struct buf *bp;
994 	struct ext2mount *ump;
995 	daddr_t bno, runstart, runlen;
996 	int bit, loc, end, error, start;
997 	char *bbp;
998 	/* XXX ondisk32 */
999 	fs = ip->i_e2fs;
1000 	ump = ip->i_ump;
1001 	if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0)
1002 		return (0);
1003 
1004 	EXT2_UNLOCK(ump);
1005 	error = bread(ip->i_devvp, fsbtodb(fs,
1006 	    e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1007 	    (int)fs->e2fs_bsize, NOCRED, &bp);
1008 	if (error)
1009 		goto fail;
1010 
1011 	if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
1012 	    EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
1013 		error = ext2_cg_block_bitmap_init(fs, cg, bp);
1014 		if (error)
1015 			goto fail;
1016 
1017 		ext2_gd_b_bitmap_csum_set(fs, cg, bp);
1018 	}
1019 	error = ext2_gd_b_bitmap_csum_verify(fs, cg, bp);
1020 	if (error)
1021 		goto fail;
1022 
1023 	error = ext2_b_bitmap_validate(fs,bp, cg);
1024 	if (error)
1025 		goto fail;
1026 
1027 	/*
1028 	 * Check, that another thread did not not allocate the last block in this
1029 	 * group while we were waiting for the buffer.
1030 	 */
1031 	if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0)
1032 		goto fail;
1033 
1034 	bbp = (char *)bp->b_data;
1035 
1036 	if (dtog(fs, bpref) != cg)
1037 		bpref = 0;
1038 	if (bpref != 0) {
1039 		bpref = dtogd(fs, bpref);
1040 		/*
1041 		 * if the requested block is available, use it
1042 		 */
1043 		if (isclr(bbp, bpref)) {
1044 			bno = bpref;
1045 			goto gotit;
1046 		}
1047 	}
1048 	/*
1049 	 * no blocks in the requested cylinder, so take next
1050 	 * available one in this cylinder group.
1051 	 * first try to get 8 contigous blocks, then fall back to a single
1052 	 * block.
1053 	 */
1054 	if (bpref)
1055 		start = dtogd(fs, bpref) / NBBY;
1056 	else
1057 		start = 0;
1058 	end = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
1059 retry:
1060 	runlen = 0;
1061 	runstart = 0;
1062 	for (loc = start; loc < end; loc++) {
1063 		if (bbp[loc] == (char)0xff) {
1064 			runlen = 0;
1065 			continue;
1066 		}
1067 
1068 		/* Start of a run, find the number of high clear bits. */
1069 		if (runlen == 0) {
1070 			bit = fls(bbp[loc]);
1071 			runlen = NBBY - bit;
1072 			runstart = loc * NBBY + bit;
1073 		} else if (bbp[loc] == 0) {
1074 			/* Continue a run. */
1075 			runlen += NBBY;
1076 		} else {
1077 			/*
1078 			 * Finish the current run.  If it isn't long
1079 			 * enough, start a new one.
1080 			 */
1081 			bit = ffs(bbp[loc]) - 1;
1082 			runlen += bit;
1083 			if (runlen >= 8) {
1084 				bno = runstart;
1085 				goto gotit;
1086 			}
1087 
1088 			/* Run was too short, start a new one. */
1089 			bit = fls(bbp[loc]);
1090 			runlen = NBBY - bit;
1091 			runstart = loc * NBBY + bit;
1092 		}
1093 
1094 		/* If the current run is long enough, use it. */
1095 		if (runlen >= 8) {
1096 			bno = runstart;
1097 			goto gotit;
1098 		}
1099 	}
1100 	if (start != 0) {
1101 		end = start;
1102 		start = 0;
1103 		goto retry;
1104 	}
1105 	bno = ext2_mapsearch(fs, bbp, bpref);
1106 	if (bno < 0)
1107 		goto fail;
1108 
1109 gotit:
1110 #ifdef INVARIANTS
1111 	if (isset(bbp, bno)) {
1112 		printf("ext2fs_alloccgblk: cg=%d bno=%jd fs=%s\n",
1113 		    cg, (intmax_t)bno, fs->e2fs_fsmnt);
1114 		panic("ext2fs_alloccg: dup alloc");
1115 	}
1116 #endif
1117 	setbit(bbp, bno);
1118 	EXT2_LOCK(ump);
1119 	ext2_clusteracct(fs, bbp, cg, bno, -1);
1120 	fs->e2fs_fbcount--;
1121 	e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1122 	    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1123 	fs->e2fs_fmod = 1;
1124 	EXT2_UNLOCK(ump);
1125 	ext2_gd_b_bitmap_csum_set(fs, cg, bp);
1126 	bdwrite(bp);
1127 	return (((uint64_t)cg) * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1128 
1129 fail:
1130 	brelse(bp);
1131 	EXT2_LOCK(ump);
1132 	return (0);
1133 }
1134 
1135 /*
1136  * Determine whether a cluster can be allocated.
1137  */
1138 static daddr_t
1139 ext2_clusteralloc(struct inode *ip, int cg, daddr_t bpref, int len)
1140 {
1141 	struct m_ext2fs *fs;
1142 	struct ext2mount *ump;
1143 	struct buf *bp;
1144 	char *bbp;
1145 	int bit, error, got, i, loc, run;
1146 	int32_t *lp;
1147 	daddr_t bno;
1148 
1149 	fs = ip->i_e2fs;
1150 	ump = ip->i_ump;
1151 
1152 	if (fs->e2fs_maxcluster[cg] < len)
1153 		return (0);
1154 
1155 	EXT2_UNLOCK(ump);
1156 	error = bread(ip->i_devvp,
1157 	    fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1158 	    (int)fs->e2fs_bsize, NOCRED, &bp);
1159 	if (error)
1160 		goto fail_lock;
1161 
1162 	bbp = (char *)bp->b_data;
1163 	EXT2_LOCK(ump);
1164 	/*
1165 	 * Check to see if a cluster of the needed size (or bigger) is
1166 	 * available in this cylinder group.
1167 	 */
1168 	lp = &fs->e2fs_clustersum[cg].cs_sum[len];
1169 	for (i = len; i <= fs->e2fs_contigsumsize; i++)
1170 		if (*lp++ > 0)
1171 			break;
1172 	if (i > fs->e2fs_contigsumsize) {
1173 		/*
1174 		 * Update the cluster summary information to reflect
1175 		 * the true maximum-sized cluster so that future cluster
1176 		 * allocation requests can avoid reading the bitmap only
1177 		 * to find no cluster.
1178 		 */
1179 		lp = &fs->e2fs_clustersum[cg].cs_sum[len - 1];
1180 		for (i = len - 1; i > 0; i--)
1181 			if (*lp-- > 0)
1182 				break;
1183 		fs->e2fs_maxcluster[cg] = i;
1184 		goto fail;
1185 	}
1186 	EXT2_UNLOCK(ump);
1187 
1188 	/* Search the bitmap to find a big enough cluster like in FFS. */
1189 	if (dtog(fs, bpref) != cg)
1190 		bpref = 0;
1191 	if (bpref != 0)
1192 		bpref = dtogd(fs, bpref);
1193 	loc = bpref / NBBY;
1194 	bit = 1 << (bpref % NBBY);
1195 	for (run = 0, got = bpref; got < fs->e2fs->e2fs_fpg; got++) {
1196 		if ((bbp[loc] & bit) != 0)
1197 			run = 0;
1198 		else {
1199 			run++;
1200 			if (run == len)
1201 				break;
1202 		}
1203 		if ((got & (NBBY - 1)) != (NBBY - 1))
1204 			bit <<= 1;
1205 		else {
1206 			loc++;
1207 			bit = 1;
1208 		}
1209 	}
1210 
1211 	if (got >= fs->e2fs->e2fs_fpg)
1212 		goto fail_lock;
1213 
1214 	/* Allocate the cluster that we found. */
1215 	for (i = 1; i < len; i++)
1216 		if (!isclr(bbp, got - run + i))
1217 			panic("ext2_clusteralloc: map mismatch");
1218 
1219 	bno = got - run + 1;
1220 	if (bno >= fs->e2fs->e2fs_fpg)
1221 		panic("ext2_clusteralloc: allocated out of group");
1222 
1223 	EXT2_LOCK(ump);
1224 	for (i = 0; i < len; i += fs->e2fs_fpb) {
1225 		setbit(bbp, bno + i);
1226 		ext2_clusteracct(fs, bbp, cg, bno + i, -1);
1227 		fs->e2fs_fbcount--;
1228 		e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1229 		    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1230 	}
1231 	fs->e2fs_fmod = 1;
1232 	EXT2_UNLOCK(ump);
1233 
1234 	bdwrite(bp);
1235 	return (cg * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1236 
1237 fail_lock:
1238 	EXT2_LOCK(ump);
1239 fail:
1240 	brelse(bp);
1241 	return (0);
1242 }
1243 
1244 static int
1245 ext2_zero_inode_table(struct inode *ip, int cg)
1246 {
1247 	struct m_ext2fs *fs;
1248 	struct buf *bp;
1249 	int i, all_blks, used_blks;
1250 
1251 	fs = ip->i_e2fs;
1252 
1253 	if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_ZEROED)
1254 		return (0);
1255 
1256 	all_blks = fs->e2fs->e2fs_inode_size * fs->e2fs->e2fs_ipg /
1257 	    fs->e2fs_bsize;
1258 
1259 	used_blks = howmany(fs->e2fs->e2fs_ipg -
1260 	    e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]),
1261 	    fs->e2fs_bsize / EXT2_INODE_SIZE(fs));
1262 
1263 	for (i = 0; i < all_blks - used_blks; i++) {
1264 		bp = getblk(ip->i_devvp, fsbtodb(fs,
1265 		    e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) + used_blks + i),
1266 		    fs->e2fs_bsize, 0, 0, 0);
1267 		if (!bp)
1268 			return (EIO);
1269 
1270 		vfs_bio_bzero_buf(bp, 0, fs->e2fs_bsize);
1271 		bawrite(bp);
1272 	}
1273 
1274 	fs->e2fs_gd[cg].ext4bgd_flags |= EXT2_BG_INODE_ZEROED;
1275 
1276 	return (0);
1277 }
1278 
1279 /*
1280  * Determine whether an inode can be allocated.
1281  *
1282  * Check to see if an inode is available, and if it is,
1283  * allocate it using tode in the specified cylinder group.
1284  */
1285 static daddr_t
1286 ext2_nodealloccg(struct inode *ip, int cg, daddr_t ipref, int mode)
1287 {
1288 	struct m_ext2fs *fs;
1289 	struct buf *bp;
1290 	struct ext2mount *ump;
1291 	int error, start, len, ifree;
1292 	char *ibp, *loc;
1293 
1294 	ipref--;	/* to avoid a lot of (ipref -1) */
1295 	if (ipref == -1)
1296 		ipref = 0;
1297 	fs = ip->i_e2fs;
1298 	ump = ip->i_ump;
1299 	if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0)
1300 		return (0);
1301 	EXT2_UNLOCK(ump);
1302 	error = bread(ip->i_devvp, fsbtodb(fs,
1303 	    e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1304 	    (int)fs->e2fs_bsize, NOCRED, &bp);
1305 	if (error) {
1306 		brelse(bp);
1307 		EXT2_LOCK(ump);
1308 		return (0);
1309 	}
1310 	if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
1311 	    EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
1312 		if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_UNINIT) {
1313 			memset(bp->b_data, 0, fs->e2fs_bsize);
1314 			fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_INODE_UNINIT;
1315 		}
1316 		ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1317 		error = ext2_zero_inode_table(ip, cg);
1318 		if (error) {
1319 			brelse(bp);
1320 			EXT2_LOCK(ump);
1321 			return (0);
1322 		}
1323 	}
1324 	error = ext2_gd_i_bitmap_csum_verify(fs, cg, bp);
1325 	if (error) {
1326 		brelse(bp);
1327 		EXT2_LOCK(ump);
1328 		return (0);
1329 	}
1330 	if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0) {
1331 		/*
1332 		 * Another thread allocated the last i-node in this
1333 		 * group while we were waiting for the buffer.
1334 		 */
1335 		brelse(bp);
1336 		EXT2_LOCK(ump);
1337 		return (0);
1338 	}
1339 	ibp = (char *)bp->b_data;
1340 	if (ipref) {
1341 		ipref %= fs->e2fs->e2fs_ipg;
1342 		if (isclr(ibp, ipref))
1343 			goto gotit;
1344 	}
1345 	start = ipref / NBBY;
1346 	len = howmany(fs->e2fs->e2fs_ipg - ipref, NBBY);
1347 	loc = memcchr(&ibp[start], 0xff, len);
1348 	if (loc == NULL) {
1349 		len = start + 1;
1350 		start = 0;
1351 		loc = memcchr(&ibp[start], 0xff, len);
1352 		if (loc == NULL) {
1353 			printf("ext2fs: inode bitmap corrupted: "
1354 			    "cg = %d, ipref = %lld, fs = %s - run fsck\n",
1355 			    cg, (long long)ipref, fs->e2fs_fsmnt);
1356 			brelse(bp);
1357 			EXT2_LOCK(ump);
1358 			return (0);
1359 		}
1360 	}
1361 	ipref = (loc - ibp) * NBBY + ffs(~*loc) - 1;
1362 gotit:
1363 	setbit(ibp, ipref);
1364 	EXT2_LOCK(ump);
1365 	e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1366 	    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) - 1);
1367 	if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM) ||
1368 	    EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_METADATA_CKSUM)) {
1369 		ifree = fs->e2fs->e2fs_ipg - e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]);
1370 		if (ipref + 1 > ifree)
1371 			e2fs_gd_set_i_unused(&fs->e2fs_gd[cg],
1372 			    fs->e2fs->e2fs_ipg - (ipref + 1));
1373 	}
1374 	fs->e2fs->e2fs_ficount--;
1375 	fs->e2fs_fmod = 1;
1376 	if ((mode & IFMT) == IFDIR) {
1377 		e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1378 		    e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) + 1);
1379 		fs->e2fs_total_dir++;
1380 	}
1381 	EXT2_UNLOCK(ump);
1382 	ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1383 	bdwrite(bp);
1384 	return ((uint64_t)cg * fs->e2fs_ipg + ipref + 1);
1385 }
1386 
1387 /*
1388  * Free a block or fragment.
1389  *
1390  */
1391 void
1392 ext2_blkfree(struct inode *ip, e4fs_daddr_t bno, long size)
1393 {
1394 	struct m_ext2fs *fs;
1395 	struct buf *bp;
1396 	struct ext2mount *ump;
1397 	int cg, error;
1398 	char *bbp;
1399 
1400 	fs = ip->i_e2fs;
1401 	ump = ip->i_ump;
1402 	cg = dtog(fs, bno);
1403 	if (bno >= fs->e2fs_bcount) {
1404 		printf("bad block %lld, ino %ju\n", (long long)bno,
1405 		    (uintmax_t)ip->i_number);
1406 		ext2_fserr(fs, ip->i_uid, "bad block");
1407 		return;
1408 	}
1409 	error = bread(ip->i_devvp,
1410 	    fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1411 	    (int)fs->e2fs_bsize, NOCRED, &bp);
1412 	if (error) {
1413 		brelse(bp);
1414 		return;
1415 	}
1416 	bbp = (char *)bp->b_data;
1417 	bno = dtogd(fs, bno);
1418 	if (isclr(bbp, bno)) {
1419 		printf("block = %lld, fs = %s\n",
1420 		    (long long)bno, fs->e2fs_fsmnt);
1421 		panic("ext2_blkfree: freeing free block");
1422 	}
1423 	clrbit(bbp, bno);
1424 	EXT2_LOCK(ump);
1425 	ext2_clusteracct(fs, bbp, cg, bno, 1);
1426 	fs->e2fs_fbcount++;
1427 	e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1428 	    e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) + 1);
1429 	fs->e2fs_fmod = 1;
1430 	EXT2_UNLOCK(ump);
1431 	ext2_gd_b_bitmap_csum_set(fs, cg, bp);
1432 	bdwrite(bp);
1433 }
1434 
1435 /*
1436  * Free an inode.
1437  *
1438  */
1439 int
1440 ext2_vfree(struct vnode *pvp, ino_t ino, int mode)
1441 {
1442 	struct m_ext2fs *fs;
1443 	struct inode *pip;
1444 	struct buf *bp;
1445 	struct ext2mount *ump;
1446 	int error, cg;
1447 	char *ibp;
1448 
1449 	pip = VTOI(pvp);
1450 	fs = pip->i_e2fs;
1451 	ump = pip->i_ump;
1452 	if ((u_int)ino > fs->e2fs_ipg * fs->e2fs_gcount)
1453 		panic("ext2_vfree: range: devvp = %p, ino = %ju, fs = %s",
1454 		    pip->i_devvp, (uintmax_t)ino, fs->e2fs_fsmnt);
1455 
1456 	cg = ino_to_cg(fs, ino);
1457 	error = bread(pip->i_devvp,
1458 	    fsbtodb(fs, e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1459 	    (int)fs->e2fs_bsize, NOCRED, &bp);
1460 	if (error) {
1461 		brelse(bp);
1462 		return (0);
1463 	}
1464 	ibp = (char *)bp->b_data;
1465 	ino = (ino - 1) % fs->e2fs->e2fs_ipg;
1466 	if (isclr(ibp, ino)) {
1467 		printf("ino = %ju, fs = %s\n",
1468 		    ino, fs->e2fs_fsmnt);
1469 		if (fs->e2fs_ronly == 0)
1470 			panic("ext2_vfree: freeing free inode");
1471 	}
1472 	clrbit(ibp, ino);
1473 	EXT2_LOCK(ump);
1474 	fs->e2fs->e2fs_ficount++;
1475 	e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1476 	    e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) + 1);
1477 	if ((mode & IFMT) == IFDIR) {
1478 		e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1479 		    e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) - 1);
1480 		fs->e2fs_total_dir--;
1481 	}
1482 	fs->e2fs_fmod = 1;
1483 	EXT2_UNLOCK(ump);
1484 	ext2_gd_i_bitmap_csum_set(fs, cg, bp);
1485 	bdwrite(bp);
1486 	return (0);
1487 }
1488 
1489 /*
1490  * Find a block in the specified cylinder group.
1491  *
1492  * It is a panic if a request is made to find a block if none are
1493  * available.
1494  */
1495 static daddr_t
1496 ext2_mapsearch(struct m_ext2fs *fs, char *bbp, daddr_t bpref)
1497 {
1498 	char *loc;
1499 	int start, len;
1500 
1501 	/*
1502 	 * find the fragment by searching through the free block
1503 	 * map for an appropriate bit pattern
1504 	 */
1505 	if (bpref)
1506 		start = dtogd(fs, bpref) / NBBY;
1507 	else
1508 		start = 0;
1509 	len = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
1510 	loc = memcchr(&bbp[start], 0xff, len);
1511 	if (loc == NULL) {
1512 		len = start + 1;
1513 		start = 0;
1514 		loc = memcchr(&bbp[start], 0xff, len);
1515 		if (loc == NULL) {
1516 			printf("start = %d, len = %d, fs = %s\n",
1517 			    start, len, fs->e2fs_fsmnt);
1518 			panic("ext2_mapsearch: map corrupted");
1519 			/* NOTREACHED */
1520 		}
1521 	}
1522 	return ((loc - bbp) * NBBY + ffs(~*loc) - 1);
1523 }
1524 
1525 /*
1526  * Fserr prints the name of a filesystem with an error diagnostic.
1527  *
1528  * The form of the error message is:
1529  *	fs: error message
1530  */
1531 void
1532 ext2_fserr(struct m_ext2fs *fs, uid_t uid, char *cp)
1533 {
1534 
1535 	log(LOG_ERR, "uid %u on %s: %s\n", uid, fs->e2fs_fsmnt, cp);
1536 }
1537 
1538 int
1539 ext2_cg_has_sb(struct m_ext2fs *fs, int cg)
1540 {
1541 	int a3, a5, a7;
1542 
1543 	if (cg == 0)
1544 		return (1);
1545 
1546 	if (EXT2_HAS_COMPAT_FEATURE(fs, EXT2F_COMPAT_SPARSESUPER2)) {
1547 		if (cg == fs->e2fs->e4fs_backup_bgs[0] ||
1548 		    cg == fs->e2fs->e4fs_backup_bgs[1])
1549 			return (1);
1550 		return (0);
1551 	}
1552 
1553 	if ((cg <= 1) ||
1554 	    !EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_SPARSESUPER))
1555 		return (1);
1556 
1557 	if (!(cg & 1))
1558 		return (0);
1559 
1560 	for (a3 = 3, a5 = 5, a7 = 7;
1561 	    a3 <= cg || a5 <= cg || a7 <= cg;
1562 	    a3 *= 3, a5 *= 5, a7 *= 7)
1563 		if (cg == a3 || cg == a5 || cg == a7)
1564 			return (1);
1565 	return (0);
1566 }
1567