]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/ext2fs/ext2_alloc.c
Merge ^/head r327341 through r327623.
[FreeBSD/FreeBSD.git] / sys / fs / ext2fs / ext2_alloc.c
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 inode *pip;
377         struct m_ext2fs *fs;
378         struct inode *ip;
379         struct ext2mount *ump;
380         ino_t ino, ipref;
381         int error, cg;
382
383         *vpp = NULL;
384         pip = VTOI(pvp);
385         fs = pip->i_e2fs;
386         ump = pip->i_ump;
387
388         EXT2_LOCK(ump);
389         if (fs->e2fs->e2fs_ficount == 0)
390                 goto noinodes;
391         /*
392          * If it is a directory then obtain a cylinder group based on
393          * ext2_dirpref else obtain it using ino_to_cg. The preferred inode is
394          * always the next inode.
395          */
396         if ((mode & IFMT) == IFDIR) {
397                 cg = ext2_dirpref(pip);
398                 if (fs->e2fs_contigdirs[cg] < 255)
399                         fs->e2fs_contigdirs[cg]++;
400         } else {
401                 cg = ino_to_cg(fs, pip->i_number);
402                 if (fs->e2fs_contigdirs[cg] > 0)
403                         fs->e2fs_contigdirs[cg]--;
404         }
405         ipref = cg * fs->e2fs->e2fs_ipg + 1;
406         ino = (ino_t)ext2_hashalloc(pip, cg, (long)ipref, mode, ext2_nodealloccg);
407
408         if (ino == 0)
409                 goto noinodes;
410         error = VFS_VGET(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
411         if (error) {
412                 ext2_vfree(pvp, ino, mode);
413                 return (error);
414         }
415         ip = VTOI(*vpp);
416
417         /*
418          * The question is whether using VGET was such good idea at all:
419          * Linux doesn't read the old inode in when it is allocating a
420          * new one. I will set at least i_size and i_blocks to zero.
421          */
422         ip->i_flag = 0;
423         ip->i_size = 0;
424         ip->i_blocks = 0;
425         ip->i_mode = 0;
426         ip->i_flags = 0;
427         if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_EXTENTS)
428             && (S_ISREG(mode) || S_ISDIR(mode)))
429                 ext4_ext_tree_init(ip);
430         else
431                 memset(ip->i_data, 0, sizeof(ip->i_data));
432         
433
434         /*
435          * Set up a new generation number for this inode.
436          * Avoid zero values.
437          */
438         do {
439                 ip->i_gen = arc4random();
440         } while (ip->i_gen == 0);
441
442         vfs_timestamp(&ts);
443         ip->i_birthtime = ts.tv_sec;
444         ip->i_birthnsec = ts.tv_nsec;
445
446 /*
447 printf("ext2_valloc: allocated inode %d\n", ino);
448 */
449         return (0);
450 noinodes:
451         EXT2_UNLOCK(ump);
452         ext2_fserr(fs, cred->cr_uid, "out of inodes");
453         uprintf("\n%s: create/symlink failed, no inodes free\n", fs->e2fs_fsmnt);
454         return (ENOSPC);
455 }
456
457 /*
458  * 64-bit compatible getters and setters for struct ext2_gd from ext2fs.h
459  */
460 static uint64_t
461 e2fs_gd_get_b_bitmap(struct ext2_gd *gd)
462 {
463
464         return (((uint64_t)(gd->ext4bgd_b_bitmap_hi) << 32) |
465             gd->ext2bgd_b_bitmap);
466 }
467
468 static uint64_t
469 e2fs_gd_get_i_bitmap(struct ext2_gd *gd)
470 {
471
472         return (((uint64_t)(gd->ext4bgd_i_bitmap_hi) << 32) |
473             gd->ext2bgd_i_bitmap);
474 }
475
476 uint64_t
477 e2fs_gd_get_i_tables(struct ext2_gd *gd)
478 {
479
480         return (((uint64_t)(gd->ext4bgd_i_tables_hi) << 32) |
481             gd->ext2bgd_i_tables);
482 }
483
484 static uint32_t
485 e2fs_gd_get_nbfree(struct ext2_gd *gd)
486 {
487
488         return (((uint32_t)(gd->ext4bgd_nbfree_hi) << 16) |
489             gd->ext2bgd_nbfree);
490 }
491
492 static void
493 e2fs_gd_set_nbfree(struct ext2_gd *gd, uint32_t val)
494 {
495
496         gd->ext2bgd_nbfree = val & 0xffff;
497         gd->ext4bgd_nbfree_hi = val >> 16;
498 }
499
500 static uint32_t
501 e2fs_gd_get_nifree(struct ext2_gd *gd)
502 {
503
504         return (((uint32_t)(gd->ext4bgd_nifree_hi) << 16) |
505             gd->ext2bgd_nifree);
506 }
507
508 static void
509 e2fs_gd_set_nifree(struct ext2_gd *gd, uint32_t val)
510 {
511
512         gd->ext2bgd_nifree = val & 0xffff;
513         gd->ext4bgd_nifree_hi = val >> 16;
514 }
515
516 uint32_t
517 e2fs_gd_get_ndirs(struct ext2_gd *gd)
518 {
519
520         return (((uint32_t)(gd->ext4bgd_ndirs_hi) << 16) |
521             gd->ext2bgd_ndirs);
522 }
523
524 static void
525 e2fs_gd_set_ndirs(struct ext2_gd *gd, uint32_t val)
526 {
527
528         gd->ext2bgd_ndirs = val & 0xffff;
529         gd->ext4bgd_ndirs_hi = val >> 16;
530 }
531
532 static uint32_t
533 e2fs_gd_get_i_unused(struct ext2_gd *gd)
534 {
535         return (((uint32_t)(gd->ext4bgd_i_unused_hi) << 16) |
536             gd->ext4bgd_i_unused);
537 }
538
539 static void
540 e2fs_gd_set_i_unused(struct ext2_gd *gd, uint32_t val)
541 {
542
543         gd->ext4bgd_i_unused = val & 0xffff;
544         gd->ext4bgd_i_unused_hi = val >> 16;
545 }
546
547 /*
548  * Find a cylinder to place a directory.
549  *
550  * The policy implemented by this algorithm is to allocate a
551  * directory inode in the same cylinder group as its parent
552  * directory, but also to reserve space for its files inodes
553  * and data. Restrict the number of directories which may be
554  * allocated one after another in the same cylinder group
555  * without intervening allocation of files.
556  *
557  * If we allocate a first level directory then force allocation
558  * in another cylinder group.
559  *
560  */
561 static u_long
562 ext2_dirpref(struct inode *pip)
563 {
564         struct m_ext2fs *fs;
565         int cg, prefcg, cgsize;
566         uint64_t avgbfree, minbfree;
567         u_int avgifree, avgndir, curdirsize;
568         u_int minifree, maxndir;
569         u_int mincg, minndir;
570         u_int dirsize, maxcontigdirs;
571
572         mtx_assert(EXT2_MTX(pip->i_ump), MA_OWNED);
573         fs = pip->i_e2fs;
574
575         avgifree = fs->e2fs->e2fs_ficount / fs->e2fs_gcount;
576         avgbfree = fs->e2fs_fbcount / fs->e2fs_gcount;
577         avgndir = fs->e2fs_total_dir / fs->e2fs_gcount;
578
579         /*
580          * Force allocation in another cg if creating a first level dir.
581          */
582         ASSERT_VOP_LOCKED(ITOV(pip), "ext2fs_dirpref");
583         if (ITOV(pip)->v_vflag & VV_ROOT) {
584                 prefcg = arc4random() % fs->e2fs_gcount;
585                 mincg = prefcg;
586                 minndir = fs->e2fs_ipg;
587                 for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
588                         if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
589                             e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
590                             e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
591                                 mincg = cg;
592                                 minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
593                         }
594                 for (cg = 0; cg < prefcg; cg++)
595                         if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < minndir &&
596                             e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree &&
597                             e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= avgbfree) {
598                                 mincg = cg;
599                                 minndir = e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]);
600                         }
601                 return (mincg);
602         }
603         /*
604          * Count various limits which used for
605          * optimal allocation of a directory inode.
606          */
607         maxndir = min(avgndir + fs->e2fs_ipg / 16, fs->e2fs_ipg);
608         minifree = avgifree - avgifree / 4;
609         if (minifree < 1)
610                 minifree = 1;
611         minbfree = avgbfree - avgbfree / 4;
612         if (minbfree < 1)
613                 minbfree = 1;
614         cgsize = fs->e2fs_fsize * fs->e2fs_fpg;
615         dirsize = AVGDIRSIZE;
616         curdirsize = avgndir ? (cgsize - avgbfree * fs->e2fs_bsize) / avgndir : 0;
617         if (dirsize < curdirsize)
618                 dirsize = curdirsize;
619         maxcontigdirs = min((avgbfree * fs->e2fs_bsize) / dirsize, 255);
620         maxcontigdirs = min(maxcontigdirs, fs->e2fs_ipg / AFPDIR);
621         if (maxcontigdirs == 0)
622                 maxcontigdirs = 1;
623
624         /*
625          * Limit number of dirs in one cg and reserve space for
626          * regular files, but only if we have no deficit in
627          * inodes or space.
628          */
629         prefcg = ino_to_cg(fs, pip->i_number);
630         for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
631                 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
632                     e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
633                     e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
634                         if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
635                                 return (cg);
636                 }
637         for (cg = 0; cg < prefcg; cg++)
638                 if (e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) < maxndir &&
639                     e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= minifree &&
640                     e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) >= minbfree) {
641                         if (fs->e2fs_contigdirs[cg] < maxcontigdirs)
642                                 return (cg);
643                 }
644         /*
645          * This is a backstop when we have deficit in space.
646          */
647         for (cg = prefcg; cg < fs->e2fs_gcount; cg++)
648                 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
649                         return (cg);
650         for (cg = 0; cg < prefcg; cg++)
651                 if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) >= avgifree)
652                         break;
653         return (cg);
654 }
655
656 /*
657  * Select the desired position for the next block in a file.
658  *
659  * we try to mimic what Remy does in inode_getblk/block_getblk
660  *
661  * we note: blocknr == 0 means that we're about to allocate either
662  * a direct block or a pointer block at the first level of indirection
663  * (In other words, stuff that will go in i_db[] or i_ib[])
664  *
665  * blocknr != 0 means that we're allocating a block that is none
666  * of the above. Then, blocknr tells us the number of the block
667  * that will hold the pointer
668  */
669 e4fs_daddr_t
670 ext2_blkpref(struct inode *ip, e2fs_lbn_t lbn, int indx, e2fs_daddr_t *bap,
671     e2fs_daddr_t blocknr)
672 {
673         struct m_ext2fs *fs;
674         int tmp;
675
676         fs = ip->i_e2fs;
677
678         mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
679
680         /*
681          * If the next block is actually what we thought it is, then set the
682          * goal to what we thought it should be.
683          */
684         if (ip->i_next_alloc_block == lbn && ip->i_next_alloc_goal != 0)
685                 return ip->i_next_alloc_goal;
686
687         /*
688          * Now check whether we were provided with an array that basically
689          * tells us previous blocks to which we want to stay close.
690          */
691         if (bap)
692                 for (tmp = indx - 1; tmp >= 0; tmp--)
693                         if (bap[tmp])
694                                 return bap[tmp];
695
696         /*
697          * Else lets fall back to the blocknr or, if there is none, follow
698          * the rule that a block should be allocated near its inode.
699          */
700         return (blocknr ? blocknr :
701             (e2fs_daddr_t)(ip->i_block_group *
702             EXT2_BLOCKS_PER_GROUP(fs)) + fs->e2fs->e2fs_first_dblock);
703 }
704
705 /*
706  * Implement the cylinder overflow algorithm.
707  *
708  * The policy implemented by this algorithm is:
709  *   1) allocate the block in its requested cylinder group.
710  *   2) quadradically rehash on the cylinder group number.
711  *   3) brute force search for a free block.
712  */
713 static e4fs_daddr_t
714 ext2_hashalloc(struct inode *ip, int cg, long pref, int size,
715     daddr_t (*allocator) (struct inode *, int, daddr_t, int))
716 {
717         struct m_ext2fs *fs;
718         e4fs_daddr_t result;
719         int i, icg = cg;
720
721         mtx_assert(EXT2_MTX(ip->i_ump), MA_OWNED);
722         fs = ip->i_e2fs;
723         /*
724          * 1: preferred cylinder group
725          */
726         result = (*allocator)(ip, cg, pref, size);
727         if (result)
728                 return (result);
729         /*
730          * 2: quadratic rehash
731          */
732         for (i = 1; i < fs->e2fs_gcount; i *= 2) {
733                 cg += i;
734                 if (cg >= fs->e2fs_gcount)
735                         cg -= fs->e2fs_gcount;
736                 result = (*allocator)(ip, cg, 0, size);
737                 if (result)
738                         return (result);
739         }
740         /*
741          * 3: brute force search
742          * Note that we start at i == 2, since 0 was checked initially,
743          * and 1 is always checked in the quadratic rehash.
744          */
745         cg = (icg + 2) % fs->e2fs_gcount;
746         for (i = 2; i < fs->e2fs_gcount; i++) {
747                 result = (*allocator)(ip, cg, 0, size);
748                 if (result)
749                         return (result);
750                 cg++;
751                 if (cg == fs->e2fs_gcount)
752                         cg = 0;
753         }
754         return (0);
755 }
756
757 static unsigned long
758 ext2_cg_num_gdb(struct m_ext2fs *fs, int cg)
759 {
760         int gd_per_block, metagroup, first, last;
761
762         gd_per_block = fs->e2fs_bsize / sizeof(struct ext2_gd);
763         metagroup = cg / gd_per_block;
764         first = metagroup * gd_per_block;
765         last = first + gd_per_block - 1;
766
767         if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
768             metagroup < fs->e2fs->e3fs_first_meta_bg) {
769                 if (!ext2_cg_has_sb(fs, cg))
770                         return (0);
771                 if (EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG))
772                         return (fs->e2fs->e3fs_first_meta_bg);
773                 return (fs->e2fs_gdbcount);
774         }
775
776         if (cg == first || cg == first + 1 || cg == last)
777                 return (1);
778         return (0);
779
780 }
781
782 static int
783 ext2_num_base_meta_blocks(struct m_ext2fs *fs, int cg)
784 {
785         int num, gd_per_block;
786
787         gd_per_block = fs->e2fs_bsize / sizeof(struct ext2_gd);
788         num = ext2_cg_has_sb(fs, cg);
789
790         if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_META_BG) ||
791             cg < fs->e2fs->e3fs_first_meta_bg * gd_per_block) {
792                 if (num) {
793                         num += ext2_cg_num_gdb(fs, cg);
794                         num += fs->e2fs->e2fs_reserved_ngdb;
795                 }
796         } else {
797                 num += ext2_cg_num_gdb(fs, cg);
798         }
799         
800         return (num);
801 }
802
803 static void
804 ext2_mark_bitmap_end(int start_bit, int end_bit, char *bitmap)
805 {
806         int i;
807
808         if (start_bit >= end_bit)
809                 return;
810
811         for (i = start_bit; i < ((start_bit + 7) & ~7UL); i++)
812                 setbit(bitmap, i);
813         if (i < end_bit)
814                 memset(bitmap + (i >> 3), 0xff, (end_bit - i) >> 3);
815 }
816
817 static int
818 ext2_cg_block_bitmap_init(struct m_ext2fs *fs, int cg, struct buf *bp)
819 {
820         int bit, bit_max, inodes_per_block;
821         uint64_t start, tmp;
822
823         if (!(fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_BLOCK_UNINIT))
824                 return (0);
825
826         memset(bp->b_data, 0, fs->e2fs_bsize);
827
828         bit_max = ext2_num_base_meta_blocks(fs, cg);
829         if ((bit_max >> 3) >= fs->e2fs_bsize)
830                 return (EINVAL);
831
832         for (bit = 0; bit < bit_max; bit++)
833                 setbit(bp->b_data, bit);
834
835         start = (uint64_t)cg * fs->e2fs->e2fs_bpg + fs->e2fs->e2fs_first_dblock;
836
837         /* Set bits for block and inode bitmaps, and inode table. */
838         tmp = e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg]);
839         if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
840             cg == dtogd(fs, tmp))
841                 setbit(bp->b_data, tmp - start);
842
843         tmp = e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg]);
844         if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
845             cg == dtogd(fs, tmp))
846                 setbit(bp->b_data, tmp - start);
847
848         tmp = e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]);
849         inodes_per_block = fs->e2fs_bsize/EXT2_INODE_SIZE(fs);
850         while( tmp < e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) +
851             fs->e2fs->e2fs_ipg / inodes_per_block ) {
852                 if (!EXT2_HAS_INCOMPAT_FEATURE(fs, EXT2F_INCOMPAT_FLEX_BG) ||
853                     cg == dtogd(fs, tmp))
854                         setbit(bp->b_data, tmp - start);
855                 tmp++;
856         }
857
858         /*
859          * Also if the number of blocks within the group is less than
860          * the blocksize * 8 ( which is the size of bitmap ), set rest
861          * of the block bitmap to 1
862          */
863         ext2_mark_bitmap_end(fs->e2fs->e2fs_bpg, fs->e2fs_bsize * 8,
864             bp->b_data);
865
866         /* Clean the flag */
867         fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_BLOCK_UNINIT;
868
869         return (0);
870 }
871
872 /*
873  * Determine whether a block can be allocated.
874  *
875  * Check to see if a block of the appropriate size is available,
876  * and if it is, allocate it.
877  */
878 static daddr_t
879 ext2_alloccg(struct inode *ip, int cg, daddr_t bpref, int size)
880 {
881         struct m_ext2fs *fs;
882         struct buf *bp;
883         struct ext2mount *ump;
884         daddr_t bno, runstart, runlen;
885         int bit, loc, end, error, start;
886         char *bbp;
887         /* XXX ondisk32 */
888         fs = ip->i_e2fs;
889         ump = ip->i_ump;
890         if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0)
891                 return (0);
892         EXT2_UNLOCK(ump);
893         error = bread(ip->i_devvp, fsbtodb(fs,
894             e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
895             (int)fs->e2fs_bsize, NOCRED, &bp);
896         if (error) {
897                 brelse(bp);
898                 EXT2_LOCK(ump);
899                 return (0);
900         }
901         if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM)) {
902                 error = ext2_cg_block_bitmap_init(fs, cg, bp);
903                 if (error) {
904                         brelse(bp);
905                         EXT2_LOCK(ump);
906                         return (0);
907                 }
908         }
909         if (e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) == 0) {
910                 /*
911                  * Another thread allocated the last block in this
912                  * group while we were waiting for the buffer.
913                  */
914                 brelse(bp);
915                 EXT2_LOCK(ump);
916                 return (0);
917         }
918         bbp = (char *)bp->b_data;
919
920         if (dtog(fs, bpref) != cg)
921                 bpref = 0;
922         if (bpref != 0) {
923                 bpref = dtogd(fs, bpref);
924                 /*
925                  * if the requested block is available, use it
926                  */
927                 if (isclr(bbp, bpref)) {
928                         bno = bpref;
929                         goto gotit;
930                 }
931         }
932         /*
933          * no blocks in the requested cylinder, so take next
934          * available one in this cylinder group.
935          * first try to get 8 contigous blocks, then fall back to a single
936          * block.
937          */
938         if (bpref)
939                 start = dtogd(fs, bpref) / NBBY;
940         else
941                 start = 0;
942         end = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
943 retry:
944         runlen = 0;
945         runstart = 0;
946         for (loc = start; loc < end; loc++) {
947                 if (bbp[loc] == (char)0xff) {
948                         runlen = 0;
949                         continue;
950                 }
951
952                 /* Start of a run, find the number of high clear bits. */
953                 if (runlen == 0) {
954                         bit = fls(bbp[loc]);
955                         runlen = NBBY - bit;
956                         runstart = loc * NBBY + bit;
957                 } else if (bbp[loc] == 0) {
958                         /* Continue a run. */
959                         runlen += NBBY;
960                 } else {
961                         /*
962                          * Finish the current run.  If it isn't long
963                          * enough, start a new one.
964                          */
965                         bit = ffs(bbp[loc]) - 1;
966                         runlen += bit;
967                         if (runlen >= 8) {
968                                 bno = runstart;
969                                 goto gotit;
970                         }
971
972                         /* Run was too short, start a new one. */
973                         bit = fls(bbp[loc]);
974                         runlen = NBBY - bit;
975                         runstart = loc * NBBY + bit;
976                 }
977
978                 /* If the current run is long enough, use it. */
979                 if (runlen >= 8) {
980                         bno = runstart;
981                         goto gotit;
982                 }
983         }
984         if (start != 0) {
985                 end = start;
986                 start = 0;
987                 goto retry;
988         }
989         bno = ext2_mapsearch(fs, bbp, bpref);
990         if (bno < 0) {
991                 brelse(bp);
992                 EXT2_LOCK(ump);
993                 return (0);
994         }
995 gotit:
996 #ifdef INVARIANTS
997         if (isset(bbp, bno)) {
998                 printf("ext2fs_alloccgblk: cg=%d bno=%jd fs=%s\n",
999                     cg, (intmax_t)bno, fs->e2fs_fsmnt);
1000                 panic("ext2fs_alloccg: dup alloc");
1001         }
1002 #endif
1003         setbit(bbp, bno);
1004         EXT2_LOCK(ump);
1005         ext2_clusteracct(fs, bbp, cg, bno, -1);
1006         fs->e2fs_fbcount--;
1007         e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1008             e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1009         fs->e2fs_fmod = 1;
1010         EXT2_UNLOCK(ump);
1011         bdwrite(bp);
1012         return (((uint64_t)cg) * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1013 }
1014
1015 /*
1016  * Determine whether a cluster can be allocated.
1017  */
1018 static daddr_t
1019 ext2_clusteralloc(struct inode *ip, int cg, daddr_t bpref, int len)
1020 {
1021         struct m_ext2fs *fs;
1022         struct ext2mount *ump;
1023         struct buf *bp;
1024         char *bbp;
1025         int bit, error, got, i, loc, run;
1026         int32_t *lp;
1027         daddr_t bno;
1028
1029         fs = ip->i_e2fs;
1030         ump = ip->i_ump;
1031
1032         if (fs->e2fs_maxcluster[cg] < len)
1033                 return (0);
1034
1035         EXT2_UNLOCK(ump);
1036         error = bread(ip->i_devvp,
1037             fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1038             (int)fs->e2fs_bsize, NOCRED, &bp);
1039         if (error)
1040                 goto fail_lock;
1041
1042         bbp = (char *)bp->b_data;
1043         EXT2_LOCK(ump);
1044         /*
1045          * Check to see if a cluster of the needed size (or bigger) is
1046          * available in this cylinder group.
1047          */
1048         lp = &fs->e2fs_clustersum[cg].cs_sum[len];
1049         for (i = len; i <= fs->e2fs_contigsumsize; i++)
1050                 if (*lp++ > 0)
1051                         break;
1052         if (i > fs->e2fs_contigsumsize) {
1053                 /*
1054                  * Update the cluster summary information to reflect
1055                  * the true maximum-sized cluster so that future cluster
1056                  * allocation requests can avoid reading the bitmap only
1057                  * to find no cluster.
1058                  */
1059                 lp = &fs->e2fs_clustersum[cg].cs_sum[len - 1];
1060                 for (i = len - 1; i > 0; i--)
1061                         if (*lp-- > 0)
1062                                 break;
1063                 fs->e2fs_maxcluster[cg] = i;
1064                 goto fail;
1065         }
1066         EXT2_UNLOCK(ump);
1067
1068         /* Search the bitmap to find a big enough cluster like in FFS. */
1069         if (dtog(fs, bpref) != cg)
1070                 bpref = 0;
1071         if (bpref != 0)
1072                 bpref = dtogd(fs, bpref);
1073         loc = bpref / NBBY;
1074         bit = 1 << (bpref % NBBY);
1075         for (run = 0, got = bpref; got < fs->e2fs->e2fs_fpg; got++) {
1076                 if ((bbp[loc] & bit) != 0)
1077                         run = 0;
1078                 else {
1079                         run++;
1080                         if (run == len)
1081                                 break;
1082                 }
1083                 if ((got & (NBBY - 1)) != (NBBY - 1))
1084                         bit <<= 1;
1085                 else {
1086                         loc++;
1087                         bit = 1;
1088                 }
1089         }
1090
1091         if (got >= fs->e2fs->e2fs_fpg)
1092                 goto fail_lock;
1093
1094         /* Allocate the cluster that we found. */
1095         for (i = 1; i < len; i++)
1096                 if (!isclr(bbp, got - run + i))
1097                         panic("ext2_clusteralloc: map mismatch");
1098
1099         bno = got - run + 1;
1100         if (bno >= fs->e2fs->e2fs_fpg)
1101                 panic("ext2_clusteralloc: allocated out of group");
1102
1103         EXT2_LOCK(ump);
1104         for (i = 0; i < len; i += fs->e2fs_fpb) {
1105                 setbit(bbp, bno + i);
1106                 ext2_clusteracct(fs, bbp, cg, bno + i, -1);
1107                 fs->e2fs_fbcount--;
1108                 e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1109                     e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) - 1);
1110         }
1111         fs->e2fs_fmod = 1;
1112         EXT2_UNLOCK(ump);
1113
1114         bdwrite(bp);
1115         return (cg * fs->e2fs->e2fs_fpg + fs->e2fs->e2fs_first_dblock + bno);
1116
1117 fail_lock:
1118         EXT2_LOCK(ump);
1119 fail:
1120         brelse(bp);
1121         return (0);
1122 }
1123
1124 static int
1125 ext2_zero_inode_table(struct inode *ip, int cg)
1126 {
1127         struct m_ext2fs *fs;
1128         struct buf *bp;
1129         int i, all_blks, used_blks;
1130
1131         fs = ip->i_e2fs;
1132
1133         if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_ZEROED)
1134                 return (0);
1135
1136         all_blks = fs->e2fs->e2fs_inode_size * fs->e2fs->e2fs_ipg /
1137             fs->e2fs_bsize;
1138
1139         used_blks = howmany(fs->e2fs->e2fs_ipg -
1140             e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]),
1141             fs->e2fs_bsize / EXT2_INODE_SIZE(fs));
1142
1143         for (i = 0; i < all_blks - used_blks; i++) {
1144                 bp = getblk(ip->i_devvp, fsbtodb(fs,
1145                     e2fs_gd_get_i_tables(&fs->e2fs_gd[cg]) + used_blks + i),
1146                     fs->e2fs_bsize, 0, 0, 0);
1147                 if (!bp)
1148                         return (EIO);
1149
1150                 vfs_bio_bzero_buf(bp, 0, fs->e2fs_bsize);
1151                 bawrite(bp);
1152         }
1153
1154         fs->e2fs_gd[cg].ext4bgd_flags |= EXT2_BG_INODE_ZEROED;
1155
1156         return (0);
1157 }
1158
1159 /*
1160  * Determine whether an inode can be allocated.
1161  *
1162  * Check to see if an inode is available, and if it is,
1163  * allocate it using tode in the specified cylinder group.
1164  */
1165 static daddr_t
1166 ext2_nodealloccg(struct inode *ip, int cg, daddr_t ipref, int mode)
1167 {
1168         struct m_ext2fs *fs;
1169         struct buf *bp;
1170         struct ext2mount *ump;
1171         int error, start, len;
1172         char *ibp, *loc;
1173
1174         ipref--;        /* to avoid a lot of (ipref -1) */
1175         if (ipref == -1)
1176                 ipref = 0;
1177         fs = ip->i_e2fs;
1178         ump = ip->i_ump;
1179         if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0)
1180                 return (0);
1181         EXT2_UNLOCK(ump);
1182         error = bread(ip->i_devvp, fsbtodb(fs,
1183             e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1184             (int)fs->e2fs_bsize, NOCRED, &bp);
1185         if (error) {
1186                 brelse(bp);
1187                 EXT2_LOCK(ump);
1188                 return (0);
1189         }
1190         if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM)) {
1191                 if (fs->e2fs_gd[cg].ext4bgd_flags & EXT2_BG_INODE_UNINIT) {
1192                         memset(bp->b_data, 0, fs->e2fs_bsize);
1193                         fs->e2fs_gd[cg].ext4bgd_flags &= ~EXT2_BG_INODE_UNINIT;
1194                 }
1195                 error = ext2_zero_inode_table(ip, cg);
1196                 if (error) {
1197                         brelse(bp);
1198                         EXT2_LOCK(ump);
1199                         return (0);
1200                 }
1201         }
1202         if (e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) == 0) {
1203                 /*
1204                  * Another thread allocated the last i-node in this
1205                  * group while we were waiting for the buffer.
1206                  */
1207                 brelse(bp);
1208                 EXT2_LOCK(ump);
1209                 return (0);
1210         }
1211         ibp = (char *)bp->b_data;
1212         if (ipref) {
1213                 ipref %= fs->e2fs->e2fs_ipg;
1214                 if (isclr(ibp, ipref))
1215                         goto gotit;
1216         }
1217         start = ipref / NBBY;
1218         len = howmany(fs->e2fs->e2fs_ipg - ipref, NBBY);
1219         loc = memcchr(&ibp[start], 0xff, len);
1220         if (loc == NULL) {
1221                 len = start + 1;
1222                 start = 0;
1223                 loc = memcchr(&ibp[start], 0xff, len);
1224                 if (loc == NULL) {
1225                         printf("cg = %d, ipref = %lld, fs = %s\n",
1226                             cg, (long long)ipref, fs->e2fs_fsmnt);
1227                         panic("ext2fs_nodealloccg: map corrupted");
1228                         /* NOTREACHED */
1229                 }
1230         }
1231         ipref = (loc - ibp) * NBBY + ffs(~*loc) - 1;
1232 gotit:
1233         setbit(ibp, ipref);
1234         EXT2_LOCK(ump);
1235         e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1236             e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) - 1);
1237         if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM))
1238                 e2fs_gd_set_i_unused(&fs->e2fs_gd[cg],
1239                     e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]) - 1);
1240         fs->e2fs->e2fs_ficount--;
1241         fs->e2fs_fmod = 1;
1242         if ((mode & IFMT) == IFDIR) {
1243                 e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1244                     e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) + 1);
1245                 fs->e2fs_total_dir++;
1246         }
1247         EXT2_UNLOCK(ump);
1248         bdwrite(bp);
1249         return ((uint64_t)cg * fs->e2fs_ipg + ipref + 1);
1250 }
1251
1252 /*
1253  * Free a block or fragment.
1254  *
1255  */
1256 void
1257 ext2_blkfree(struct inode *ip, e4fs_daddr_t bno, long size)
1258 {
1259         struct m_ext2fs *fs;
1260         struct buf *bp;
1261         struct ext2mount *ump;
1262         int cg, error;
1263         char *bbp;
1264
1265         fs = ip->i_e2fs;
1266         ump = ip->i_ump;
1267         cg = dtog(fs, bno);
1268         if (bno >= fs->e2fs_bcount) {
1269                 printf("bad block %lld, ino %ju\n", (long long)bno,
1270                     (uintmax_t)ip->i_number);
1271                 ext2_fserr(fs, ip->i_uid, "bad block");
1272                 return;
1273         }
1274         error = bread(ip->i_devvp,
1275             fsbtodb(fs, e2fs_gd_get_b_bitmap(&fs->e2fs_gd[cg])),
1276             (int)fs->e2fs_bsize, NOCRED, &bp);
1277         if (error) {
1278                 brelse(bp);
1279                 return;
1280         }
1281         bbp = (char *)bp->b_data;
1282         bno = dtogd(fs, bno);
1283         if (isclr(bbp, bno)) {
1284                 printf("block = %lld, fs = %s\n",
1285                     (long long)bno, fs->e2fs_fsmnt);
1286                 panic("ext2_blkfree: freeing free block");
1287         }
1288         clrbit(bbp, bno);
1289         EXT2_LOCK(ump);
1290         ext2_clusteracct(fs, bbp, cg, bno, 1);
1291         fs->e2fs_fbcount++;
1292         e2fs_gd_set_nbfree(&fs->e2fs_gd[cg],
1293             e2fs_gd_get_nbfree(&fs->e2fs_gd[cg]) + 1);
1294         fs->e2fs_fmod = 1;
1295         EXT2_UNLOCK(ump);
1296         bdwrite(bp);
1297 }
1298
1299 /*
1300  * Free an inode.
1301  *
1302  */
1303 int
1304 ext2_vfree(struct vnode *pvp, ino_t ino, int mode)
1305 {
1306         struct m_ext2fs *fs;
1307         struct inode *pip;
1308         struct buf *bp;
1309         struct ext2mount *ump;
1310         int error, cg;
1311         char *ibp;
1312
1313         pip = VTOI(pvp);
1314         fs = pip->i_e2fs;
1315         ump = pip->i_ump;
1316         if ((u_int)ino > fs->e2fs_ipg * fs->e2fs_gcount)
1317                 panic("ext2_vfree: range: devvp = %p, ino = %ju, fs = %s",
1318                     pip->i_devvp, (uintmax_t)ino, fs->e2fs_fsmnt);
1319
1320         cg = ino_to_cg(fs, ino);
1321         error = bread(pip->i_devvp,
1322             fsbtodb(fs, e2fs_gd_get_i_bitmap(&fs->e2fs_gd[cg])),
1323             (int)fs->e2fs_bsize, NOCRED, &bp);
1324         if (error) {
1325                 brelse(bp);
1326                 return (0);
1327         }
1328         ibp = (char *)bp->b_data;
1329         ino = (ino - 1) % fs->e2fs->e2fs_ipg;
1330         if (isclr(ibp, ino)) {
1331                 printf("ino = %llu, fs = %s\n",
1332                     (unsigned long long)ino, fs->e2fs_fsmnt);
1333                 if (fs->e2fs_ronly == 0)
1334                         panic("ext2_vfree: freeing free inode");
1335         }
1336         clrbit(ibp, ino);
1337         EXT2_LOCK(ump);
1338         fs->e2fs->e2fs_ficount++;
1339         e2fs_gd_set_nifree(&fs->e2fs_gd[cg],
1340             e2fs_gd_get_nifree(&fs->e2fs_gd[cg]) + 1);
1341         if (EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM))
1342                 e2fs_gd_set_i_unused(&fs->e2fs_gd[cg],
1343                     e2fs_gd_get_i_unused(&fs->e2fs_gd[cg]) + 1);
1344         if ((mode & IFMT) == IFDIR) {
1345                 e2fs_gd_set_ndirs(&fs->e2fs_gd[cg],
1346                     e2fs_gd_get_ndirs(&fs->e2fs_gd[cg]) - 1);
1347                 fs->e2fs_total_dir--;
1348         }
1349         fs->e2fs_fmod = 1;
1350         EXT2_UNLOCK(ump);
1351         bdwrite(bp);
1352         return (0);
1353 }
1354
1355 /*
1356  * Find a block in the specified cylinder group.
1357  *
1358  * It is a panic if a request is made to find a block if none are
1359  * available.
1360  */
1361 static daddr_t
1362 ext2_mapsearch(struct m_ext2fs *fs, char *bbp, daddr_t bpref)
1363 {
1364         char *loc;
1365         int start, len;
1366
1367         /*
1368          * find the fragment by searching through the free block
1369          * map for an appropriate bit pattern
1370          */
1371         if (bpref)
1372                 start = dtogd(fs, bpref) / NBBY;
1373         else
1374                 start = 0;
1375         len = howmany(fs->e2fs->e2fs_fpg, NBBY) - start;
1376         loc = memcchr(&bbp[start], 0xff, len);
1377         if (loc == NULL) {
1378                 len = start + 1;
1379                 start = 0;
1380                 loc = memcchr(&bbp[start], 0xff, len);
1381                 if (loc == NULL) {
1382                         printf("start = %d, len = %d, fs = %s\n",
1383                             start, len, fs->e2fs_fsmnt);
1384                         panic("ext2_mapsearch: map corrupted");
1385                         /* NOTREACHED */
1386                 }
1387         }
1388         return ((loc - bbp) * NBBY + ffs(~*loc) - 1);
1389 }
1390
1391 /*
1392  * Fserr prints the name of a filesystem with an error diagnostic.
1393  *
1394  * The form of the error message is:
1395  *      fs: error message
1396  */
1397 void
1398 ext2_fserr(struct m_ext2fs *fs, uid_t uid, char *cp)
1399 {
1400
1401         log(LOG_ERR, "uid %u on %s: %s\n", uid, fs->e2fs_fsmnt, cp);
1402 }
1403
1404 int
1405 ext2_cg_has_sb(struct m_ext2fs *fs, int cg)
1406 {
1407         int a3, a5, a7;
1408
1409         if (cg == 0)
1410                 return (1);
1411
1412         if (EXT2_HAS_COMPAT_FEATURE(fs, EXT2F_COMPAT_SPARSESUPER2)) {
1413                 if (cg == fs->e2fs->e4fs_backup_bgs[0] ||
1414                     cg == fs->e2fs->e4fs_backup_bgs[1])
1415                         return (1);
1416                 return (0);
1417         }
1418
1419         if ((cg <= 1) ||
1420             !EXT2_HAS_RO_COMPAT_FEATURE(fs, EXT2F_ROCOMPAT_SPARSESUPER))
1421                 return (1);
1422
1423         if (!(cg & 1))
1424                 return (0);
1425
1426         for (a3 = 3, a5 = 5, a7 = 7;
1427             a3 <= cg || a5 <= cg || a7 <= cg;
1428             a3 *= 3, a5 *= 5, a7 *= 7)
1429                 if (cg == a3 || cg == a5 || cg == a7)
1430                         return (1);
1431         return (0);
1432 }