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