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