]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/ufs/ffs/ffs_alloc.c
MFC r309400:
[FreeBSD/stable/8.git] / sys / ufs / ffs / ffs_alloc.c
1 /*-
2  * Copyright (c) 2002 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by Marshall
6  * Kirk McKusick and Network Associates Laboratories, the Security
7  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
8  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
9  * research program
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * Copyright (c) 1982, 1986, 1989, 1993
33  *      The Regents of the University of California.  All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 4. Neither the name of the University nor the names of its contributors
44  *    may be used to endorse or promote products derived from this software
45  *    without specific prior written permission.
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57  * SUCH DAMAGE.
58  *
59  *      @(#)ffs_alloc.c 8.18 (Berkeley) 5/26/95
60  */
61
62 #include <sys/cdefs.h>
63 __FBSDID("$FreeBSD$");
64
65 #include "opt_quota.h"
66
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/bio.h>
70 #include <sys/buf.h>
71 #include <sys/conf.h>
72 #include <sys/file.h>
73 #include <sys/filedesc.h>
74 #include <sys/priv.h>
75 #include <sys/proc.h>
76 #include <sys/vnode.h>
77 #include <sys/mount.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/syslog.h>
81 #include <sys/taskqueue.h>
82
83 #include <geom/geom.h>
84
85 #include <ufs/ufs/extattr.h>
86 #include <ufs/ufs/quota.h>
87 #include <ufs/ufs/inode.h>
88 #include <ufs/ufs/ufs_extern.h>
89 #include <ufs/ufs/ufsmount.h>
90
91 #include <ufs/ffs/fs.h>
92 #include <ufs/ffs/ffs_extern.h>
93
94 typedef ufs2_daddr_t allocfcn_t(struct inode *ip, u_int cg, ufs2_daddr_t bpref,
95                                   int size);
96
97 static ufs2_daddr_t ffs_alloccg(struct inode *, u_int, ufs2_daddr_t, int);
98 static ufs2_daddr_t
99               ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t);
100 static void     ffs_blkfree_cg(struct ufsmount *, struct fs *,
101                     struct vnode *, ufs2_daddr_t, long, ino_t);
102 static void     ffs_blkfree_trim_completed(struct bio *);
103 static void     ffs_blkfree_trim_task(void *ctx, int pending __unused);
104 #ifdef INVARIANTS
105 static int      ffs_checkblk(struct inode *, ufs2_daddr_t, long);
106 #endif
107 static ufs2_daddr_t ffs_clusteralloc(struct inode *, u_int, ufs2_daddr_t, int);
108 static void     ffs_clusteracct(struct ufsmount *, struct fs *, struct cg *,
109                     ufs1_daddr_t, int);
110 static ino_t    ffs_dirpref(struct inode *);
111 static ufs2_daddr_t ffs_fragextend(struct inode *, u_int, ufs2_daddr_t,
112                     int, int);
113 static void     ffs_fserr(struct fs *, ino_t, char *);
114 static ufs2_daddr_t     ffs_hashalloc
115                 (struct inode *, u_int, ufs2_daddr_t, int, allocfcn_t *);
116 static ufs2_daddr_t ffs_nodealloccg(struct inode *, u_int, ufs2_daddr_t, int);
117 static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
118 static int      ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
119 static int      ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
120
121 /*
122  * Allocate a block in the filesystem.
123  *
124  * The size of the requested block is given, which must be some
125  * multiple of fs_fsize and <= fs_bsize.
126  * A preference may be optionally specified. If a preference is given
127  * the following hierarchy is used to allocate a block:
128  *   1) allocate the requested block.
129  *   2) allocate a rotationally optimal block in the same cylinder.
130  *   3) allocate a block in the same cylinder group.
131  *   4) quadradically rehash into other cylinder groups, until an
132  *      available block is located.
133  * If no block preference is given the following hierarchy is used
134  * to allocate a block:
135  *   1) allocate a block in the cylinder group that contains the
136  *      inode for the file.
137  *   2) quadradically rehash into other cylinder groups, until an
138  *      available block is located.
139  */
140 int
141 ffs_alloc(ip, lbn, bpref, size, flags, cred, bnp)
142         struct inode *ip;
143         ufs2_daddr_t lbn, bpref;
144         int size, flags;
145         struct ucred *cred;
146         ufs2_daddr_t *bnp;
147 {
148         struct fs *fs;
149         struct ufsmount *ump;
150         ufs2_daddr_t bno;
151         u_int cg, reclaimed;
152         static struct timeval lastfail;
153         static int curfail;
154         int64_t delta;
155 #ifdef QUOTA
156         int error;
157 #endif
158
159         *bnp = 0;
160         fs = ip->i_fs;
161         ump = ip->i_ump;
162         mtx_assert(UFS_MTX(ump), MA_OWNED);
163 #ifdef INVARIANTS
164         if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
165                 printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
166                     devtoname(ip->i_dev), (long)fs->fs_bsize, size,
167                     fs->fs_fsmnt);
168                 panic("ffs_alloc: bad size");
169         }
170         if (cred == NOCRED)
171                 panic("ffs_alloc: missing credential");
172 #endif /* INVARIANTS */
173         reclaimed = 0;
174 retry:
175 #ifdef QUOTA
176         UFS_UNLOCK(ump);
177         error = chkdq(ip, btodb(size), cred, 0);
178         if (error)
179                 return (error);
180         UFS_LOCK(ump);
181 #endif
182         if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
183                 goto nospace;
184         if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
185             freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
186                 goto nospace;
187         if (bpref >= fs->fs_size)
188                 bpref = 0;
189         if (bpref == 0)
190                 cg = ino_to_cg(fs, ip->i_number);
191         else
192                 cg = dtog(fs, bpref);
193         bno = ffs_hashalloc(ip, cg, bpref, size, ffs_alloccg);
194         if (bno > 0) {
195                 delta = btodb(size);
196                 if (ip->i_flag & IN_SPACECOUNTED) {
197                         UFS_LOCK(ump);
198                         fs->fs_pendingblocks += delta;
199                         UFS_UNLOCK(ump);
200                 }
201                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
202                 if (flags & IO_EXT)
203                         ip->i_flag |= IN_CHANGE;
204                 else
205                         ip->i_flag |= IN_CHANGE | IN_UPDATE;
206                 *bnp = bno;
207                 return (0);
208         }
209 nospace:
210 #ifdef QUOTA
211         UFS_UNLOCK(ump);
212         /*
213          * Restore user's disk quota because allocation failed.
214          */
215         (void) chkdq(ip, -btodb(size), cred, FORCE);
216         UFS_LOCK(ump);
217 #endif
218         if (fs->fs_pendingblocks > 0 && reclaimed == 0) {
219                 reclaimed = 1;
220                 softdep_request_cleanup(fs, ITOV(ip));
221                 goto retry;
222         }
223         UFS_UNLOCK(ump);
224         if (ppsratecheck(&lastfail, &curfail, 1)) {
225                 ffs_fserr(fs, ip->i_number, "filesystem full");
226                 uprintf("\n%s: write failed, filesystem is full\n",
227                     fs->fs_fsmnt);
228         }
229         return (ENOSPC);
230 }
231
232 /*
233  * Reallocate a fragment to a bigger size
234  *
235  * The number and size of the old block is given, and a preference
236  * and new size is also specified. The allocator attempts to extend
237  * the original block. Failing that, the regular block allocator is
238  * invoked to get an appropriate block.
239  */
240 int
241 ffs_realloccg(ip, lbprev, bprev, bpref, osize, nsize, flags, cred, bpp)
242         struct inode *ip;
243         ufs2_daddr_t lbprev;
244         ufs2_daddr_t bprev;
245         ufs2_daddr_t bpref;
246         int osize, nsize, flags;
247         struct ucred *cred;
248         struct buf **bpp;
249 {
250         struct vnode *vp;
251         struct fs *fs;
252         struct buf *bp;
253         struct ufsmount *ump;
254         u_int cg, request, reclaimed;
255         int error;
256         ufs2_daddr_t bno;
257         static struct timeval lastfail;
258         static int curfail;
259         int64_t delta;
260
261         *bpp = 0;
262         vp = ITOV(ip);
263         fs = ip->i_fs;
264         bp = NULL;
265         ump = ip->i_ump;
266         mtx_assert(UFS_MTX(ump), MA_OWNED);
267 #ifdef INVARIANTS
268         if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
269                 panic("ffs_realloccg: allocation on suspended filesystem");
270         if ((u_int)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
271             (u_int)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
272                 printf(
273                 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
274                     devtoname(ip->i_dev), (long)fs->fs_bsize, osize,
275                     nsize, fs->fs_fsmnt);
276                 panic("ffs_realloccg: bad size");
277         }
278         if (cred == NOCRED)
279                 panic("ffs_realloccg: missing credential");
280 #endif /* INVARIANTS */
281         reclaimed = 0;
282 retry:
283         if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0) &&
284             freespace(fs, fs->fs_minfree) -  numfrags(fs, nsize - osize) < 0) {
285                 goto nospace;
286         }
287         if (bprev == 0) {
288                 printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
289                     devtoname(ip->i_dev), (long)fs->fs_bsize, (intmax_t)bprev,
290                     fs->fs_fsmnt);
291                 panic("ffs_realloccg: bad bprev");
292         }
293         UFS_UNLOCK(ump);
294         /*
295          * Allocate the extra space in the buffer.
296          */
297         error = bread(vp, lbprev, osize, NOCRED, &bp);
298         if (error) {
299                 brelse(bp);
300                 return (error);
301         }
302
303         if (bp->b_blkno == bp->b_lblkno) {
304                 if (lbprev >= NDADDR)
305                         panic("ffs_realloccg: lbprev out of range");
306                 bp->b_blkno = fsbtodb(fs, bprev);
307         }
308
309 #ifdef QUOTA
310         error = chkdq(ip, btodb(nsize - osize), cred, 0);
311         if (error) {
312                 brelse(bp);
313                 return (error);
314         }
315 #endif
316         /*
317          * Check for extension in the existing location.
318          */
319         cg = dtog(fs, bprev);
320         UFS_LOCK(ump);
321         bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
322         if (bno) {
323                 if (bp->b_blkno != fsbtodb(fs, bno))
324                         panic("ffs_realloccg: bad blockno");
325                 delta = btodb(nsize - osize);
326                 if (ip->i_flag & IN_SPACECOUNTED) {
327                         UFS_LOCK(ump);
328                         fs->fs_pendingblocks += delta;
329                         UFS_UNLOCK(ump);
330                 }
331                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
332                 if (flags & IO_EXT)
333                         ip->i_flag |= IN_CHANGE;
334                 else
335                         ip->i_flag |= IN_CHANGE | IN_UPDATE;
336                 allocbuf(bp, nsize);
337                 bp->b_flags |= B_DONE;
338                 bzero(bp->b_data + osize, nsize - osize);
339                 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
340                         vfs_bio_set_valid(bp, osize, nsize - osize);
341                 *bpp = bp;
342                 return (0);
343         }
344         /*
345          * Allocate a new disk location.
346          */
347         if (bpref >= fs->fs_size)
348                 bpref = 0;
349         switch ((int)fs->fs_optim) {
350         case FS_OPTSPACE:
351                 /*
352                  * Allocate an exact sized fragment. Although this makes
353                  * best use of space, we will waste time relocating it if
354                  * the file continues to grow. If the fragmentation is
355                  * less than half of the minimum free reserve, we choose
356                  * to begin optimizing for time.
357                  */
358                 request = nsize;
359                 if (fs->fs_minfree <= 5 ||
360                     fs->fs_cstotal.cs_nffree >
361                     (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
362                         break;
363                 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
364                         fs->fs_fsmnt);
365                 fs->fs_optim = FS_OPTTIME;
366                 break;
367         case FS_OPTTIME:
368                 /*
369                  * At this point we have discovered a file that is trying to
370                  * grow a small fragment to a larger fragment. To save time,
371                  * we allocate a full sized block, then free the unused portion.
372                  * If the file continues to grow, the `ffs_fragextend' call
373                  * above will be able to grow it in place without further
374                  * copying. If aberrant programs cause disk fragmentation to
375                  * grow within 2% of the free reserve, we choose to begin
376                  * optimizing for space.
377                  */
378                 request = fs->fs_bsize;
379                 if (fs->fs_cstotal.cs_nffree <
380                     (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
381                         break;
382                 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
383                         fs->fs_fsmnt);
384                 fs->fs_optim = FS_OPTSPACE;
385                 break;
386         default:
387                 printf("dev = %s, optim = %ld, fs = %s\n",
388                     devtoname(ip->i_dev), (long)fs->fs_optim, fs->fs_fsmnt);
389                 panic("ffs_realloccg: bad optim");
390                 /* NOTREACHED */
391         }
392         bno = ffs_hashalloc(ip, cg, bpref, request, ffs_alloccg);
393         if (bno > 0) {
394                 bp->b_blkno = fsbtodb(fs, bno);
395                 if (!DOINGSOFTDEP(vp))
396                         ffs_blkfree(ump, fs, ip->i_devvp, bprev, (long)osize,
397                             ip->i_number);
398                 if (nsize < request)
399                         ffs_blkfree(ump, fs, ip->i_devvp,
400                             bno + numfrags(fs, nsize),
401                             (long)(request - nsize), ip->i_number);
402                 delta = btodb(nsize - osize);
403                 if (ip->i_flag & IN_SPACECOUNTED) {
404                         UFS_LOCK(ump);
405                         fs->fs_pendingblocks += delta;
406                         UFS_UNLOCK(ump);
407                 }
408                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
409                 if (flags & IO_EXT)
410                         ip->i_flag |= IN_CHANGE;
411                 else
412                         ip->i_flag |= IN_CHANGE | IN_UPDATE;
413                 allocbuf(bp, nsize);
414                 bp->b_flags |= B_DONE;
415                 bzero(bp->b_data + osize, nsize - osize);
416                 if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
417                         vfs_bio_set_valid(bp, osize, nsize - osize);
418                 *bpp = bp;
419                 return (0);
420         }
421 #ifdef QUOTA
422         UFS_UNLOCK(ump);
423         /*
424          * Restore user's disk quota because allocation failed.
425          */
426         (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
427         UFS_LOCK(ump);
428 #endif
429 nospace:
430         /*
431          * no space available
432          */
433         if (fs->fs_pendingblocks > 0 && reclaimed == 0) {
434                 reclaimed = 1;
435                 softdep_request_cleanup(fs, vp);
436                 UFS_UNLOCK(ump);
437                 if (bp) {
438                         brelse(bp);
439                         bp = NULL;
440                 }
441                 UFS_LOCK(ump);
442                 goto retry;
443         }
444         UFS_UNLOCK(ump);
445         if (bp)
446                 brelse(bp);
447         if (ppsratecheck(&lastfail, &curfail, 1)) {
448                 ffs_fserr(fs, ip->i_number, "filesystem full");
449                 uprintf("\n%s: write failed, filesystem is full\n",
450                     fs->fs_fsmnt);
451         }
452         return (ENOSPC);
453 }
454
455 /*
456  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
457  *
458  * The vnode and an array of buffer pointers for a range of sequential
459  * logical blocks to be made contiguous is given. The allocator attempts
460  * to find a range of sequential blocks starting as close as possible
461  * from the end of the allocation for the logical block immediately
462  * preceding the current range. If successful, the physical block numbers
463  * in the buffer pointers and in the inode are changed to reflect the new
464  * allocation. If unsuccessful, the allocation is left unchanged. The
465  * success in doing the reallocation is returned. Note that the error
466  * return is not reflected back to the user. Rather the previous block
467  * allocation will be used.
468  */
469
470 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
471
472 static int doasyncfree = 1;
473 SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0, "");
474
475 static int doreallocblks = 1;
476 SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
477
478 #ifdef DEBUG
479 static volatile int prtrealloc = 0;
480 #endif
481
482 int
483 ffs_reallocblks(ap)
484         struct vop_reallocblks_args /* {
485                 struct vnode *a_vp;
486                 struct cluster_save *a_buflist;
487         } */ *ap;
488 {
489
490         if (doreallocblks == 0)
491                 return (ENOSPC);
492         if (VTOI(ap->a_vp)->i_ump->um_fstype == UFS1)
493                 return (ffs_reallocblks_ufs1(ap));
494         return (ffs_reallocblks_ufs2(ap));
495 }
496         
497 static int
498 ffs_reallocblks_ufs1(ap)
499         struct vop_reallocblks_args /* {
500                 struct vnode *a_vp;
501                 struct cluster_save *a_buflist;
502         } */ *ap;
503 {
504         struct fs *fs;
505         struct inode *ip;
506         struct vnode *vp;
507         struct buf *sbp, *ebp;
508         ufs1_daddr_t *bap, *sbap, *ebap = 0;
509         struct cluster_save *buflist;
510         struct ufsmount *ump;
511         ufs_lbn_t start_lbn, end_lbn;
512         ufs1_daddr_t soff, newblk, blkno;
513         ufs2_daddr_t pref;
514         struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
515         int i, len, start_lvl, end_lvl, ssize;
516
517         vp = ap->a_vp;
518         ip = VTOI(vp);
519         fs = ip->i_fs;
520         ump = ip->i_ump;
521         if (fs->fs_contigsumsize <= 0)
522                 return (ENOSPC);
523         buflist = ap->a_buflist;
524         len = buflist->bs_nchildren;
525         start_lbn = buflist->bs_children[0]->b_lblkno;
526         end_lbn = start_lbn + len - 1;
527 #ifdef INVARIANTS
528         for (i = 0; i < len; i++)
529                 if (!ffs_checkblk(ip,
530                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
531                         panic("ffs_reallocblks: unallocated block 1");
532         for (i = 1; i < len; i++)
533                 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
534                         panic("ffs_reallocblks: non-logical cluster");
535         blkno = buflist->bs_children[0]->b_blkno;
536         ssize = fsbtodb(fs, fs->fs_frag);
537         for (i = 1; i < len - 1; i++)
538                 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
539                         panic("ffs_reallocblks: non-physical cluster %d", i);
540 #endif
541         /*
542          * If the latest allocation is in a new cylinder group, assume that
543          * the filesystem has decided to move and do not force it back to
544          * the previous cylinder group.
545          */
546         if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
547             dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
548                 return (ENOSPC);
549         if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
550             ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
551                 return (ENOSPC);
552         /*
553          * Get the starting offset and block map for the first block.
554          */
555         if (start_lvl == 0) {
556                 sbap = &ip->i_din1->di_db[0];
557                 soff = start_lbn;
558         } else {
559                 idp = &start_ap[start_lvl - 1];
560                 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
561                         brelse(sbp);
562                         return (ENOSPC);
563                 }
564                 sbap = (ufs1_daddr_t *)sbp->b_data;
565                 soff = idp->in_off;
566         }
567         /*
568          * If the block range spans two block maps, get the second map.
569          */
570         if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
571                 ssize = len;
572         } else {
573 #ifdef INVARIANTS
574                 if (start_lvl > 0 &&
575                     start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
576                         panic("ffs_reallocblk: start == end");
577 #endif
578                 ssize = len - (idp->in_off + 1);
579                 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
580                         goto fail;
581                 ebap = (ufs1_daddr_t *)ebp->b_data;
582         }
583         /*
584          * Find the preferred location for the cluster.
585          */
586         UFS_LOCK(ump);
587         pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
588         /*
589          * Search the block map looking for an allocation of the desired size.
590          */
591         if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
592             len, ffs_clusteralloc)) == 0) {
593                 UFS_UNLOCK(ump);
594                 goto fail;
595         }
596         /*
597          * We have found a new contiguous block.
598          *
599          * First we have to replace the old block pointers with the new
600          * block pointers in the inode and indirect blocks associated
601          * with the file.
602          */
603 #ifdef DEBUG
604         if (prtrealloc)
605                 printf("realloc: ino %d, lbns %jd-%jd\n\told:", ip->i_number,
606                     (intmax_t)start_lbn, (intmax_t)end_lbn);
607 #endif
608         blkno = newblk;
609         for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
610                 if (i == ssize) {
611                         bap = ebap;
612                         soff = -i;
613                 }
614 #ifdef INVARIANTS
615                 if (!ffs_checkblk(ip,
616                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
617                         panic("ffs_reallocblks: unallocated block 2");
618                 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
619                         panic("ffs_reallocblks: alloc mismatch");
620 #endif
621 #ifdef DEBUG
622                 if (prtrealloc)
623                         printf(" %d,", *bap);
624 #endif
625                 if (DOINGSOFTDEP(vp)) {
626                         if (sbap == &ip->i_din1->di_db[0] && i < ssize)
627                                 softdep_setup_allocdirect(ip, start_lbn + i,
628                                     blkno, *bap, fs->fs_bsize, fs->fs_bsize,
629                                     buflist->bs_children[i]);
630                         else
631                                 softdep_setup_allocindir_page(ip, start_lbn + i,
632                                     i < ssize ? sbp : ebp, soff + i, blkno,
633                                     *bap, buflist->bs_children[i]);
634                 }
635                 *bap++ = blkno;
636         }
637         /*
638          * Next we must write out the modified inode and indirect blocks.
639          * For strict correctness, the writes should be synchronous since
640          * the old block values may have been written to disk. In practise
641          * they are almost never written, but if we are concerned about
642          * strict correctness, the `doasyncfree' flag should be set to zero.
643          *
644          * The test on `doasyncfree' should be changed to test a flag
645          * that shows whether the associated buffers and inodes have
646          * been written. The flag should be set when the cluster is
647          * started and cleared whenever the buffer or inode is flushed.
648          * We can then check below to see if it is set, and do the
649          * synchronous write only when it has been cleared.
650          */
651         if (sbap != &ip->i_din1->di_db[0]) {
652                 if (doasyncfree)
653                         bdwrite(sbp);
654                 else
655                         bwrite(sbp);
656         } else {
657                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
658                 if (!doasyncfree)
659                         ffs_update(vp, 1);
660         }
661         if (ssize < len) {
662                 if (doasyncfree)
663                         bdwrite(ebp);
664                 else
665                         bwrite(ebp);
666         }
667         /*
668          * Last, free the old blocks and assign the new blocks to the buffers.
669          */
670 #ifdef DEBUG
671         if (prtrealloc)
672                 printf("\n\tnew:");
673 #endif
674         for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
675                 if (!DOINGSOFTDEP(vp))
676                         ffs_blkfree(ump, fs, ip->i_devvp,
677                             dbtofsb(fs, buflist->bs_children[i]->b_blkno),
678                             fs->fs_bsize, ip->i_number);
679                 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
680 #ifdef INVARIANTS
681                 if (!ffs_checkblk(ip,
682                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
683                         panic("ffs_reallocblks: unallocated block 3");
684 #endif
685 #ifdef DEBUG
686                 if (prtrealloc)
687                         printf(" %d,", blkno);
688 #endif
689         }
690 #ifdef DEBUG
691         if (prtrealloc) {
692                 prtrealloc--;
693                 printf("\n");
694         }
695 #endif
696         return (0);
697
698 fail:
699         if (ssize < len)
700                 brelse(ebp);
701         if (sbap != &ip->i_din1->di_db[0])
702                 brelse(sbp);
703         return (ENOSPC);
704 }
705
706 static int
707 ffs_reallocblks_ufs2(ap)
708         struct vop_reallocblks_args /* {
709                 struct vnode *a_vp;
710                 struct cluster_save *a_buflist;
711         } */ *ap;
712 {
713         struct fs *fs;
714         struct inode *ip;
715         struct vnode *vp;
716         struct buf *sbp, *ebp;
717         ufs2_daddr_t *bap, *sbap, *ebap = 0;
718         struct cluster_save *buflist;
719         struct ufsmount *ump;
720         ufs_lbn_t start_lbn, end_lbn;
721         ufs2_daddr_t soff, newblk, blkno, pref;
722         struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
723         int i, len, start_lvl, end_lvl, ssize;
724
725         vp = ap->a_vp;
726         ip = VTOI(vp);
727         fs = ip->i_fs;
728         ump = ip->i_ump;
729         if (fs->fs_contigsumsize <= 0)
730                 return (ENOSPC);
731         buflist = ap->a_buflist;
732         len = buflist->bs_nchildren;
733         start_lbn = buflist->bs_children[0]->b_lblkno;
734         end_lbn = start_lbn + len - 1;
735 #ifdef INVARIANTS
736         for (i = 0; i < len; i++)
737                 if (!ffs_checkblk(ip,
738                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
739                         panic("ffs_reallocblks: unallocated block 1");
740         for (i = 1; i < len; i++)
741                 if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
742                         panic("ffs_reallocblks: non-logical cluster");
743         blkno = buflist->bs_children[0]->b_blkno;
744         ssize = fsbtodb(fs, fs->fs_frag);
745         for (i = 1; i < len - 1; i++)
746                 if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
747                         panic("ffs_reallocblks: non-physical cluster %d", i);
748 #endif
749         /*
750          * If the latest allocation is in a new cylinder group, assume that
751          * the filesystem has decided to move and do not force it back to
752          * the previous cylinder group.
753          */
754         if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
755             dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
756                 return (ENOSPC);
757         if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
758             ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
759                 return (ENOSPC);
760         /*
761          * Get the starting offset and block map for the first block.
762          */
763         if (start_lvl == 0) {
764                 sbap = &ip->i_din2->di_db[0];
765                 soff = start_lbn;
766         } else {
767                 idp = &start_ap[start_lvl - 1];
768                 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
769                         brelse(sbp);
770                         return (ENOSPC);
771                 }
772                 sbap = (ufs2_daddr_t *)sbp->b_data;
773                 soff = idp->in_off;
774         }
775         /*
776          * If the block range spans two block maps, get the second map.
777          */
778         if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
779                 ssize = len;
780         } else {
781 #ifdef INVARIANTS
782                 if (start_lvl > 0 &&
783                     start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
784                         panic("ffs_reallocblk: start == end");
785 #endif
786                 ssize = len - (idp->in_off + 1);
787                 if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
788                         goto fail;
789                 ebap = (ufs2_daddr_t *)ebp->b_data;
790         }
791         /*
792          * Find the preferred location for the cluster.
793          */
794         UFS_LOCK(ump);
795         pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
796         /*
797          * Search the block map looking for an allocation of the desired size.
798          */
799         if ((newblk = ffs_hashalloc(ip, dtog(fs, pref), pref,
800             len, ffs_clusteralloc)) == 0) {
801                 UFS_UNLOCK(ump);
802                 goto fail;
803         }
804         /*
805          * We have found a new contiguous block.
806          *
807          * First we have to replace the old block pointers with the new
808          * block pointers in the inode and indirect blocks associated
809          * with the file.
810          */
811 #ifdef DEBUG
812         if (prtrealloc)
813                 printf("realloc: ino %d, lbns %jd-%jd\n\told:", ip->i_number,
814                     (intmax_t)start_lbn, (intmax_t)end_lbn);
815 #endif
816         blkno = newblk;
817         for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
818                 if (i == ssize) {
819                         bap = ebap;
820                         soff = -i;
821                 }
822 #ifdef INVARIANTS
823                 if (!ffs_checkblk(ip,
824                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
825                         panic("ffs_reallocblks: unallocated block 2");
826                 if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
827                         panic("ffs_reallocblks: alloc mismatch");
828 #endif
829 #ifdef DEBUG
830                 if (prtrealloc)
831                         printf(" %jd,", (intmax_t)*bap);
832 #endif
833                 if (DOINGSOFTDEP(vp)) {
834                         if (sbap == &ip->i_din2->di_db[0] && i < ssize)
835                                 softdep_setup_allocdirect(ip, start_lbn + i,
836                                     blkno, *bap, fs->fs_bsize, fs->fs_bsize,
837                                     buflist->bs_children[i]);
838                         else
839                                 softdep_setup_allocindir_page(ip, start_lbn + i,
840                                     i < ssize ? sbp : ebp, soff + i, blkno,
841                                     *bap, buflist->bs_children[i]);
842                 }
843                 *bap++ = blkno;
844         }
845         /*
846          * Next we must write out the modified inode and indirect blocks.
847          * For strict correctness, the writes should be synchronous since
848          * the old block values may have been written to disk. In practise
849          * they are almost never written, but if we are concerned about
850          * strict correctness, the `doasyncfree' flag should be set to zero.
851          *
852          * The test on `doasyncfree' should be changed to test a flag
853          * that shows whether the associated buffers and inodes have
854          * been written. The flag should be set when the cluster is
855          * started and cleared whenever the buffer or inode is flushed.
856          * We can then check below to see if it is set, and do the
857          * synchronous write only when it has been cleared.
858          */
859         if (sbap != &ip->i_din2->di_db[0]) {
860                 if (doasyncfree)
861                         bdwrite(sbp);
862                 else
863                         bwrite(sbp);
864         } else {
865                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
866                 if (!doasyncfree)
867                         ffs_update(vp, 1);
868         }
869         if (ssize < len) {
870                 if (doasyncfree)
871                         bdwrite(ebp);
872                 else
873                         bwrite(ebp);
874         }
875         /*
876          * Last, free the old blocks and assign the new blocks to the buffers.
877          */
878 #ifdef DEBUG
879         if (prtrealloc)
880                 printf("\n\tnew:");
881 #endif
882         for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
883                 if (!DOINGSOFTDEP(vp))
884                         ffs_blkfree(ump, fs, ip->i_devvp,
885                             dbtofsb(fs, buflist->bs_children[i]->b_blkno),
886                             fs->fs_bsize, ip->i_number);
887                 buflist->bs_children[i]->b_blkno = fsbtodb(fs, blkno);
888 #ifdef INVARIANTS
889                 if (!ffs_checkblk(ip,
890                    dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
891                         panic("ffs_reallocblks: unallocated block 3");
892 #endif
893 #ifdef DEBUG
894                 if (prtrealloc)
895                         printf(" %jd,", (intmax_t)blkno);
896 #endif
897         }
898 #ifdef DEBUG
899         if (prtrealloc) {
900                 prtrealloc--;
901                 printf("\n");
902         }
903 #endif
904         return (0);
905
906 fail:
907         if (ssize < len)
908                 brelse(ebp);
909         if (sbap != &ip->i_din2->di_db[0])
910                 brelse(sbp);
911         return (ENOSPC);
912 }
913
914 /*
915  * Allocate an inode in the filesystem.
916  *
917  * If allocating a directory, use ffs_dirpref to select the inode.
918  * If allocating in a directory, the following hierarchy is followed:
919  *   1) allocate the preferred inode.
920  *   2) allocate an inode in the same cylinder group.
921  *   3) quadradically rehash into other cylinder groups, until an
922  *      available inode is located.
923  * If no inode preference is given the following hierarchy is used
924  * to allocate an inode:
925  *   1) allocate an inode in cylinder group 0.
926  *   2) quadradically rehash into other cylinder groups, until an
927  *      available inode is located.
928  */
929 int
930 ffs_valloc(pvp, mode, cred, vpp)
931         struct vnode *pvp;
932         int mode;
933         struct ucred *cred;
934         struct vnode **vpp;
935 {
936         struct inode *pip;
937         struct fs *fs;
938         struct inode *ip;
939         struct timespec ts;
940         struct ufsmount *ump;
941         ino_t ino, ipref;
942         u_int cg;
943         int error, error1;
944         static struct timeval lastfail;
945         static int curfail;
946
947         *vpp = NULL;
948         pip = VTOI(pvp);
949         fs = pip->i_fs;
950         ump = pip->i_ump;
951
952         UFS_LOCK(ump);
953         if (fs->fs_cstotal.cs_nifree == 0)
954                 goto noinodes;
955
956         if ((mode & IFMT) == IFDIR)
957                 ipref = ffs_dirpref(pip);
958         else
959                 ipref = pip->i_number;
960         if (ipref >= fs->fs_ncg * fs->fs_ipg)
961                 ipref = 0;
962         cg = ino_to_cg(fs, ipref);
963         /*
964          * Track number of dirs created one after another
965          * in a same cg without intervening by files.
966          */
967         if ((mode & IFMT) == IFDIR) {
968                 if (fs->fs_contigdirs[cg] < 255)
969                         fs->fs_contigdirs[cg]++;
970         } else {
971                 if (fs->fs_contigdirs[cg] > 0)
972                         fs->fs_contigdirs[cg]--;
973         }
974         ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode,
975                                         (allocfcn_t *)ffs_nodealloccg);
976         if (ino == 0)
977                 goto noinodes;
978         error = ffs_vget(pvp->v_mount, ino, LK_EXCLUSIVE, vpp);
979         if (error) {
980                 error1 = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
981                     FFSV_FORCEINSMQ);
982                 ffs_vfree(pvp, ino, mode);
983                 if (error1 == 0) {
984                         ip = VTOI(*vpp);
985                         if (ip->i_mode)
986                                 goto dup_alloc;
987                         ip->i_flag |= IN_MODIFIED;
988                         vput(*vpp);
989                 }
990                 return (error);
991         }
992         ip = VTOI(*vpp);
993         if (ip->i_mode) {
994 dup_alloc:
995                 printf("mode = 0%o, inum = %lu, fs = %s\n",
996                     ip->i_mode, (u_long)ip->i_number, fs->fs_fsmnt);
997                 panic("ffs_valloc: dup alloc");
998         }
999         if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) {  /* XXX */
1000                 printf("free inode %s/%lu had %ld blocks\n",
1001                     fs->fs_fsmnt, (u_long)ino, (long)DIP(ip, i_blocks));
1002                 DIP_SET(ip, i_blocks, 0);
1003         }
1004         ip->i_flags = 0;
1005         DIP_SET(ip, i_flags, 0);
1006         /*
1007          * Set up a new generation number for this inode.
1008          */
1009         if (ip->i_gen == 0 || ++ip->i_gen == 0)
1010                 ip->i_gen = arc4random() / 2 + 1;
1011         DIP_SET(ip, i_gen, ip->i_gen);
1012         if (fs->fs_magic == FS_UFS2_MAGIC) {
1013                 vfs_timestamp(&ts);
1014                 ip->i_din2->di_birthtime = ts.tv_sec;
1015                 ip->i_din2->di_birthnsec = ts.tv_nsec;
1016         }
1017         ufs_prepare_reclaim(*vpp);
1018         ip->i_flag = 0;
1019         (*vpp)->v_vflag = 0;
1020         (*vpp)->v_type = VNON;
1021         if (fs->fs_magic == FS_UFS2_MAGIC)
1022                 (*vpp)->v_op = &ffs_vnodeops2;
1023         else
1024                 (*vpp)->v_op = &ffs_vnodeops1;
1025         return (0);
1026 noinodes:
1027         UFS_UNLOCK(ump);
1028         if (ppsratecheck(&lastfail, &curfail, 1)) {
1029                 ffs_fserr(fs, pip->i_number, "out of inodes");
1030                 uprintf("\n%s: create/symlink failed, no inodes free\n",
1031                     fs->fs_fsmnt);
1032         }
1033         return (ENOSPC);
1034 }
1035
1036 /*
1037  * Find a cylinder group to place a directory.
1038  *
1039  * The policy implemented by this algorithm is to allocate a
1040  * directory inode in the same cylinder group as its parent
1041  * directory, but also to reserve space for its files inodes
1042  * and data. Restrict the number of directories which may be
1043  * allocated one after another in the same cylinder group
1044  * without intervening allocation of files.
1045  *
1046  * If we allocate a first level directory then force allocation
1047  * in another cylinder group.
1048  */
1049 static ino_t
1050 ffs_dirpref(pip)
1051         struct inode *pip;
1052 {
1053         struct fs *fs;
1054         u_int cg, prefcg, dirsize, cgsize;
1055         u_int avgifree, avgbfree, avgndir, curdirsize;
1056         u_int minifree, minbfree, maxndir;
1057         u_int mincg, minndir;
1058         u_int maxcontigdirs;
1059
1060         mtx_assert(UFS_MTX(pip->i_ump), MA_OWNED);
1061         fs = pip->i_fs;
1062
1063         avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1064         avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1065         avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1066
1067         /*
1068          * Force allocation in another cg if creating a first level dir.
1069          */
1070         ASSERT_VOP_LOCKED(ITOV(pip), "ffs_dirpref");
1071         if (ITOV(pip)->v_vflag & VV_ROOT) {
1072                 prefcg = arc4random() % fs->fs_ncg;
1073                 mincg = prefcg;
1074                 minndir = fs->fs_ipg;
1075                 for (cg = prefcg; cg < fs->fs_ncg; cg++)
1076                         if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1077                             fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1078                             fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1079                                 mincg = cg;
1080                                 minndir = fs->fs_cs(fs, cg).cs_ndir;
1081                         }
1082                 for (cg = 0; cg < prefcg; cg++)
1083                         if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
1084                             fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
1085                             fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1086                                 mincg = cg;
1087                                 minndir = fs->fs_cs(fs, cg).cs_ndir;
1088                         }
1089                 return ((ino_t)(fs->fs_ipg * mincg));
1090         }
1091
1092         /*
1093          * Count various limits which used for
1094          * optimal allocation of a directory inode.
1095          */
1096         maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
1097         minifree = avgifree - avgifree / 4;
1098         if (minifree < 1)
1099                 minifree = 1;
1100         minbfree = avgbfree - avgbfree / 4;
1101         if (minbfree < 1)
1102                 minbfree = 1;
1103         cgsize = fs->fs_fsize * fs->fs_fpg;
1104         dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1105         curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1106         if (dirsize < curdirsize)
1107                 dirsize = curdirsize;
1108         if (dirsize <= 0)
1109                 maxcontigdirs = 0;              /* dirsize overflowed */
1110         else
1111                 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1112         if (fs->fs_avgfpdir > 0)
1113                 maxcontigdirs = min(maxcontigdirs,
1114                                     fs->fs_ipg / fs->fs_avgfpdir);
1115         if (maxcontigdirs == 0)
1116                 maxcontigdirs = 1;
1117
1118         /*
1119          * Limit number of dirs in one cg and reserve space for 
1120          * regular files, but only if we have no deficit in
1121          * inodes or space.
1122          */
1123         prefcg = ino_to_cg(fs, pip->i_number);
1124         for (cg = prefcg; cg < fs->fs_ncg; cg++)
1125                 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1126                     fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1127                     fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1128                         if (fs->fs_contigdirs[cg] < maxcontigdirs)
1129                                 return ((ino_t)(fs->fs_ipg * cg));
1130                 }
1131         for (cg = 0; cg < prefcg; cg++)
1132                 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1133                     fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1134                     fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1135                         if (fs->fs_contigdirs[cg] < maxcontigdirs)
1136                                 return ((ino_t)(fs->fs_ipg * cg));
1137                 }
1138         /*
1139          * This is a backstop when we have deficit in space.
1140          */
1141         for (cg = prefcg; cg < fs->fs_ncg; cg++)
1142                 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1143                         return ((ino_t)(fs->fs_ipg * cg));
1144         for (cg = 0; cg < prefcg; cg++)
1145                 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1146                         break;
1147         return ((ino_t)(fs->fs_ipg * cg));
1148 }
1149
1150 /*
1151  * Select the desired position for the next block in a file.  The file is
1152  * logically divided into sections. The first section is composed of the
1153  * direct blocks. Each additional section contains fs_maxbpg blocks.
1154  *
1155  * If no blocks have been allocated in the first section, the policy is to
1156  * request a block in the same cylinder group as the inode that describes
1157  * the file. If no blocks have been allocated in any other section, the
1158  * policy is to place the section in a cylinder group with a greater than
1159  * average number of free blocks.  An appropriate cylinder group is found
1160  * by using a rotor that sweeps the cylinder groups. When a new group of
1161  * blocks is needed, the sweep begins in the cylinder group following the
1162  * cylinder group from which the previous allocation was made. The sweep
1163  * continues until a cylinder group with greater than the average number
1164  * of free blocks is found. If the allocation is for the first block in an
1165  * indirect block, the information on the previous allocation is unavailable;
1166  * here a best guess is made based upon the logical block number being
1167  * allocated.
1168  *
1169  * If a section is already partially allocated, the policy is to
1170  * contiguously allocate fs_maxcontig blocks. The end of one of these
1171  * contiguous blocks and the beginning of the next is laid out
1172  * contiguously if possible.
1173  */
1174 ufs2_daddr_t
1175 ffs_blkpref_ufs1(ip, lbn, indx, bap)
1176         struct inode *ip;
1177         ufs_lbn_t lbn;
1178         int indx;
1179         ufs1_daddr_t *bap;
1180 {
1181         struct fs *fs;
1182         u_int cg;
1183         u_int avgbfree, startcg;
1184
1185         mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1186         fs = ip->i_fs;
1187         if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1188                 if (lbn < NDADDR + NINDIR(fs)) {
1189                         cg = ino_to_cg(fs, ip->i_number);
1190                         return (cgbase(fs, cg) + fs->fs_frag);
1191                 }
1192                 /*
1193                  * Find a cylinder with greater than average number of
1194                  * unused data blocks.
1195                  */
1196                 if (indx == 0 || bap[indx - 1] == 0)
1197                         startcg =
1198                             ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1199                 else
1200                         startcg = dtog(fs, bap[indx - 1]) + 1;
1201                 startcg %= fs->fs_ncg;
1202                 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1203                 for (cg = startcg; cg < fs->fs_ncg; cg++)
1204                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1205                                 fs->fs_cgrotor = cg;
1206                                 return (cgbase(fs, cg) + fs->fs_frag);
1207                         }
1208                 for (cg = 0; cg <= startcg; cg++)
1209                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1210                                 fs->fs_cgrotor = cg;
1211                                 return (cgbase(fs, cg) + fs->fs_frag);
1212                         }
1213                 return (0);
1214         }
1215         /*
1216          * We just always try to lay things out contiguously.
1217          */
1218         return (bap[indx - 1] + fs->fs_frag);
1219 }
1220
1221 /*
1222  * Same as above, but for UFS2
1223  */
1224 ufs2_daddr_t
1225 ffs_blkpref_ufs2(ip, lbn, indx, bap)
1226         struct inode *ip;
1227         ufs_lbn_t lbn;
1228         int indx;
1229         ufs2_daddr_t *bap;
1230 {
1231         struct fs *fs;
1232         u_int cg;
1233         u_int avgbfree, startcg;
1234
1235         mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1236         fs = ip->i_fs;
1237         if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
1238                 if (lbn < NDADDR + NINDIR(fs)) {
1239                         cg = ino_to_cg(fs, ip->i_number);
1240                         return (cgbase(fs, cg) + fs->fs_frag);
1241                 }
1242                 /*
1243                  * Find a cylinder with greater than average number of
1244                  * unused data blocks.
1245                  */
1246                 if (indx == 0 || bap[indx - 1] == 0)
1247                         startcg =
1248                             ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
1249                 else
1250                         startcg = dtog(fs, bap[indx - 1]) + 1;
1251                 startcg %= fs->fs_ncg;
1252                 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1253                 for (cg = startcg; cg < fs->fs_ncg; cg++)
1254                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1255                                 fs->fs_cgrotor = cg;
1256                                 return (cgbase(fs, cg) + fs->fs_frag);
1257                         }
1258                 for (cg = 0; cg <= startcg; cg++)
1259                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1260                                 fs->fs_cgrotor = cg;
1261                                 return (cgbase(fs, cg) + fs->fs_frag);
1262                         }
1263                 return (0);
1264         }
1265         /*
1266          * We just always try to lay things out contiguously.
1267          */
1268         return (bap[indx - 1] + fs->fs_frag);
1269 }
1270
1271 /*
1272  * Implement the cylinder overflow algorithm.
1273  *
1274  * The policy implemented by this algorithm is:
1275  *   1) allocate the block in its requested cylinder group.
1276  *   2) quadradically rehash on the cylinder group number.
1277  *   3) brute force search for a free block.
1278  *
1279  * Must be called with the UFS lock held.  Will release the lock on success
1280  * and return with it held on failure.
1281  */
1282 /*VARARGS5*/
1283 static ufs2_daddr_t
1284 ffs_hashalloc(ip, cg, pref, size, allocator)
1285         struct inode *ip;
1286         u_int cg;
1287         ufs2_daddr_t pref;
1288         int size;       /* size for data blocks, mode for inodes */
1289         allocfcn_t *allocator;
1290 {
1291         struct fs *fs;
1292         ufs2_daddr_t result;
1293         u_int i, icg = cg;
1294
1295         mtx_assert(UFS_MTX(ip->i_ump), MA_OWNED);
1296 #ifdef INVARIANTS
1297         if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1298                 panic("ffs_hashalloc: allocation on suspended filesystem");
1299 #endif
1300         fs = ip->i_fs;
1301         /*
1302          * 1: preferred cylinder group
1303          */
1304         result = (*allocator)(ip, cg, pref, size);
1305         if (result)
1306                 return (result);
1307         /*
1308          * 2: quadratic rehash
1309          */
1310         for (i = 1; i < fs->fs_ncg; i *= 2) {
1311                 cg += i;
1312                 if (cg >= fs->fs_ncg)
1313                         cg -= fs->fs_ncg;
1314                 result = (*allocator)(ip, cg, 0, size);
1315                 if (result)
1316                         return (result);
1317         }
1318         /*
1319          * 3: brute force search
1320          * Note that we start at i == 2, since 0 was checked initially,
1321          * and 1 is always checked in the quadratic rehash.
1322          */
1323         cg = (icg + 2) % fs->fs_ncg;
1324         for (i = 2; i < fs->fs_ncg; i++) {
1325                 result = (*allocator)(ip, cg, 0, size);
1326                 if (result)
1327                         return (result);
1328                 cg++;
1329                 if (cg == fs->fs_ncg)
1330                         cg = 0;
1331         }
1332         return (0);
1333 }
1334
1335 /*
1336  * Determine whether a fragment can be extended.
1337  *
1338  * Check to see if the necessary fragments are available, and
1339  * if they are, allocate them.
1340  */
1341 static ufs2_daddr_t
1342 ffs_fragextend(ip, cg, bprev, osize, nsize)
1343         struct inode *ip;
1344         u_int cg;
1345         ufs2_daddr_t bprev;
1346         int osize, nsize;
1347 {
1348         struct fs *fs;
1349         struct cg *cgp;
1350         struct buf *bp;
1351         struct ufsmount *ump;
1352         int nffree;
1353         long bno;
1354         int frags, bbase;
1355         int i, error;
1356         u_int8_t *blksfree;
1357
1358         ump = ip->i_ump;
1359         fs = ip->i_fs;
1360         if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
1361                 return (0);
1362         frags = numfrags(fs, nsize);
1363         bbase = fragnum(fs, bprev);
1364         if (bbase > fragnum(fs, (bprev + frags - 1))) {
1365                 /* cannot extend across a block boundary */
1366                 return (0);
1367         }
1368         UFS_UNLOCK(ump);
1369         error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1370                 (int)fs->fs_cgsize, NOCRED, &bp);
1371         if (error)
1372                 goto fail;
1373         cgp = (struct cg *)bp->b_data;
1374         if (!cg_chkmagic(cgp))
1375                 goto fail;
1376         bp->b_xflags |= BX_BKGRDWRITE;
1377         cgp->cg_old_time = cgp->cg_time = time_second;
1378         bno = dtogd(fs, bprev);
1379         blksfree = cg_blksfree(cgp);
1380         for (i = numfrags(fs, osize); i < frags; i++)
1381                 if (isclr(blksfree, bno + i))
1382                         goto fail;
1383         /*
1384          * the current fragment can be extended
1385          * deduct the count on fragment being extended into
1386          * increase the count on the remaining fragment (if any)
1387          * allocate the extended piece
1388          */
1389         for (i = frags; i < fs->fs_frag - bbase; i++)
1390                 if (isclr(blksfree, bno + i))
1391                         break;
1392         cgp->cg_frsum[i - numfrags(fs, osize)]--;
1393         if (i != frags)
1394                 cgp->cg_frsum[i - frags]++;
1395         for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
1396                 clrbit(blksfree, bno + i);
1397                 cgp->cg_cs.cs_nffree--;
1398                 nffree++;
1399         }
1400         UFS_LOCK(ump);
1401         fs->fs_cstotal.cs_nffree -= nffree;
1402         fs->fs_cs(fs, cg).cs_nffree -= nffree;
1403         fs->fs_fmod = 1;
1404         ACTIVECLEAR(fs, cg);
1405         UFS_UNLOCK(ump);
1406         if (DOINGSOFTDEP(ITOV(ip)))
1407                 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev);
1408         bdwrite(bp);
1409         return (bprev);
1410
1411 fail:
1412         brelse(bp);
1413         UFS_LOCK(ump);
1414         return (0);
1415
1416 }
1417
1418 /*
1419  * Determine whether a block can be allocated.
1420  *
1421  * Check to see if a block of the appropriate size is available,
1422  * and if it is, allocate it.
1423  */
1424 static ufs2_daddr_t
1425 ffs_alloccg(ip, cg, bpref, size)
1426         struct inode *ip;
1427         u_int cg;
1428         ufs2_daddr_t bpref;
1429         int size;
1430 {
1431         struct fs *fs;
1432         struct cg *cgp;
1433         struct buf *bp;
1434         struct ufsmount *ump;
1435         ufs1_daddr_t bno;
1436         ufs2_daddr_t blkno;
1437         int i, allocsiz, error, frags;
1438         u_int8_t *blksfree;
1439
1440         ump = ip->i_ump;
1441         fs = ip->i_fs;
1442         if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1443                 return (0);
1444         UFS_UNLOCK(ump);
1445         error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1446                 (int)fs->fs_cgsize, NOCRED, &bp);
1447         if (error)
1448                 goto fail;
1449         cgp = (struct cg *)bp->b_data;
1450         if (!cg_chkmagic(cgp) ||
1451             (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1452                 goto fail;
1453         bp->b_xflags |= BX_BKGRDWRITE;
1454         cgp->cg_old_time = cgp->cg_time = time_second;
1455         if (size == fs->fs_bsize) {
1456                 UFS_LOCK(ump);
1457                 blkno = ffs_alloccgblk(ip, bp, bpref);
1458                 ACTIVECLEAR(fs, cg);
1459                 UFS_UNLOCK(ump);
1460                 bdwrite(bp);
1461                 return (blkno);
1462         }
1463         /*
1464          * check to see if any fragments are already available
1465          * allocsiz is the size which will be allocated, hacking
1466          * it down to a smaller size if necessary
1467          */
1468         blksfree = cg_blksfree(cgp);
1469         frags = numfrags(fs, size);
1470         for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1471                 if (cgp->cg_frsum[allocsiz] != 0)
1472                         break;
1473         if (allocsiz == fs->fs_frag) {
1474                 /*
1475                  * no fragments were available, so a block will be
1476                  * allocated, and hacked up
1477                  */
1478                 if (cgp->cg_cs.cs_nbfree == 0)
1479                         goto fail;
1480                 UFS_LOCK(ump);
1481                 blkno = ffs_alloccgblk(ip, bp, bpref);
1482                 bno = dtogd(fs, blkno);
1483                 for (i = frags; i < fs->fs_frag; i++)
1484                         setbit(blksfree, bno + i);
1485                 i = fs->fs_frag - frags;
1486                 cgp->cg_cs.cs_nffree += i;
1487                 fs->fs_cstotal.cs_nffree += i;
1488                 fs->fs_cs(fs, cg).cs_nffree += i;
1489                 fs->fs_fmod = 1;
1490                 cgp->cg_frsum[i]++;
1491                 ACTIVECLEAR(fs, cg);
1492                 UFS_UNLOCK(ump);
1493                 bdwrite(bp);
1494                 return (blkno);
1495         }
1496         bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1497         if (bno < 0)
1498                 goto fail;
1499         for (i = 0; i < frags; i++)
1500                 clrbit(blksfree, bno + i);
1501         cgp->cg_cs.cs_nffree -= frags;
1502         cgp->cg_frsum[allocsiz]--;
1503         if (frags != allocsiz)
1504                 cgp->cg_frsum[allocsiz - frags]++;
1505         UFS_LOCK(ump);
1506         fs->fs_cstotal.cs_nffree -= frags;
1507         fs->fs_cs(fs, cg).cs_nffree -= frags;
1508         fs->fs_fmod = 1;
1509         blkno = cgbase(fs, cg) + bno;
1510         ACTIVECLEAR(fs, cg);
1511         UFS_UNLOCK(ump);
1512         if (DOINGSOFTDEP(ITOV(ip)))
1513                 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno);
1514         bdwrite(bp);
1515         return (blkno);
1516
1517 fail:
1518         brelse(bp);
1519         UFS_LOCK(ump);
1520         return (0);
1521 }
1522
1523 /*
1524  * Allocate a block in a cylinder group.
1525  *
1526  * This algorithm implements the following policy:
1527  *   1) allocate the requested block.
1528  *   2) allocate a rotationally optimal block in the same cylinder.
1529  *   3) allocate the next available block on the block rotor for the
1530  *      specified cylinder group.
1531  * Note that this routine only allocates fs_bsize blocks; these
1532  * blocks may be fragmented by the routine that allocates them.
1533  */
1534 static ufs2_daddr_t
1535 ffs_alloccgblk(ip, bp, bpref)
1536         struct inode *ip;
1537         struct buf *bp;
1538         ufs2_daddr_t bpref;
1539 {
1540         struct fs *fs;
1541         struct cg *cgp;
1542         struct ufsmount *ump;
1543         ufs1_daddr_t bno;
1544         ufs2_daddr_t blkno;
1545         u_int8_t *blksfree;
1546
1547         fs = ip->i_fs;
1548         ump = ip->i_ump;
1549         mtx_assert(UFS_MTX(ump), MA_OWNED);
1550         cgp = (struct cg *)bp->b_data;
1551         blksfree = cg_blksfree(cgp);
1552         if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
1553                 bpref = cgp->cg_rotor;
1554         } else {
1555                 bpref = blknum(fs, bpref);
1556                 bno = dtogd(fs, bpref);
1557                 /*
1558                  * if the requested block is available, use it
1559                  */
1560                 if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1561                         goto gotit;
1562         }
1563         /*
1564          * Take the next available block in this cylinder group.
1565          */
1566         bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1567         if (bno < 0)
1568                 return (0);
1569         cgp->cg_rotor = bno;
1570 gotit:
1571         blkno = fragstoblks(fs, bno);
1572         ffs_clrblock(fs, blksfree, (long)blkno);
1573         ffs_clusteracct(ump, fs, cgp, blkno, -1);
1574         cgp->cg_cs.cs_nbfree--;
1575         fs->fs_cstotal.cs_nbfree--;
1576         fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1577         fs->fs_fmod = 1;
1578         blkno = cgbase(fs, cgp->cg_cgx) + bno;
1579         /* XXX Fixme. */
1580         UFS_UNLOCK(ump);
1581         if (DOINGSOFTDEP(ITOV(ip)))
1582                 softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno);
1583         UFS_LOCK(ump);
1584         return (blkno);
1585 }
1586
1587 /*
1588  * Determine whether a cluster can be allocated.
1589  *
1590  * We do not currently check for optimal rotational layout if there
1591  * are multiple choices in the same cylinder group. Instead we just
1592  * take the first one that we find following bpref.
1593  */
1594 static ufs2_daddr_t
1595 ffs_clusteralloc(ip, cg, bpref, len)
1596         struct inode *ip;
1597         u_int cg;
1598         ufs2_daddr_t bpref;
1599         int len;
1600 {
1601         struct fs *fs;
1602         struct cg *cgp;
1603         struct buf *bp;
1604         struct ufsmount *ump;
1605         int i, run, bit, map, got;
1606         ufs2_daddr_t bno;
1607         u_char *mapp;
1608         int32_t *lp;
1609         u_int8_t *blksfree;
1610
1611         fs = ip->i_fs;
1612         ump = ip->i_ump;
1613         if (fs->fs_maxcluster[cg] < len)
1614                 return (0);
1615         UFS_UNLOCK(ump);
1616         if (bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)), (int)fs->fs_cgsize,
1617             NOCRED, &bp))
1618                 goto fail_lock;
1619         cgp = (struct cg *)bp->b_data;
1620         if (!cg_chkmagic(cgp))
1621                 goto fail_lock;
1622         bp->b_xflags |= BX_BKGRDWRITE;
1623         /*
1624          * Check to see if a cluster of the needed size (or bigger) is
1625          * available in this cylinder group.
1626          */
1627         lp = &cg_clustersum(cgp)[len];
1628         for (i = len; i <= fs->fs_contigsumsize; i++)
1629                 if (*lp++ > 0)
1630                         break;
1631         if (i > fs->fs_contigsumsize) {
1632                 /*
1633                  * This is the first time looking for a cluster in this
1634                  * cylinder group. Update the cluster summary information
1635                  * to reflect the true maximum sized cluster so that
1636                  * future cluster allocation requests can avoid reading
1637                  * the cylinder group map only to find no clusters.
1638                  */
1639                 lp = &cg_clustersum(cgp)[len - 1];
1640                 for (i = len - 1; i > 0; i--)
1641                         if (*lp-- > 0)
1642                                 break;
1643                 UFS_LOCK(ump);
1644                 fs->fs_maxcluster[cg] = i;
1645                 goto fail;
1646         }
1647         /*
1648          * Search the cluster map to find a big enough cluster.
1649          * We take the first one that we find, even if it is larger
1650          * than we need as we prefer to get one close to the previous
1651          * block allocation. We do not search before the current
1652          * preference point as we do not want to allocate a block
1653          * that is allocated before the previous one (as we will
1654          * then have to wait for another pass of the elevator
1655          * algorithm before it will be read). We prefer to fail and
1656          * be recalled to try an allocation in the next cylinder group.
1657          */
1658         if (dtog(fs, bpref) != cg)
1659                 bpref = 0;
1660         else
1661                 bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1662         mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1663         map = *mapp++;
1664         bit = 1 << (bpref % NBBY);
1665         for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1666                 if ((map & bit) == 0) {
1667                         run = 0;
1668                 } else {
1669                         run++;
1670                         if (run == len)
1671                                 break;
1672                 }
1673                 if ((got & (NBBY - 1)) != (NBBY - 1)) {
1674                         bit <<= 1;
1675                 } else {
1676                         map = *mapp++;
1677                         bit = 1;
1678                 }
1679         }
1680         if (got >= cgp->cg_nclusterblks)
1681                 goto fail_lock;
1682         /*
1683          * Allocate the cluster that we have found.
1684          */
1685         blksfree = cg_blksfree(cgp);
1686         for (i = 1; i <= len; i++)
1687                 if (!ffs_isblock(fs, blksfree, got - run + i))
1688                         panic("ffs_clusteralloc: map mismatch");
1689         bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
1690         if (dtog(fs, bno) != cg)
1691                 panic("ffs_clusteralloc: allocated out of group");
1692         len = blkstofrags(fs, len);
1693         UFS_LOCK(ump);
1694         for (i = 0; i < len; i += fs->fs_frag)
1695                 if (ffs_alloccgblk(ip, bp, bno + i) != bno + i)
1696                         panic("ffs_clusteralloc: lost block");
1697         ACTIVECLEAR(fs, cg);
1698         UFS_UNLOCK(ump);
1699         bdwrite(bp);
1700         return (bno);
1701
1702 fail_lock:
1703         UFS_LOCK(ump);
1704 fail:
1705         brelse(bp);
1706         return (0);
1707 }
1708
1709 static inline struct buf *
1710 getinobuf(struct inode *ip, u_int cg, u_int32_t cginoblk, int gbflags)
1711 {
1712         struct fs *fs;
1713
1714         fs = ip->i_fs;
1715         return (getblk(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs,
1716             cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
1717             gbflags));
1718 }
1719
1720 /*
1721  * Determine whether an inode can be allocated.
1722  *
1723  * Check to see if an inode is available, and if it is,
1724  * allocate it using the following policy:
1725  *   1) allocate the requested inode.
1726  *   2) allocate the next available inode after the requested
1727  *      inode in the specified cylinder group.
1728  */
1729 static ufs2_daddr_t
1730 ffs_nodealloccg(ip, cg, ipref, mode)
1731         struct inode *ip;
1732         u_int cg;
1733         ufs2_daddr_t ipref;
1734         int mode;
1735 {
1736         struct fs *fs;
1737         struct cg *cgp;
1738         struct buf *bp, *ibp;
1739         struct ufsmount *ump;
1740         u_int8_t *inosused;
1741         struct ufs2_dinode *dp2;
1742         int error, start, len, loc, map, i;
1743         u_int32_t old_initediblk;
1744
1745         fs = ip->i_fs;
1746         ump = ip->i_ump;
1747 check_nifree:
1748         if (fs->fs_cs(fs, cg).cs_nifree == 0)
1749                 return (0);
1750         UFS_UNLOCK(ump);
1751         error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1752                 (int)fs->fs_cgsize, NOCRED, &bp);
1753         if (error) {
1754                 brelse(bp);
1755                 UFS_LOCK(ump);
1756                 return (0);
1757         }
1758         cgp = (struct cg *)bp->b_data;
1759 restart:
1760         if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1761                 brelse(bp);
1762                 UFS_LOCK(ump);
1763                 return (0);
1764         }
1765         bp->b_xflags |= BX_BKGRDWRITE;
1766         inosused = cg_inosused(cgp);
1767         if (ipref) {
1768                 ipref %= fs->fs_ipg;
1769                 if (isclr(inosused, ipref))
1770                         goto gotit;
1771         }
1772         start = cgp->cg_irotor / NBBY;
1773         len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
1774         loc = skpc(0xff, len, &inosused[start]);
1775         if (loc == 0) {
1776                 len = start + 1;
1777                 start = 0;
1778                 loc = skpc(0xff, len, &inosused[0]);
1779                 if (loc == 0) {
1780                         printf("cg = %d, irotor = %ld, fs = %s\n",
1781                             cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
1782                         panic("ffs_nodealloccg: map corrupted");
1783                         /* NOTREACHED */
1784                 }
1785         }
1786         i = start + len - loc;
1787         map = inosused[i] ^ 0xff;
1788         if (map == 0) {
1789                 printf("fs = %s\n", fs->fs_fsmnt);
1790                 panic("ffs_nodealloccg: block not in map");
1791         }
1792         ipref = i * NBBY + ffs(map) - 1;
1793 gotit:
1794         /*
1795          * Check to see if we need to initialize more inodes.
1796          */
1797         if (fs->fs_magic == FS_UFS2_MAGIC &&
1798             ipref + INOPB(fs) > cgp->cg_initediblk &&
1799             cgp->cg_initediblk < cgp->cg_niblk) {
1800                 old_initediblk = cgp->cg_initediblk;
1801
1802                 /*
1803                  * Free the cylinder group lock before writing the
1804                  * initialized inode block.  Entering the
1805                  * babarrierwrite() with the cylinder group lock
1806                  * causes lock order violation between the lock and
1807                  * snaplk.
1808                  *
1809                  * Another thread can decide to initialize the same
1810                  * inode block, but whichever thread first gets the
1811                  * cylinder group lock after writing the newly
1812                  * allocated inode block will update it and the other
1813                  * will realize that it has lost and leave the
1814                  * cylinder group unchanged.
1815                  */
1816                 ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
1817                 brelse(bp);
1818                 if (ibp == NULL) {
1819                         /*
1820                          * The inode block buffer is already owned by
1821                          * another thread, which must initialize it.
1822                          * Wait on the buffer to allow another thread
1823                          * to finish the updates, with dropped cg
1824                          * buffer lock, then retry.
1825                          */
1826                         ibp = getinobuf(ip, cg, old_initediblk, 0);
1827                         brelse(ibp);
1828                         UFS_LOCK(ump);
1829                         goto check_nifree;
1830                 }
1831                 bzero(ibp->b_data, (int)fs->fs_bsize);
1832                 dp2 = (struct ufs2_dinode *)(ibp->b_data);
1833                 for (i = 0; i < INOPB(fs); i++) {
1834                         dp2->di_gen = arc4random() / 2 + 1;
1835                         dp2++;
1836                 }
1837                 /*
1838                  * Rather than adding a soft updates dependency to ensure
1839                  * that the new inode block is written before it is claimed
1840                  * by the cylinder group map, we just do a barrier write
1841                  * here. The barrier write will ensure that the inode block
1842                  * gets written before the updated cylinder group map can be
1843                  * written. The barrier write should only slow down bulk
1844                  * loading of newly created filesystems.
1845                  */
1846                 babarrierwrite(ibp);
1847
1848                 /*
1849                  * After the inode block is written, try to update the
1850                  * cg initediblk pointer.  If another thread beat us
1851                  * to it, then leave it unchanged as the other thread
1852                  * has already set it correctly.
1853                  */
1854                 error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
1855                     (int)fs->fs_cgsize, NOCRED, &bp);
1856                 UFS_LOCK(ump);
1857                 ACTIVECLEAR(fs, cg);
1858                 UFS_UNLOCK(ump);
1859                 if (error != 0) {
1860                         brelse(bp);
1861                         return (error);
1862                 }
1863                 cgp = (struct cg *)bp->b_data;
1864                 if (cgp->cg_initediblk == old_initediblk)
1865                         cgp->cg_initediblk += INOPB(fs);
1866                 goto restart;
1867         }
1868         cgp->cg_old_time = cgp->cg_time = time_second;
1869         cgp->cg_irotor = ipref;
1870         UFS_LOCK(ump);
1871         ACTIVECLEAR(fs, cg);
1872         setbit(inosused, ipref);
1873         cgp->cg_cs.cs_nifree--;
1874         fs->fs_cstotal.cs_nifree--;
1875         fs->fs_cs(fs, cg).cs_nifree--;
1876         fs->fs_fmod = 1;
1877         if ((mode & IFMT) == IFDIR) {
1878                 cgp->cg_cs.cs_ndir++;
1879                 fs->fs_cstotal.cs_ndir++;
1880                 fs->fs_cs(fs, cg).cs_ndir++;
1881         }
1882         UFS_UNLOCK(ump);
1883         if (DOINGSOFTDEP(ITOV(ip)))
1884                 softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref);
1885         bdwrite(bp);
1886         return ((ino_t)(cg * fs->fs_ipg + ipref));
1887 }
1888
1889 /*
1890  * check if a block is free
1891  */
1892 static int
1893 ffs_isfreeblock(struct fs *fs, u_char *cp, ufs1_daddr_t h)
1894 {
1895
1896         switch ((int)fs->fs_frag) {
1897         case 8:
1898                 return (cp[h] == 0);
1899         case 4:
1900                 return ((cp[h >> 1] & (0x0f << ((h & 0x1) << 2))) == 0);
1901         case 2:
1902                 return ((cp[h >> 2] & (0x03 << ((h & 0x3) << 1))) == 0);
1903         case 1:
1904                 return ((cp[h >> 3] & (0x01 << (h & 0x7))) == 0);
1905         default:
1906                 panic("ffs_isfreeblock");
1907         }
1908         return (0);
1909 }
1910
1911 /*
1912  * Free a block or fragment.
1913  *
1914  * The specified block or fragment is placed back in the
1915  * free map. If a fragment is deallocated, a possible
1916  * block reassembly is checked.
1917  */
1918 static void
1919 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum)
1920         struct ufsmount *ump;
1921         struct fs *fs;
1922         struct vnode *devvp;
1923         ufs2_daddr_t bno;
1924         long size;
1925         ino_t inum;
1926 {
1927         struct cg *cgp;
1928         struct buf *bp;
1929         ufs1_daddr_t fragno, cgbno;
1930         ufs2_daddr_t cgblkno;
1931         int i, blk, frags, bbase;
1932         u_int cg;
1933         u_int8_t *blksfree;
1934         struct cdev *dev;
1935
1936         cg = dtog(fs, bno);
1937         if (devvp->v_type == VREG) {
1938                 /* devvp is a snapshot */
1939                 dev = VTOI(devvp)->i_devvp->v_rdev;
1940                 cgblkno = fragstoblks(fs, cgtod(fs, cg));
1941         } else {
1942                 /* devvp is a normal disk device */
1943                 dev = devvp->v_rdev;
1944                 cgblkno = fsbtodb(fs, cgtod(fs, cg));
1945                 ASSERT_VOP_LOCKED(devvp, "ffs_blkfree_cg");
1946         }
1947 #ifdef INVARIANTS
1948         if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1949             fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1950                 printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
1951                     devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
1952                     size, fs->fs_fsmnt);
1953                 panic("ffs_blkfree: bad size");
1954         }
1955 #endif
1956         if ((u_int)bno >= fs->fs_size) {
1957                 printf("bad block %jd, ino %lu\n", (intmax_t)bno,
1958                     (u_long)inum);
1959                 ffs_fserr(fs, inum, "bad block");
1960                 return;
1961         }
1962         if (bread(devvp, cgblkno, (int)fs->fs_cgsize, NOCRED, &bp)) {
1963                 brelse(bp);
1964                 return;
1965         }
1966         cgp = (struct cg *)bp->b_data;
1967         if (!cg_chkmagic(cgp)) {
1968                 brelse(bp);
1969                 return;
1970         }
1971         bp->b_xflags |= BX_BKGRDWRITE;
1972         cgp->cg_old_time = cgp->cg_time = time_second;
1973         cgbno = dtogd(fs, bno);
1974         blksfree = cg_blksfree(cgp);
1975         UFS_LOCK(ump);
1976         if (size == fs->fs_bsize) {
1977                 fragno = fragstoblks(fs, cgbno);
1978                 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
1979                         if (devvp->v_type == VREG) {
1980                                 UFS_UNLOCK(ump);
1981                                 /* devvp is a snapshot */
1982                                 brelse(bp);
1983                                 return;
1984                         }
1985                         printf("dev = %s, block = %jd, fs = %s\n",
1986                             devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
1987                         panic("ffs_blkfree: freeing free block");
1988                 }
1989                 ffs_setblock(fs, blksfree, fragno);
1990                 ffs_clusteracct(ump, fs, cgp, fragno, 1);
1991                 cgp->cg_cs.cs_nbfree++;
1992                 fs->fs_cstotal.cs_nbfree++;
1993                 fs->fs_cs(fs, cg).cs_nbfree++;
1994         } else {
1995                 bbase = cgbno - fragnum(fs, cgbno);
1996                 /*
1997                  * decrement the counts associated with the old frags
1998                  */
1999                 blk = blkmap(fs, blksfree, bbase);
2000                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2001                 /*
2002                  * deallocate the fragment
2003                  */
2004                 frags = numfrags(fs, size);
2005                 for (i = 0; i < frags; i++) {
2006                         if (isset(blksfree, cgbno + i)) {
2007                                 printf("dev = %s, block = %jd, fs = %s\n",
2008                                     devtoname(dev), (intmax_t)(bno + i),
2009                                     fs->fs_fsmnt);
2010                                 panic("ffs_blkfree: freeing free frag");
2011                         }
2012                         setbit(blksfree, cgbno + i);
2013                 }
2014                 cgp->cg_cs.cs_nffree += i;
2015                 fs->fs_cstotal.cs_nffree += i;
2016                 fs->fs_cs(fs, cg).cs_nffree += i;
2017                 /*
2018                  * add back in counts associated with the new frags
2019                  */
2020                 blk = blkmap(fs, blksfree, bbase);
2021                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2022                 /*
2023                  * if a complete block has been reassembled, account for it
2024                  */
2025                 fragno = fragstoblks(fs, bbase);
2026                 if (ffs_isblock(fs, blksfree, fragno)) {
2027                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
2028                         fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2029                         fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2030                         ffs_clusteracct(ump, fs, cgp, fragno, 1);
2031                         cgp->cg_cs.cs_nbfree++;
2032                         fs->fs_cstotal.cs_nbfree++;
2033                         fs->fs_cs(fs, cg).cs_nbfree++;
2034                 }
2035         }
2036         fs->fs_fmod = 1;
2037         ACTIVECLEAR(fs, cg);
2038         UFS_UNLOCK(ump);
2039         bdwrite(bp);
2040 }
2041
2042 TASKQUEUE_DEFINE_THREAD(ffs_trim);
2043
2044 struct ffs_blkfree_trim_params {
2045         struct task task;
2046         struct ufsmount *ump;
2047         struct vnode *devvp;
2048         ufs2_daddr_t bno;
2049         long size;
2050         ino_t inum;
2051 };
2052
2053 static void
2054 ffs_blkfree_trim_task(ctx, pending)
2055         void *ctx;
2056         int pending;
2057 {
2058         struct ffs_blkfree_trim_params *tp;
2059
2060         tp = ctx;
2061         ffs_blkfree_cg(tp->ump, tp->ump->um_fs, tp->devvp, tp->bno, tp->size,
2062             tp->inum);
2063         vn_finished_secondary_write(UFSTOVFS(tp->ump));
2064         free(tp, M_TEMP);
2065 }
2066
2067 static void
2068 ffs_blkfree_trim_completed(bip)
2069         struct bio *bip;
2070 {
2071         struct ffs_blkfree_trim_params *tp;
2072
2073         tp = bip->bio_caller2;
2074         g_destroy_bio(bip);
2075         TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2076         taskqueue_enqueue(taskqueue_ffs_trim, &tp->task);
2077 }
2078
2079 void
2080 ffs_blkfree(ump, fs, devvp, bno, size, inum)
2081         struct ufsmount *ump;
2082         struct fs *fs;
2083         struct vnode *devvp;
2084         ufs2_daddr_t bno;
2085         long size;
2086         ino_t inum;
2087 {
2088         struct mount *mp;
2089         struct bio *bip;
2090         struct ffs_blkfree_trim_params *tp;
2091
2092         /*
2093          * Check to see if a snapshot wants to claim the block.
2094          * Check that devvp is a normal disk device, not a snapshot,
2095          * it has a snapshot(s) associated with it, and one of the
2096          * snapshots wants to claim the block.
2097          */
2098         if (devvp->v_type != VREG &&
2099             (devvp->v_vflag & VV_COPYONWRITE) &&
2100             ffs_snapblkfree(fs, devvp, bno, size, inum)) {
2101                 return;
2102         }
2103         /*
2104          * Nothing to delay if TRIM is disabled, or the operation is
2105          * performed on the snapshot.
2106          */
2107         if (!ump->um_candelete || devvp->v_type == VREG) {
2108                 ffs_blkfree_cg(ump, fs, devvp, bno, size, inum);
2109                 return;
2110         }
2111
2112         /*
2113          * Postpone the set of the free bit in the cg bitmap until the
2114          * BIO_DELETE is completed.  Otherwise, due to disk queue
2115          * reordering, TRIM might be issued after we reuse the block
2116          * and write some new data into it.
2117          */
2118         tp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TEMP, M_WAITOK);
2119         tp->ump = ump;
2120         tp->devvp = devvp;
2121         tp->bno = bno;
2122         tp->size = size;
2123         tp->inum = inum;
2124
2125         bip = g_alloc_bio();
2126         bip->bio_cmd = BIO_DELETE;
2127         bip->bio_offset = dbtob(fsbtodb(fs, bno));
2128         bip->bio_done = ffs_blkfree_trim_completed;
2129         bip->bio_length = size;
2130         bip->bio_caller2 = tp;
2131
2132         mp = UFSTOVFS(ump);
2133         vn_start_secondary_write(NULL, &mp, 0);
2134         g_io_request(bip, (struct g_consumer *)devvp->v_bufobj.bo_private);
2135 }
2136
2137 #ifdef INVARIANTS
2138 /*
2139  * Verify allocation of a block or fragment. Returns true if block or
2140  * fragment is allocated, false if it is free.
2141  */
2142 static int
2143 ffs_checkblk(ip, bno, size)
2144         struct inode *ip;
2145         ufs2_daddr_t bno;
2146         long size;
2147 {
2148         struct fs *fs;
2149         struct cg *cgp;
2150         struct buf *bp;
2151         ufs1_daddr_t cgbno;
2152         int i, error, frags, free;
2153         u_int8_t *blksfree;
2154
2155         fs = ip->i_fs;
2156         if ((u_int)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2157                 printf("bsize = %ld, size = %ld, fs = %s\n",
2158                     (long)fs->fs_bsize, size, fs->fs_fsmnt);
2159                 panic("ffs_checkblk: bad size");
2160         }
2161         if ((u_int)bno >= fs->fs_size)
2162                 panic("ffs_checkblk: bad block %jd", (intmax_t)bno);
2163         error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, dtog(fs, bno))),
2164                 (int)fs->fs_cgsize, NOCRED, &bp);
2165         if (error)
2166                 panic("ffs_checkblk: cg bread failed");
2167         cgp = (struct cg *)bp->b_data;
2168         if (!cg_chkmagic(cgp))
2169                 panic("ffs_checkblk: cg magic mismatch");
2170         bp->b_xflags |= BX_BKGRDWRITE;
2171         blksfree = cg_blksfree(cgp);
2172         cgbno = dtogd(fs, bno);
2173         if (size == fs->fs_bsize) {
2174                 free = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2175         } else {
2176                 frags = numfrags(fs, size);
2177                 for (free = 0, i = 0; i < frags; i++)
2178                         if (isset(blksfree, cgbno + i))
2179                                 free++;
2180                 if (free != 0 && free != frags)
2181                         panic("ffs_checkblk: partially free fragment");
2182         }
2183         brelse(bp);
2184         return (!free);
2185 }
2186 #endif /* INVARIANTS */
2187
2188 /*
2189  * Free an inode.
2190  */
2191 int
2192 ffs_vfree(pvp, ino, mode)
2193         struct vnode *pvp;
2194         ino_t ino;
2195         int mode;
2196 {
2197         struct inode *ip;
2198
2199         if (DOINGSOFTDEP(pvp)) {
2200                 softdep_freefile(pvp, ino, mode);
2201                 return (0);
2202         }
2203         ip = VTOI(pvp);
2204         return (ffs_freefile(ip->i_ump, ip->i_fs, ip->i_devvp, ino, mode));
2205 }
2206
2207 /*
2208  * Do the actual free operation.
2209  * The specified inode is placed back in the free map.
2210  */
2211 int
2212 ffs_freefile(ump, fs, devvp, ino, mode)
2213         struct ufsmount *ump;
2214         struct fs *fs;
2215         struct vnode *devvp;
2216         ino_t ino;
2217         int mode;
2218 {
2219         struct cg *cgp;
2220         struct buf *bp;
2221         ufs2_daddr_t cgbno;
2222         int error;
2223         u_int cg;
2224         u_int8_t *inosused;
2225         struct cdev *dev;
2226
2227         cg = ino_to_cg(fs, ino);
2228         if (devvp->v_type == VREG) {
2229                 /* devvp is a snapshot */
2230                 dev = VTOI(devvp)->i_devvp->v_rdev;
2231                 cgbno = fragstoblks(fs, cgtod(fs, cg));
2232         } else {
2233                 /* devvp is a normal disk device */
2234                 dev = devvp->v_rdev;
2235                 cgbno = fsbtodb(fs, cgtod(fs, cg));
2236         }
2237         if (ino >= fs->fs_ipg * fs->fs_ncg)
2238                 panic("ffs_freefile: range: dev = %s, ino = %lu, fs = %s",
2239                     devtoname(dev), (u_long)ino, fs->fs_fsmnt);
2240         if ((error = bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp))) {
2241                 brelse(bp);
2242                 return (error);
2243         }
2244         cgp = (struct cg *)bp->b_data;
2245         if (!cg_chkmagic(cgp)) {
2246                 brelse(bp);
2247                 return (0);
2248         }
2249         bp->b_xflags |= BX_BKGRDWRITE;
2250         cgp->cg_old_time = cgp->cg_time = time_second;
2251         inosused = cg_inosused(cgp);
2252         ino %= fs->fs_ipg;
2253         if (isclr(inosused, ino)) {
2254                 printf("dev = %s, ino = %u, fs = %s\n", devtoname(dev),
2255                     ino + cg * fs->fs_ipg, fs->fs_fsmnt);
2256                 if (fs->fs_ronly == 0)
2257                         panic("ffs_freefile: freeing free inode");
2258         }
2259         clrbit(inosused, ino);
2260         if (ino < cgp->cg_irotor)
2261                 cgp->cg_irotor = ino;
2262         cgp->cg_cs.cs_nifree++;
2263         UFS_LOCK(ump);
2264         fs->fs_cstotal.cs_nifree++;
2265         fs->fs_cs(fs, cg).cs_nifree++;
2266         if ((mode & IFMT) == IFDIR) {
2267                 cgp->cg_cs.cs_ndir--;
2268                 fs->fs_cstotal.cs_ndir--;
2269                 fs->fs_cs(fs, cg).cs_ndir--;
2270         }
2271         fs->fs_fmod = 1;
2272         ACTIVECLEAR(fs, cg);
2273         UFS_UNLOCK(ump);
2274         bdwrite(bp);
2275         return (0);
2276 }
2277
2278 /*
2279  * Check to see if a file is free.
2280  */
2281 int
2282 ffs_checkfreefile(fs, devvp, ino)
2283         struct fs *fs;
2284         struct vnode *devvp;
2285         ino_t ino;
2286 {
2287         struct cg *cgp;
2288         struct buf *bp;
2289         ufs2_daddr_t cgbno;
2290         int ret;
2291         u_int cg;
2292         u_int8_t *inosused;
2293
2294         cg = ino_to_cg(fs, ino);
2295         if (devvp->v_type == VREG) {
2296                 /* devvp is a snapshot */
2297                 cgbno = fragstoblks(fs, cgtod(fs, cg));
2298         } else {
2299                 /* devvp is a normal disk device */
2300                 cgbno = fsbtodb(fs, cgtod(fs, cg));
2301         }
2302         if (ino >= fs->fs_ipg * fs->fs_ncg)
2303                 return (1);
2304         if (bread(devvp, cgbno, (int)fs->fs_cgsize, NOCRED, &bp)) {
2305                 brelse(bp);
2306                 return (1);
2307         }
2308         cgp = (struct cg *)bp->b_data;
2309         if (!cg_chkmagic(cgp)) {
2310                 brelse(bp);
2311                 return (1);
2312         }
2313         inosused = cg_inosused(cgp);
2314         ino %= fs->fs_ipg;
2315         ret = isclr(inosused, ino);
2316         brelse(bp);
2317         return (ret);
2318 }
2319
2320 /*
2321  * Find a block of the specified size in the specified cylinder group.
2322  *
2323  * It is a panic if a request is made to find a block if none are
2324  * available.
2325  */
2326 static ufs1_daddr_t
2327 ffs_mapsearch(fs, cgp, bpref, allocsiz)
2328         struct fs *fs;
2329         struct cg *cgp;
2330         ufs2_daddr_t bpref;
2331         int allocsiz;
2332 {
2333         ufs1_daddr_t bno;
2334         int start, len, loc, i;
2335         int blk, field, subfield, pos;
2336         u_int8_t *blksfree;
2337
2338         /*
2339          * find the fragment by searching through the free block
2340          * map for an appropriate bit pattern
2341          */
2342         if (bpref)
2343                 start = dtogd(fs, bpref) / NBBY;
2344         else
2345                 start = cgp->cg_frotor / NBBY;
2346         blksfree = cg_blksfree(cgp);
2347         len = howmany(fs->fs_fpg, NBBY) - start;
2348         loc = scanc((u_int)len, (u_char *)&blksfree[start],
2349                 fragtbl[fs->fs_frag],
2350                 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2351         if (loc == 0) {
2352                 len = start + 1;
2353                 start = 0;
2354                 loc = scanc((u_int)len, (u_char *)&blksfree[0],
2355                         fragtbl[fs->fs_frag],
2356                         (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2357                 if (loc == 0) {
2358                         printf("start = %d, len = %d, fs = %s\n",
2359                             start, len, fs->fs_fsmnt);
2360                         panic("ffs_alloccg: map corrupted");
2361                         /* NOTREACHED */
2362                 }
2363         }
2364         bno = (start + len - loc) * NBBY;
2365         cgp->cg_frotor = bno;
2366         /*
2367          * found the byte in the map
2368          * sift through the bits to find the selected frag
2369          */
2370         for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2371                 blk = blkmap(fs, blksfree, bno);
2372                 blk <<= 1;
2373                 field = around[allocsiz];
2374                 subfield = inside[allocsiz];
2375                 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2376                         if ((blk & field) == subfield)
2377                                 return (bno + pos);
2378                         field <<= 1;
2379                         subfield <<= 1;
2380                 }
2381         }
2382         printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
2383         panic("ffs_alloccg: block not in map");
2384         return (-1);
2385 }
2386
2387 /*
2388  * Update the cluster map because of an allocation or free.
2389  *
2390  * Cnt == 1 means free; cnt == -1 means allocating.
2391  */
2392 void
2393 ffs_clusteracct(ump, fs, cgp, blkno, cnt)
2394         struct ufsmount *ump;
2395         struct fs *fs;
2396         struct cg *cgp;
2397         ufs1_daddr_t blkno;
2398         int cnt;
2399 {
2400         int32_t *sump;
2401         int32_t *lp;
2402         u_char *freemapp, *mapp;
2403         int i, start, end, forw, back, map, bit;
2404
2405         mtx_assert(UFS_MTX(ump), MA_OWNED);
2406
2407         if (fs->fs_contigsumsize <= 0)
2408                 return;
2409         freemapp = cg_clustersfree(cgp);
2410         sump = cg_clustersum(cgp);
2411         /*
2412          * Allocate or clear the actual block.
2413          */
2414         if (cnt > 0)
2415                 setbit(freemapp, blkno);
2416         else
2417                 clrbit(freemapp, blkno);
2418         /*
2419          * Find the size of the cluster going forward.
2420          */
2421         start = blkno + 1;
2422         end = start + fs->fs_contigsumsize;
2423         if (end >= cgp->cg_nclusterblks)
2424                 end = cgp->cg_nclusterblks;
2425         mapp = &freemapp[start / NBBY];
2426         map = *mapp++;
2427         bit = 1 << (start % NBBY);
2428         for (i = start; i < end; i++) {
2429                 if ((map & bit) == 0)
2430                         break;
2431                 if ((i & (NBBY - 1)) != (NBBY - 1)) {
2432                         bit <<= 1;
2433                 } else {
2434                         map = *mapp++;
2435                         bit = 1;
2436                 }
2437         }
2438         forw = i - start;
2439         /*
2440          * Find the size of the cluster going backward.
2441          */
2442         start = blkno - 1;
2443         end = start - fs->fs_contigsumsize;
2444         if (end < 0)
2445                 end = -1;
2446         mapp = &freemapp[start / NBBY];
2447         map = *mapp--;
2448         bit = 1 << (start % NBBY);
2449         for (i = start; i > end; i--) {
2450                 if ((map & bit) == 0)
2451                         break;
2452                 if ((i & (NBBY - 1)) != 0) {
2453                         bit >>= 1;
2454                 } else {
2455                         map = *mapp--;
2456                         bit = 1 << (NBBY - 1);
2457                 }
2458         }
2459         back = start - i;
2460         /*
2461          * Account for old cluster and the possibly new forward and
2462          * back clusters.
2463          */
2464         i = back + forw + 1;
2465         if (i > fs->fs_contigsumsize)
2466                 i = fs->fs_contigsumsize;
2467         sump[i] += cnt;
2468         if (back > 0)
2469                 sump[back] -= cnt;
2470         if (forw > 0)
2471                 sump[forw] -= cnt;
2472         /*
2473          * Update cluster summary information.
2474          */
2475         lp = &sump[fs->fs_contigsumsize];
2476         for (i = fs->fs_contigsumsize; i > 0; i--)
2477                 if (*lp-- > 0)
2478                         break;
2479         fs->fs_maxcluster[cgp->cg_cgx] = i;
2480 }
2481
2482 /*
2483  * Fserr prints the name of a filesystem with an error diagnostic.
2484  *
2485  * The form of the error message is:
2486  *      fs: error message
2487  */
2488 static void
2489 ffs_fserr(fs, inum, cp)
2490         struct fs *fs;
2491         ino_t inum;
2492         char *cp;
2493 {
2494         struct thread *td = curthread;  /* XXX */
2495         struct proc *p = td->td_proc;
2496
2497         log(LOG_ERR, "pid %d (%s), uid %d inumber %d on %s: %s\n",
2498             p->p_pid, p->p_comm, td->td_ucred->cr_uid, inum, fs->fs_fsmnt, cp);
2499 }
2500
2501 /*
2502  * This function provides the capability for the fsck program to
2503  * update an active filesystem. Eleven operations are provided:
2504  *
2505  * adjrefcnt(inode, amt) - adjusts the reference count on the
2506  *      specified inode by the specified amount. Under normal
2507  *      operation the count should always go down. Decrementing
2508  *      the count to zero will cause the inode to be freed.
2509  * adjblkcnt(inode, amt) - adjust the number of blocks used to
2510  *      by the specifed amount.
2511  * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
2512  *      adjust the superblock summary.
2513  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
2514  *      are marked as free. Inodes should never have to be marked
2515  *      as in use.
2516  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
2517  *      are marked as free. Inodes should never have to be marked
2518  *      as in use.
2519  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
2520  *      are marked as free. Blocks should never have to be marked
2521  *      as in use.
2522  * setflags(flags, set/clear) - the fs_flags field has the specified
2523  *      flags set (second parameter +1) or cleared (second parameter -1).
2524  */
2525
2526 static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
2527
2528 SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt, CTLFLAG_WR|CTLTYPE_STRUCT,
2529         0, 0, sysctl_ffs_fsck, "S,fsck", "Adjust Inode Reference Count");
2530
2531 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt, CTLFLAG_WR,
2532         sysctl_ffs_fsck, "Adjust Inode Used Blocks Count");
2533
2534 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir, CTLFLAG_WR,
2535         sysctl_ffs_fsck, "Adjust number of directories");
2536
2537 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree, CTLFLAG_WR,
2538         sysctl_ffs_fsck, "Adjust number of free blocks");
2539
2540 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree, CTLFLAG_WR,
2541         sysctl_ffs_fsck, "Adjust number of free inodes");
2542
2543 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree, CTLFLAG_WR,
2544         sysctl_ffs_fsck, "Adjust number of free frags");
2545
2546 static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters, CTLFLAG_WR,
2547         sysctl_ffs_fsck, "Adjust number of free clusters");
2548
2549 static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs, CTLFLAG_WR,
2550         sysctl_ffs_fsck, "Free Range of Directory Inodes");
2551
2552 static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles, CTLFLAG_WR,
2553         sysctl_ffs_fsck, "Free Range of File Inodes");
2554
2555 static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks, CTLFLAG_WR,
2556         sysctl_ffs_fsck, "Free Range of Blocks");
2557
2558 static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags, CTLFLAG_WR,
2559         sysctl_ffs_fsck, "Change Filesystem Flags");
2560
2561 #ifdef DEBUG
2562 static int fsckcmds = 0;
2563 SYSCTL_INT(_debug, OID_AUTO, fsckcmds, CTLFLAG_RW, &fsckcmds, 0, "");
2564 #endif /* DEBUG */
2565
2566 static int
2567 sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
2568 {
2569         struct fsck_cmd cmd;
2570         struct ufsmount *ump;
2571         struct vnode *vp;
2572         struct inode *ip;
2573         struct mount *mp;
2574         struct fs *fs;
2575         ufs2_daddr_t blkno;
2576         long blkcnt, blksize;
2577         struct file *fp;
2578         int filetype, error;
2579
2580         if (req->newlen > sizeof cmd)
2581                 return (EBADRPC);
2582         if ((error = SYSCTL_IN(req, &cmd, sizeof cmd)) != 0)
2583                 return (error);
2584         if (cmd.version != FFS_CMD_VERSION)
2585                 return (ERPCMISMATCH);
2586         if ((error = getvnode(curproc->p_fd, cmd.handle, &fp)) != 0)
2587                 return (error);
2588         vn_start_write(fp->f_data, &mp, V_WAIT);
2589         if (mp == 0 || strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
2590                 vn_finished_write(mp);
2591                 fdrop(fp, curthread);
2592                 return (EINVAL);
2593         }
2594         if (mp->mnt_flag & MNT_RDONLY) {
2595                 vn_finished_write(mp);
2596                 fdrop(fp, curthread);
2597                 return (EROFS);
2598         }
2599         ump = VFSTOUFS(mp);
2600         fs = ump->um_fs;
2601         filetype = IFREG;
2602
2603         switch (oidp->oid_number) {
2604
2605         case FFS_SET_FLAGS:
2606 #ifdef DEBUG
2607                 if (fsckcmds)
2608                         printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
2609                             cmd.size > 0 ? "set" : "clear");
2610 #endif /* DEBUG */
2611                 if (cmd.size > 0)
2612                         fs->fs_flags |= (long)cmd.value;
2613                 else
2614                         fs->fs_flags &= ~(long)cmd.value;
2615                 break;
2616
2617         case FFS_ADJ_REFCNT:
2618 #ifdef DEBUG
2619                 if (fsckcmds) {
2620                         printf("%s: adjust inode %jd count by %jd\n",
2621                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2622                             (intmax_t)cmd.size);
2623                 }
2624 #endif /* DEBUG */
2625                 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2626                         break;
2627                 ip = VTOI(vp);
2628                 ip->i_nlink += cmd.size;
2629                 DIP_SET(ip, i_nlink, ip->i_nlink);
2630                 ip->i_effnlink += cmd.size;
2631                 ip->i_flag |= IN_CHANGE;
2632                 if (DOINGSOFTDEP(vp))
2633                         softdep_change_linkcnt(ip);
2634                 vput(vp);
2635                 break;
2636
2637         case FFS_ADJ_BLKCNT:
2638 #ifdef DEBUG
2639                 if (fsckcmds) {
2640                         printf("%s: adjust inode %jd block count by %jd\n",
2641                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
2642                             (intmax_t)cmd.size);
2643                 }
2644 #endif /* DEBUG */
2645                 if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
2646                         break;
2647                 ip = VTOI(vp);
2648                 if (ip->i_flag & IN_SPACECOUNTED) {
2649                         UFS_LOCK(ump);
2650                         fs->fs_pendingblocks += cmd.size;
2651                         UFS_UNLOCK(ump);
2652                 }
2653                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
2654                 ip->i_flag |= IN_CHANGE;
2655                 vput(vp);
2656                 break;
2657
2658         case FFS_DIR_FREE:
2659                 filetype = IFDIR;
2660                 /* fall through */
2661
2662         case FFS_FILE_FREE:
2663 #ifdef DEBUG
2664                 if (fsckcmds) {
2665                         if (cmd.size == 1)
2666                                 printf("%s: free %s inode %d\n",
2667                                     mp->mnt_stat.f_mntonname,
2668                                     filetype == IFDIR ? "directory" : "file",
2669                                     (ino_t)cmd.value);
2670                         else
2671                                 printf("%s: free %s inodes %d-%d\n",
2672                                     mp->mnt_stat.f_mntonname,
2673                                     filetype == IFDIR ? "directory" : "file",
2674                                     (ino_t)cmd.value,
2675                                     (ino_t)(cmd.value + cmd.size - 1));
2676                 }
2677 #endif /* DEBUG */
2678                 while (cmd.size > 0) {
2679                         if ((error = ffs_freefile(ump, fs, ump->um_devvp,
2680                             cmd.value, filetype)))
2681                                 break;
2682                         cmd.size -= 1;
2683                         cmd.value += 1;
2684                 }
2685                 break;
2686
2687         case FFS_BLK_FREE:
2688 #ifdef DEBUG
2689                 if (fsckcmds) {
2690                         if (cmd.size == 1)
2691                                 printf("%s: free block %jd\n",
2692                                     mp->mnt_stat.f_mntonname,
2693                                     (intmax_t)cmd.value);
2694                         else
2695                                 printf("%s: free blocks %jd-%jd\n",
2696                                     mp->mnt_stat.f_mntonname, 
2697                                     (intmax_t)cmd.value,
2698                                     (intmax_t)cmd.value + cmd.size - 1);
2699                 }
2700 #endif /* DEBUG */
2701                 blkno = cmd.value;
2702                 blkcnt = cmd.size;
2703                 blksize = fs->fs_frag - (blkno % fs->fs_frag);
2704                 while (blkcnt > 0) {
2705                         if (blksize > blkcnt)
2706                                 blksize = blkcnt;
2707                         ffs_blkfree(ump, fs, ump->um_devvp, blkno,
2708                             blksize * fs->fs_fsize, ROOTINO);
2709                         blkno += blksize;
2710                         blkcnt -= blksize;
2711                         blksize = fs->fs_frag;
2712                 }
2713                 break;
2714
2715         /*
2716          * Adjust superblock summaries.  fsck(8) is expected to
2717          * submit deltas when necessary.
2718          */
2719         case FFS_ADJ_NDIR:
2720 #ifdef DEBUG
2721                 if (fsckcmds) {
2722                         printf("%s: adjust number of directories by %jd\n",
2723                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2724                 }
2725 #endif /* DEBUG */
2726                 fs->fs_cstotal.cs_ndir += cmd.value;
2727                 break;
2728         case FFS_ADJ_NBFREE:
2729 #ifdef DEBUG
2730                 if (fsckcmds) {
2731                         printf("%s: adjust number of free blocks by %+jd\n",
2732                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2733                 }
2734 #endif /* DEBUG */
2735                 fs->fs_cstotal.cs_nbfree += cmd.value;
2736                 break;
2737         case FFS_ADJ_NIFREE:
2738 #ifdef DEBUG
2739                 if (fsckcmds) {
2740                         printf("%s: adjust number of free inodes by %+jd\n",
2741                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2742                 }
2743 #endif /* DEBUG */
2744                 fs->fs_cstotal.cs_nifree += cmd.value;
2745                 break;
2746         case FFS_ADJ_NFFREE:
2747 #ifdef DEBUG
2748                 if (fsckcmds) {
2749                         printf("%s: adjust number of free frags by %+jd\n",
2750                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2751                 }
2752 #endif /* DEBUG */
2753                 fs->fs_cstotal.cs_nffree += cmd.value;
2754                 break;
2755         case FFS_ADJ_NUMCLUSTERS:
2756 #ifdef DEBUG
2757                 if (fsckcmds) {
2758                         printf("%s: adjust number of free clusters by %+jd\n",
2759                             mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
2760                 }
2761 #endif /* DEBUG */
2762                 fs->fs_cstotal.cs_numclusters += cmd.value;
2763                 break;
2764
2765         default:
2766 #ifdef DEBUG
2767                 if (fsckcmds) {
2768                         printf("Invalid request %d from fsck\n",
2769                             oidp->oid_number);
2770                 }
2771 #endif /* DEBUG */
2772                 error = EINVAL;
2773                 break;
2774
2775         }
2776         fdrop(fp, curthread);
2777         vn_finished_write(mp);
2778         return (error);
2779 }