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