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