Major BUF/BIO work commit. Make I/O BIO-centric and specify the disk or
[dragonfly.git] / sys / vfs / ufs / ffs_alloc.c
1 /*
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)ffs_alloc.c 8.18 (Berkeley) 5/26/95
34  * $FreeBSD: src/sys/ufs/ffs/ffs_alloc.c,v 1.64.2.2 2001/09/21 19:15:21 dillon Exp $
35  * $DragonFly: src/sys/vfs/ufs/ffs_alloc.c,v 1.18 2006/03/24 18:35:34 dillon Exp $
36  */
37
38 #include "opt_quota.h"
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/buf.h>
43 #include <sys/conf.h>
44 #include <sys/proc.h>
45 #include <sys/vnode.h>
46 #include <sys/mount.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/syslog.h>
50
51 #include <machine/inttypes.h>
52
53 #include "quota.h"
54 #include "inode.h"
55 #include "ufs_extern.h"
56 #include "ufsmount.h"
57
58 #include "fs.h"
59 #include "ffs_extern.h"
60
61 typedef ufs_daddr_t allocfcn_t (struct inode *ip, int cg, ufs_daddr_t bpref,
62                                   int size);
63
64 static ufs_daddr_t ffs_alloccg (struct inode *, int, ufs_daddr_t, int);
65 static ufs_daddr_t
66               ffs_alloccgblk (struct inode *, struct buf *, ufs_daddr_t);
67 #ifdef DIAGNOSTIC
68 static int      ffs_checkblk (struct inode *, ufs_daddr_t, long);
69 #endif
70 static void     ffs_clusteracct (struct fs *, struct cg *, ufs_daddr_t,
71                                      int);
72 static ufs_daddr_t ffs_clusteralloc (struct inode *, int, ufs_daddr_t,
73             int);
74 static ino_t    ffs_dirpref (struct inode *);
75 static ufs_daddr_t ffs_fragextend (struct inode *, int, long, int, int);
76 static void     ffs_fserr (struct fs *, uint, char *);
77 static u_long   ffs_hashalloc
78                     (struct inode *, int, long, int, allocfcn_t *);
79 static ino_t    ffs_nodealloccg (struct inode *, int, ufs_daddr_t, int);
80 static ufs_daddr_t ffs_mapsearch (struct fs *, struct cg *, ufs_daddr_t,
81             int);
82
83 /*
84  * Allocate a block in the filesystem.
85  *
86  * The size of the requested block is given, which must be some
87  * multiple of fs_fsize and <= fs_bsize.
88  * A preference may be optionally specified. If a preference is given
89  * the following hierarchy is used to allocate a block:
90  *   1) allocate the requested block.
91  *   2) allocate a rotationally optimal block in the same cylinder.
92  *   3) allocate a block in the same cylinder group.
93  *   4) quadradically rehash into other cylinder groups, until an
94  *      available block is located.
95  * If no block preference is given the following heirarchy is used
96  * to allocate a block:
97  *   1) allocate a block in the cylinder group that contains the
98  *      inode for the file.
99  *   2) quadradically rehash into other cylinder groups, until an
100  *      available block is located.
101  */
102 int
103 ffs_alloc(struct inode *ip, ufs_daddr_t lbn, ufs_daddr_t bpref, int size,
104           struct ucred *cred, ufs_daddr_t *bnp)
105 {
106         struct fs *fs;
107         ufs_daddr_t bno;
108         int cg;
109 #ifdef QUOTA
110         int error;
111 #endif
112
113         *bnp = 0;
114         fs = ip->i_fs;
115 #ifdef DIAGNOSTIC
116         if ((uint)size > fs->fs_bsize || fragoff(fs, size) != 0) {
117                 printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
118                     devtoname(ip->i_dev), (long)fs->fs_bsize, size,
119                     fs->fs_fsmnt);
120                 panic("ffs_alloc: bad size");
121         }
122         if (cred == NOCRED)
123                 panic("ffs_alloc: missing credential");
124 #endif /* DIAGNOSTIC */
125         if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
126                 goto nospace;
127         if (cred->cr_uid != 0 &&
128             freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
129                 goto nospace;
130 #ifdef QUOTA
131         error = chkdq(ip, (long)btodb(size), cred, 0);
132         if (error)
133                 return (error);
134 #endif
135         if (bpref >= fs->fs_size)
136                 bpref = 0;
137         if (bpref == 0)
138                 cg = ino_to_cg(fs, ip->i_number);
139         else
140                 cg = dtog(fs, bpref);
141         bno = (ufs_daddr_t)ffs_hashalloc(ip, cg, (long)bpref, size,
142                                          ffs_alloccg);
143         if (bno > 0) {
144                 ip->i_blocks += btodb(size);
145                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
146                 *bnp = bno;
147                 return (0);
148         }
149 #ifdef QUOTA
150         /*
151          * Restore user's disk quota because allocation failed.
152          */
153         (void) chkdq(ip, (long)-btodb(size), cred, FORCE);
154 #endif
155 nospace:
156         ffs_fserr(fs, cred->cr_uid, "filesystem full");
157         uprintf("\n%s: write failed, filesystem is full\n", fs->fs_fsmnt);
158         return (ENOSPC);
159 }
160
161 /*
162  * Reallocate a fragment to a bigger size
163  *
164  * The number and size of the old block is given, and a preference
165  * and new size is also specified. The allocator attempts to extend
166  * the original block. Failing that, the regular block allocator is
167  * invoked to get an appropriate block.
168  */
169 int
170 ffs_realloccg(struct inode *ip, ufs_daddr_t lbprev, ufs_daddr_t bpref,
171               int osize, int nsize, struct ucred *cred, struct buf **bpp)
172 {
173         struct fs *fs;
174         struct buf *bp;
175         int cg, request, error;
176         ufs_daddr_t bprev, bno;
177
178         *bpp = 0;
179         fs = ip->i_fs;
180 #ifdef DIAGNOSTIC
181         if ((uint)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
182             (uint)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
183                 printf(
184                 "dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
185                     devtoname(ip->i_dev), (long)fs->fs_bsize, osize,
186                     nsize, fs->fs_fsmnt);
187                 panic("ffs_realloccg: bad size");
188         }
189         if (cred == NOCRED)
190                 panic("ffs_realloccg: missing credential");
191 #endif /* DIAGNOSTIC */
192         if (cred->cr_uid != 0 &&
193             freespace(fs, fs->fs_minfree) -  numfrags(fs, nsize - osize) < 0)
194                 goto nospace;
195         if ((bprev = ip->i_db[lbprev]) == 0) {
196                 printf("dev = %s, bsize = %ld, bprev = %ld, fs = %s\n",
197                     devtoname(ip->i_dev), (long)fs->fs_bsize, (long)bprev,
198                     fs->fs_fsmnt);
199                 panic("ffs_realloccg: bad bprev");
200         }
201         /*
202          * Allocate the extra space in the buffer.
203          */
204         error = bread(ITOV(ip), lblktodoff(fs, lbprev), osize, &bp);
205         if (error) {
206                 brelse(bp);
207                 return (error);
208         }
209
210         if(bp->b_bio2.bio_offset == NOOFFSET) {
211                 if( lbprev >= NDADDR)
212                         panic("ffs_realloccg: lbprev out of range");
213                 bp->b_bio2.bio_offset = fsbtodoff(fs, bprev);
214         }
215
216 #ifdef QUOTA
217         error = chkdq(ip, (long)btodb(nsize - osize), cred, 0);
218         if (error) {
219                 brelse(bp);
220                 return (error);
221         }
222 #endif
223         /*
224          * Check for extension in the existing location.
225          */
226         cg = dtog(fs, bprev);
227         bno = ffs_fragextend(ip, cg, (long)bprev, osize, nsize);
228         if (bno) {
229                 if (bp->b_bio2.bio_offset != fsbtodoff(fs, bno))
230                         panic("ffs_realloccg: bad blockno");
231                 ip->i_blocks += btodb(nsize - osize);
232                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
233                 allocbuf(bp, nsize);
234                 bp->b_flags |= B_DONE;
235                 bzero((char *)bp->b_data + osize, (uint)nsize - osize);
236                 *bpp = bp;
237                 return (0);
238         }
239         /*
240          * Allocate a new disk location.
241          */
242         if (bpref >= fs->fs_size)
243                 bpref = 0;
244         switch ((int)fs->fs_optim) {
245         case FS_OPTSPACE:
246                 /*
247                  * Allocate an exact sized fragment. Although this makes
248                  * best use of space, we will waste time relocating it if
249                  * the file continues to grow. If the fragmentation is
250                  * less than half of the minimum free reserve, we choose
251                  * to begin optimizing for time.
252                  */
253                 request = nsize;
254                 if (fs->fs_minfree <= 5 ||
255                     fs->fs_cstotal.cs_nffree >
256                     (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
257                         break;
258                 log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
259                         fs->fs_fsmnt);
260                 fs->fs_optim = FS_OPTTIME;
261                 break;
262         case FS_OPTTIME:
263                 /*
264                  * At this point we have discovered a file that is trying to
265                  * grow a small fragment to a larger fragment. To save time,
266                  * we allocate a full sized block, then free the unused portion.
267                  * If the file continues to grow, the `ffs_fragextend' call
268                  * above will be able to grow it in place without further
269                  * copying. If aberrant programs cause disk fragmentation to
270                  * grow within 2% of the free reserve, we choose to begin
271                  * optimizing for space.
272                  */
273                 request = fs->fs_bsize;
274                 if (fs->fs_cstotal.cs_nffree <
275                     (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
276                         break;
277                 log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
278                         fs->fs_fsmnt);
279                 fs->fs_optim = FS_OPTSPACE;
280                 break;
281         default:
282                 printf("dev = %s, optim = %ld, fs = %s\n",
283                     devtoname(ip->i_dev), (long)fs->fs_optim, fs->fs_fsmnt);
284                 panic("ffs_realloccg: bad optim");
285                 /* NOTREACHED */
286         }
287         bno = (ufs_daddr_t)ffs_hashalloc(ip, cg, (long)bpref, request,
288                                          ffs_alloccg);
289         if (bno > 0) {
290                 bp->b_bio2.bio_offset = fsbtodoff(fs, bno);
291                 if (!DOINGSOFTDEP(ITOV(ip)))
292                         ffs_blkfree(ip, bprev, (long)osize);
293                 if (nsize < request)
294                         ffs_blkfree(ip, bno + numfrags(fs, nsize),
295                             (long)(request - nsize));
296                 ip->i_blocks += btodb(nsize - osize);
297                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
298                 allocbuf(bp, nsize);
299                 bp->b_flags |= B_DONE;
300                 bzero((char *)bp->b_data + osize, (uint)nsize - osize);
301                 *bpp = bp;
302                 return (0);
303         }
304 #ifdef QUOTA
305         /*
306          * Restore user's disk quota because allocation failed.
307          */
308         (void) chkdq(ip, (long)-btodb(nsize - osize), cred, FORCE);
309 #endif
310         brelse(bp);
311 nospace:
312         /*
313          * no space available
314          */
315         ffs_fserr(fs, cred->cr_uid, "filesystem full");
316         uprintf("\n%s: write failed, filesystem is full\n", fs->fs_fsmnt);
317         return (ENOSPC);
318 }
319
320 SYSCTL_NODE(_vfs, OID_AUTO, ffs, CTLFLAG_RW, 0, "FFS filesystem");
321
322 /*
323  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
324  *
325  * The vnode and an array of buffer pointers for a range of sequential
326  * logical blocks to be made contiguous is given. The allocator attempts
327  * to find a range of sequential blocks starting as close as possible to
328  * an fs_rotdelay offset from the end of the allocation for the logical
329  * block immediately preceeding the current range. If successful, the
330  * physical block numbers in the buffer pointers and in the inode are
331  * changed to reflect the new allocation. If unsuccessful, the allocation
332  * is left unchanged. The success in doing the reallocation is returned.
333  * Note that the error return is not reflected back to the user. Rather
334  * the previous block allocation will be used.
335  */
336 static int doasyncfree = 1;
337 SYSCTL_INT(_vfs_ffs, FFS_ASYNCFREE, doasyncfree, CTLFLAG_RW, &doasyncfree, 0, "");
338
339 static int doreallocblks = 1;
340 SYSCTL_INT(_vfs_ffs, FFS_REALLOCBLKS, doreallocblks, CTLFLAG_RW, &doreallocblks, 0, "");
341
342 #ifdef DEBUG
343 static volatile int prtrealloc = 0;
344 #endif
345
346 /*
347  * ffs_reallocblks(struct vnode *a_vp, struct cluster_save *a_buflist)
348  */
349 int
350 ffs_reallocblks(struct vop_reallocblks_args *ap)
351 {
352         struct fs *fs;
353         struct inode *ip;
354         struct vnode *vp;
355         struct buf *sbp, *ebp;
356         ufs_daddr_t *bap, *sbap, *ebap = 0;
357         struct cluster_save *buflist;
358         ufs_daddr_t start_lbn, end_lbn, soff, newblk, blkno;
359 #ifdef DIAGNOSTIC
360         off_t boffset;
361 #endif
362         struct indir start_ap[NIADDR + 1], end_ap[NIADDR + 1], *idp;
363         int i, len, slen, start_lvl, end_lvl, pref, ssize;
364
365         if (doreallocblks == 0)
366                 return (ENOSPC);
367         vp = ap->a_vp;
368         ip = VTOI(vp);
369         fs = ip->i_fs;
370         if (fs->fs_contigsumsize <= 0)
371                 return (ENOSPC);
372         buflist = ap->a_buflist;
373         len = buflist->bs_nchildren;
374         start_lbn = lblkno(fs, buflist->bs_children[0]->b_loffset);
375         end_lbn = start_lbn + len - 1;
376 #ifdef DIAGNOSTIC
377         for (i = 0; i < len; i++)
378                 if (!ffs_checkblk(ip,
379                    dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset), fs->fs_bsize))
380                         panic("ffs_reallocblks: unallocated block 1");
381         for (i = 1; i < len; i++) {
382                 if (buflist->bs_children[i]->b_loffset != lblktodoff(fs, start_lbn) + lblktodoff(fs, i))
383                         panic("ffs_reallocblks: non-logical cluster");
384         }
385         boffset = buflist->bs_children[0]->b_bio2.bio_offset;
386         ssize = (int)fsbtodoff(fs, fs->fs_frag);
387         for (i = 1; i < len - 1; i++)
388                 if (buflist->bs_children[i]->b_bio2.bio_offset != boffset + (i * ssize))
389                         panic("ffs_reallocblks: non-physical cluster %d", i);
390 #endif
391         /*
392          * If the latest allocation is in a new cylinder group, assume that
393          * the filesystem has decided to move and do not force it back to
394          * the previous cylinder group.
395          */
396         if (dtog(fs, dofftofsb(fs, buflist->bs_children[0]->b_bio2.bio_offset)) !=
397             dtog(fs, dofftofsb(fs, buflist->bs_children[len - 1]->b_bio2.bio_offset)))
398                 return (ENOSPC);
399         if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
400             ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
401                 return (ENOSPC);
402         /*
403          * Get the starting offset and block map for the first block and
404          * the number of blocks that will fit into sbap starting at soff.
405          */
406         if (start_lvl == 0) {
407                 sbap = &ip->i_db[0];
408                 soff = start_lbn;
409                 slen = NDADDR - soff;
410         } else {
411                 idp = &start_ap[start_lvl - 1];
412                 if (bread(vp, lblktodoff(fs, idp->in_lbn), (int)fs->fs_bsize, &sbp)) {
413                         brelse(sbp);
414                         return (ENOSPC);
415                 }
416                 sbap = (ufs_daddr_t *)sbp->b_data;
417                 soff = idp->in_off;
418                 slen = fs->fs_nindir - soff;
419         }
420         /*
421          * Find the preferred location for the cluster.
422          */
423         pref = ffs_blkpref(ip, start_lbn, soff, sbap);
424         /*
425          * If the block range spans two block maps, get the second map.
426          */
427         if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
428                 ssize = len;
429         } else {
430 #ifdef DIAGNOSTIC
431                 if (start_ap[start_lvl-1].in_lbn == idp->in_lbn)
432                         panic("ffs_reallocblk: start == end");
433 #endif
434                 ssize = len - (idp->in_off + 1);
435                 if (bread(vp, lblktodoff(fs, idp->in_lbn), (int)fs->fs_bsize, &ebp))
436                         goto fail;
437                 ebap = (ufs_daddr_t *)ebp->b_data;
438         }
439
440         /*
441          * Make sure we aren't spanning more then two blockmaps.  ssize is
442          * our calculation of the span we have to scan in the first blockmap,
443          * while slen is our calculation of the number of entries available
444          * in the first blockmap (from soff).
445          */
446         if (ssize > slen) {
447                 panic("ffs_reallocblks: range spans more then two blockmaps!"
448                         " start_lbn %ld len %d (%d/%d)",
449                         (long)start_lbn, len, slen, ssize);
450         }
451         /*
452          * Search the block map looking for an allocation of the desired size.
453          */
454         if ((newblk = (ufs_daddr_t)ffs_hashalloc(ip, dtog(fs, pref), (long)pref,
455             len, ffs_clusteralloc)) == 0)
456                 goto fail;
457         /*
458          * We have found a new contiguous block.
459          *
460          * First we have to replace the old block pointers with the new
461          * block pointers in the inode and indirect blocks associated
462          * with the file.
463          */
464 #ifdef DEBUG
465         if (prtrealloc)
466                 printf("realloc: ino %d, lbns %d-%d\n\told:", ip->i_number,
467                     start_lbn, end_lbn);
468 #endif
469         blkno = newblk;
470         for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
471                 if (i == ssize) {
472                         bap = ebap;
473                         soff = -i;
474                 }
475 #ifdef DIAGNOSTIC
476                 if (!ffs_checkblk(ip,
477                    dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset), fs->fs_bsize))
478                         panic("ffs_reallocblks: unallocated block 2");
479                 if (dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset) != *bap)
480                         panic("ffs_reallocblks: alloc mismatch");
481 #endif
482 #ifdef DEBUG
483                 if (prtrealloc)
484                         printf(" %d,", *bap);
485 #endif
486                 if (DOINGSOFTDEP(vp)) {
487                         if (sbap == &ip->i_db[0] && i < ssize)
488                                 softdep_setup_allocdirect(ip, start_lbn + i,
489                                     blkno, *bap, fs->fs_bsize, fs->fs_bsize,
490                                     buflist->bs_children[i]);
491                         else
492                                 softdep_setup_allocindir_page(ip, start_lbn + i,
493                                     i < ssize ? sbp : ebp, soff + i, blkno,
494                                     *bap, buflist->bs_children[i]);
495                 }
496                 *bap++ = blkno;
497         }
498         /*
499          * Next we must write out the modified inode and indirect blocks.
500          * For strict correctness, the writes should be synchronous since
501          * the old block values may have been written to disk. In practise
502          * they are almost never written, but if we are concerned about
503          * strict correctness, the `doasyncfree' flag should be set to zero.
504          *
505          * The test on `doasyncfree' should be changed to test a flag
506          * that shows whether the associated buffers and inodes have
507          * been written. The flag should be set when the cluster is
508          * started and cleared whenever the buffer or inode is flushed.
509          * We can then check below to see if it is set, and do the
510          * synchronous write only when it has been cleared.
511          */
512         if (sbap != &ip->i_db[0]) {
513                 if (doasyncfree)
514                         bdwrite(sbp);
515                 else
516                         bwrite(sbp);
517         } else {
518                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
519                 if (!doasyncfree)
520                         UFS_UPDATE(vp, 1);
521         }
522         if (ssize < len) {
523                 if (doasyncfree)
524                         bdwrite(ebp);
525                 else
526                         bwrite(ebp);
527         }
528         /*
529          * Last, free the old blocks and assign the new blocks to the buffers.
530          */
531 #ifdef DEBUG
532         if (prtrealloc)
533                 printf("\n\tnew:");
534 #endif
535         for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
536                 if (!DOINGSOFTDEP(vp))
537                         ffs_blkfree(ip,
538                             dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset),
539                             fs->fs_bsize);
540                 buflist->bs_children[i]->b_bio2.bio_offset = fsbtodoff(fs, blkno);
541 #ifdef DIAGNOSTIC
542                 if (!ffs_checkblk(ip,
543                    dofftofsb(fs, buflist->bs_children[i]->b_bio2.bio_offset), fs->fs_bsize))
544                         panic("ffs_reallocblks: unallocated block 3");
545 #endif
546 #ifdef DEBUG
547                 if (prtrealloc)
548                         printf(" %d,", blkno);
549 #endif
550         }
551 #ifdef DEBUG
552         if (prtrealloc) {
553                 prtrealloc--;
554                 printf("\n");
555         }
556 #endif
557         return (0);
558
559 fail:
560         if (ssize < len)
561                 brelse(ebp);
562         if (sbap != &ip->i_db[0])
563                 brelse(sbp);
564         return (ENOSPC);
565 }
566
567 /*
568  * Allocate an inode in the filesystem.
569  *
570  * If allocating a directory, use ffs_dirpref to select the inode.
571  * If allocating in a directory, the following hierarchy is followed:
572  *   1) allocate the preferred inode.
573  *   2) allocate an inode in the same cylinder group.
574  *   3) quadradically rehash into other cylinder groups, until an
575  *      available inode is located.
576  * If no inode preference is given the following heirarchy is used
577  * to allocate an inode:
578  *   1) allocate an inode in cylinder group 0.
579  *   2) quadradically rehash into other cylinder groups, until an
580  *      available inode is located.
581  */
582 int
583 ffs_valloc(struct vnode *pvp, int mode, struct ucred *cred, struct vnode **vpp)
584 {
585         struct inode *pip;
586         struct fs *fs;
587         struct inode *ip;
588         ino_t ino, ipref;
589         int cg, error;
590
591         *vpp = NULL;
592         pip = VTOI(pvp);
593         fs = pip->i_fs;
594         if (fs->fs_cstotal.cs_nifree == 0)
595                 goto noinodes;
596
597         if ((mode & IFMT) == IFDIR)
598                 ipref = ffs_dirpref(pip);
599         else
600                 ipref = pip->i_number;
601         if (ipref >= fs->fs_ncg * fs->fs_ipg)
602                 ipref = 0;
603         cg = ino_to_cg(fs, ipref);
604         /*
605          * Track number of dirs created one after another
606          * in a same cg without intervening by files.
607          */
608         if ((mode & IFMT) == IFDIR) {
609                 if (fs->fs_contigdirs[cg] < 255)
610                         fs->fs_contigdirs[cg]++;
611         } else {
612                 if (fs->fs_contigdirs[cg] > 0)
613                         fs->fs_contigdirs[cg]--;
614         }
615         ino = (ino_t)ffs_hashalloc(pip, cg, (long)ipref, mode,
616                                         (allocfcn_t *)ffs_nodealloccg);
617         if (ino == 0)
618                 goto noinodes;
619         error = VFS_VGET(pvp->v_mount, ino, vpp);
620         if (error) {
621                 UFS_VFREE(pvp, ino, mode);
622                 return (error);
623         }
624         ip = VTOI(*vpp);
625         if (ip->i_mode) {
626                 printf("mode = 0%o, inum = %lu, fs = %s\n",
627                     ip->i_mode, (u_long)ip->i_number, fs->fs_fsmnt);
628                 panic("ffs_valloc: dup alloc");
629         }
630         if (ip->i_blocks) {                             /* XXX */
631                 printf("free inode %s/%lu had %ld blocks\n",
632                     fs->fs_fsmnt, (u_long)ino, (long)ip->i_blocks);
633                 ip->i_blocks = 0;
634         }
635         ip->i_flags = 0;
636         /*
637          * Set up a new generation number for this inode.
638          */
639         if (ip->i_gen == 0 || ++ip->i_gen == 0)
640                 ip->i_gen = random() / 2 + 1;
641         return (0);
642 noinodes:
643         ffs_fserr(fs, cred->cr_uid, "out of inodes");
644         uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
645         return (ENOSPC);
646 }
647
648 /*
649  * Find a cylinder group to place a directory.
650  *
651  * The policy implemented by this algorithm is to allocate a
652  * directory inode in the same cylinder group as its parent
653  * directory, but also to reserve space for its files inodes
654  * and data. Restrict the number of directories which may be
655  * allocated one after another in the same cylinder group
656  * without intervening allocation of files.
657  *
658  * If we allocate a first level directory then force allocation
659  * in another cylinder group.
660  */
661 static ino_t
662 ffs_dirpref(struct inode *pip)
663 {
664         struct fs *fs;
665         int cg, prefcg, dirsize, cgsize;
666         int64_t dirsize64;
667         int avgifree, avgbfree, avgndir, curdirsize;
668         int minifree, minbfree, maxndir;
669         int mincg, minndir;
670         int maxcontigdirs;
671
672         fs = pip->i_fs;
673
674         avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
675         avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
676         avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
677
678         /*
679          * Force allocation in another cg if creating a first level dir.
680          */
681         if (ITOV(pip)->v_flag & VROOT) {
682                 prefcg = arc4random() % fs->fs_ncg;
683                 mincg = prefcg;
684                 minndir = fs->fs_ipg;
685                 for (cg = prefcg; cg < fs->fs_ncg; cg++)
686                         if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
687                             fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
688                             fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
689                                 mincg = cg;
690                                 minndir = fs->fs_cs(fs, cg).cs_ndir;
691                         }
692                 for (cg = 0; cg < prefcg; cg++)
693                         if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
694                             fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
695                             fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
696                                 mincg = cg;
697                                 minndir = fs->fs_cs(fs, cg).cs_ndir;
698                         }
699                 return ((ino_t)(fs->fs_ipg * mincg));
700         }
701
702         /*
703          * Count various limits which used for
704          * optimal allocation of a directory inode.
705          */
706         maxndir = min(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
707         minifree = avgifree - avgifree / 4;
708         if (minifree < 1)
709                 minifree = 1;
710         minbfree = avgbfree - avgbfree / 4;
711         if (minbfree < 1)
712                 minbfree = 1;
713         cgsize = fs->fs_fsize * fs->fs_fpg;
714
715         /*
716          * fs_avgfilesize and fs_avgfpdir are user-settable entities and
717          * multiplying them may overflow a 32 bit integer.
718          */
719         dirsize64 = fs->fs_avgfilesize * (int64_t)fs->fs_avgfpdir;
720         if (dirsize64 > 0x7fffffff) {
721                 maxcontigdirs = 1;
722         } else {
723                 dirsize = (int)dirsize64;
724                 curdirsize = avgndir ?
725                         (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
726                 if (dirsize < curdirsize)
727                         dirsize = curdirsize;
728                 maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
729                 if (fs->fs_avgfpdir > 0)
730                         maxcontigdirs = min(maxcontigdirs,
731                                     fs->fs_ipg / fs->fs_avgfpdir);
732                 if (maxcontigdirs == 0)
733                         maxcontigdirs = 1;
734         }
735
736         /*
737          * Limit number of dirs in one cg and reserve space for 
738          * regular files, but only if we have no deficit in
739          * inodes or space.
740          */
741         prefcg = ino_to_cg(fs, pip->i_number);
742         for (cg = prefcg; cg < fs->fs_ncg; cg++)
743                 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
744                     fs->fs_cs(fs, cg).cs_nifree >= minifree &&
745                     fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
746                         if (fs->fs_contigdirs[cg] < maxcontigdirs)
747                                 return ((ino_t)(fs->fs_ipg * cg));
748                 }
749         for (cg = 0; cg < prefcg; cg++)
750                 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
751                     fs->fs_cs(fs, cg).cs_nifree >= minifree &&
752                     fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
753                         if (fs->fs_contigdirs[cg] < maxcontigdirs)
754                                 return ((ino_t)(fs->fs_ipg * cg));
755                 }
756         /*
757          * This is a backstop when we have deficit in space.
758          */
759         for (cg = prefcg; cg < fs->fs_ncg; cg++)
760                 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
761                         return ((ino_t)(fs->fs_ipg * cg));
762         for (cg = 0; cg < prefcg; cg++)
763                 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
764                         break;
765         return ((ino_t)(fs->fs_ipg * cg));
766 }
767
768 /*
769  * Select the desired position for the next block in a file.  The file is
770  * logically divided into sections. The first section is composed of the
771  * direct blocks. Each additional section contains fs_maxbpg blocks.
772  *
773  * If no blocks have been allocated in the first section, the policy is to
774  * request a block in the same cylinder group as the inode that describes
775  * the file. If no blocks have been allocated in any other section, the
776  * policy is to place the section in a cylinder group with a greater than
777  * average number of free blocks.  An appropriate cylinder group is found
778  * by using a rotor that sweeps the cylinder groups. When a new group of
779  * blocks is needed, the sweep begins in the cylinder group following the
780  * cylinder group from which the previous allocation was made. The sweep
781  * continues until a cylinder group with greater than the average number
782  * of free blocks is found. If the allocation is for the first block in an
783  * indirect block, the information on the previous allocation is unavailable;
784  * here a best guess is made based upon the logical block number being
785  * allocated.
786  *
787  * If a section is already partially allocated, the policy is to
788  * contiguously allocate fs_maxcontig blocks.  The end of one of these
789  * contiguous blocks and the beginning of the next is physically separated
790  * so that the disk head will be in transit between them for at least
791  * fs_rotdelay milliseconds.  This is to allow time for the processor to
792  * schedule another I/O transfer.
793  */
794 ufs_daddr_t
795 ffs_blkpref(struct inode *ip, ufs_daddr_t lbn, int indx, ufs_daddr_t *bap)
796 {
797         struct fs *fs;
798         int cg;
799         int avgbfree, startcg;
800         ufs_daddr_t nextblk;
801
802         fs = ip->i_fs;
803         if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
804                 if (lbn < NDADDR + NINDIR(fs)) {
805                         cg = ino_to_cg(fs, ip->i_number);
806                         return (fs->fs_fpg * cg + fs->fs_frag);
807                 }
808                 /*
809                  * Find a cylinder with greater than average number of
810                  * unused data blocks.
811                  */
812                 if (indx == 0 || bap[indx - 1] == 0)
813                         startcg =
814                             ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
815                 else
816                         startcg = dtog(fs, bap[indx - 1]) + 1;
817                 startcg %= fs->fs_ncg;
818                 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
819                 for (cg = startcg; cg < fs->fs_ncg; cg++)
820                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
821                                 fs->fs_cgrotor = cg;
822                                 return (fs->fs_fpg * cg + fs->fs_frag);
823                         }
824                 for (cg = 0; cg <= startcg; cg++)
825                         if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
826                                 fs->fs_cgrotor = cg;
827                                 return (fs->fs_fpg * cg + fs->fs_frag);
828                         }
829                 return (0);
830         }
831         /*
832          * One or more previous blocks have been laid out. If less
833          * than fs_maxcontig previous blocks are contiguous, the
834          * next block is requested contiguously, otherwise it is
835          * requested rotationally delayed by fs_rotdelay milliseconds.
836          */
837         nextblk = bap[indx - 1] + fs->fs_frag;
838         if (fs->fs_rotdelay == 0 || indx < fs->fs_maxcontig ||
839             bap[indx - fs->fs_maxcontig] +
840             blkstofrags(fs, fs->fs_maxcontig) != nextblk)
841                 return (nextblk);
842         /*
843          * Here we convert ms of delay to frags as:
844          * (frags) = (ms) * (rev/sec) * (sect/rev) /
845          *      ((sect/frag) * (ms/sec))
846          * then round up to the next block.
847          */
848         nextblk += roundup(fs->fs_rotdelay * fs->fs_rps * fs->fs_nsect /
849             (NSPF(fs) * 1000), fs->fs_frag);
850         return (nextblk);
851 }
852
853 /*
854  * Implement the cylinder overflow algorithm.
855  *
856  * The policy implemented by this algorithm is:
857  *   1) allocate the block in its requested cylinder group.
858  *   2) quadradically rehash on the cylinder group number.
859  *   3) brute force search for a free block.
860  */
861 /*VARARGS5*/
862 static u_long
863 ffs_hashalloc(struct inode *ip, int cg, long pref,
864               int size, /* size for data blocks, mode for inodes */
865               allocfcn_t *allocator)
866 {
867         struct fs *fs;
868         long result;    /* XXX why not same type as we return? */
869         int i, icg = cg;
870
871         fs = ip->i_fs;
872         /*
873          * 1: preferred cylinder group
874          */
875         result = (*allocator)(ip, cg, pref, size);
876         if (result)
877                 return (result);
878         /*
879          * 2: quadratic rehash
880          */
881         for (i = 1; i < fs->fs_ncg; i *= 2) {
882                 cg += i;
883                 if (cg >= fs->fs_ncg)
884                         cg -= fs->fs_ncg;
885                 result = (*allocator)(ip, cg, 0, size);
886                 if (result)
887                         return (result);
888         }
889         /*
890          * 3: brute force search
891          * Note that we start at i == 2, since 0 was checked initially,
892          * and 1 is always checked in the quadratic rehash.
893          */
894         cg = (icg + 2) % fs->fs_ncg;
895         for (i = 2; i < fs->fs_ncg; i++) {
896                 result = (*allocator)(ip, cg, 0, size);
897                 if (result)
898                         return (result);
899                 cg++;
900                 if (cg == fs->fs_ncg)
901                         cg = 0;
902         }
903         return (0);
904 }
905
906 /*
907  * Determine whether a fragment can be extended.
908  *
909  * Check to see if the necessary fragments are available, and
910  * if they are, allocate them.
911  */
912 static ufs_daddr_t
913 ffs_fragextend(struct inode *ip, int cg, long bprev, int osize, int nsize)
914 {
915         struct fs *fs;
916         struct cg *cgp;
917         struct buf *bp;
918         long bno;
919         int frags, bbase;
920         int i, error;
921         uint8_t *blksfree;
922
923         fs = ip->i_fs;
924         if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
925                 return (0);
926         frags = numfrags(fs, nsize);
927         bbase = fragnum(fs, bprev);
928         if (bbase > fragnum(fs, (bprev + frags - 1))) {
929                 /* cannot extend across a block boundary */
930                 return (0);
931         }
932         KKASSERT(blknum(fs, bprev) == blknum(fs, bprev + frags - 1));
933         error = bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
934                 (int)fs->fs_cgsize, &bp);
935         if (error) {
936                 brelse(bp);
937                 return (0);
938         }
939         cgp = (struct cg *)bp->b_data;
940         if (!cg_chkmagic(cgp)) {
941                 brelse(bp);
942                 return (0);
943         }
944         bp->b_xflags |= BX_BKGRDWRITE;
945         cgp->cg_time = time_second;
946         bno = dtogd(fs, bprev);
947         blksfree = cg_blksfree(cgp);
948         for (i = numfrags(fs, osize); i < frags; i++) {
949                 if (isclr(blksfree, bno + i)) {
950                         brelse(bp);
951                         return (0);
952                 }
953         }
954
955         /*
956          * the current fragment can be extended
957          * deduct the count on fragment being extended into
958          * increase the count on the remaining fragment (if any)
959          * allocate the extended piece
960          *
961          * ---oooooooooonnnnnnn111----
962          *    [-----frags-----]
963          *    ^                       ^
964          *    bbase                   fs_frag
965          */
966         for (i = frags; i < fs->fs_frag - bbase; i++) {
967                 if (isclr(blksfree, bno + i))
968                         break;
969         }
970
971         /*
972          * Size of original free frag is [i - numfrags(fs, osize)]
973          * Size of remaining free frag is [i - frags]
974          */
975         cgp->cg_frsum[i - numfrags(fs, osize)]--;
976         if (i != frags)
977                 cgp->cg_frsum[i - frags]++;
978         for (i = numfrags(fs, osize); i < frags; i++) {
979                 clrbit(blksfree, bno + i);
980                 cgp->cg_cs.cs_nffree--;
981                 fs->fs_cstotal.cs_nffree--;
982                 fs->fs_cs(fs, cg).cs_nffree--;
983         }
984         fs->fs_fmod = 1;
985         if (DOINGSOFTDEP(ITOV(ip)))
986                 softdep_setup_blkmapdep(bp, fs, bprev);
987         bdwrite(bp);
988         return (bprev);
989 }
990
991 /*
992  * Determine whether a block can be allocated.
993  *
994  * Check to see if a block of the appropriate size is available,
995  * and if it is, allocate it.
996  */
997 static ufs_daddr_t
998 ffs_alloccg(struct inode *ip, int cg, ufs_daddr_t bpref, int size)
999 {
1000         struct fs *fs;
1001         struct cg *cgp;
1002         struct buf *bp;
1003         int i;
1004         ufs_daddr_t bno, blkno;
1005         int allocsiz, error, frags;
1006         uint8_t *blksfree;
1007
1008         fs = ip->i_fs;
1009         if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1010                 return (0);
1011         error = bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
1012                 (int)fs->fs_cgsize, &bp);
1013         if (error) {
1014                 brelse(bp);
1015                 return (0);
1016         }
1017         cgp = (struct cg *)bp->b_data;
1018         if (!cg_chkmagic(cgp) ||
1019             (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
1020                 brelse(bp);
1021                 return (0);
1022         }
1023         bp->b_xflags |= BX_BKGRDWRITE;
1024         cgp->cg_time = time_second;
1025         if (size == fs->fs_bsize) {
1026                 bno = ffs_alloccgblk(ip, bp, bpref);
1027                 bdwrite(bp);
1028                 return (bno);
1029         }
1030         /*
1031          * Check to see if any fragments of sufficient size are already
1032          * available.  Fit the data into a larger fragment if necessary,
1033          * before allocating a whole new block.
1034          */
1035         blksfree = cg_blksfree(cgp);
1036         frags = numfrags(fs, size);
1037         for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++) {
1038                 if (cgp->cg_frsum[allocsiz] != 0)
1039                         break;
1040         }
1041         if (allocsiz == fs->fs_frag) {
1042                 /*
1043                  * No fragments were available, allocate a whole block and
1044                  * cut the requested fragment (of size frags) out of it.
1045                  */
1046                 if (cgp->cg_cs.cs_nbfree == 0) {
1047                         brelse(bp);
1048                         return (0);
1049                 }
1050                 bno = ffs_alloccgblk(ip, bp, bpref);
1051                 bpref = dtogd(fs, bno);
1052                 for (i = frags; i < fs->fs_frag; i++)
1053                         setbit(blksfree, bpref + i);
1054
1055                 /*
1056                  * Calculate the number of free frags still remaining after
1057                  * we have cut out the requested allocation.  Indicate that
1058                  * a fragment of that size is now available for future
1059                  * allocation.
1060                  */
1061                 i = fs->fs_frag - frags;
1062                 cgp->cg_cs.cs_nffree += i;
1063                 fs->fs_cstotal.cs_nffree += i;
1064                 fs->fs_cs(fs, cg).cs_nffree += i;
1065                 fs->fs_fmod = 1;
1066                 cgp->cg_frsum[i]++;
1067                 bdwrite(bp);
1068                 return (bno);
1069         }
1070
1071         /*
1072          * cg_frsum[] has told us that a free fragment of allocsiz size is
1073          * available.  Find it, then clear the bitmap bits associated with
1074          * the size we want.
1075          */
1076         bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1077         if (bno < 0) {
1078                 brelse(bp);
1079                 return (0);
1080         }
1081         for (i = 0; i < frags; i++)
1082                 clrbit(blksfree, bno + i);
1083         cgp->cg_cs.cs_nffree -= frags;
1084         fs->fs_cstotal.cs_nffree -= frags;
1085         fs->fs_cs(fs, cg).cs_nffree -= frags;
1086         fs->fs_fmod = 1;
1087
1088         /*
1089          * Account for the allocation.  The original searched size that we
1090          * found is no longer available.  If we cut out a smaller piece then
1091          * a smaller fragment is now available.
1092          */
1093         cgp->cg_frsum[allocsiz]--;
1094         if (frags != allocsiz)
1095                 cgp->cg_frsum[allocsiz - frags]++;
1096         blkno = cg * fs->fs_fpg + bno;
1097         if (DOINGSOFTDEP(ITOV(ip)))
1098                 softdep_setup_blkmapdep(bp, fs, blkno);
1099         bdwrite(bp);
1100         return ((u_long)blkno);
1101 }
1102
1103 /*
1104  * Allocate a block in a cylinder group.
1105  *
1106  * This algorithm implements the following policy:
1107  *   1) allocate the requested block.
1108  *   2) allocate a rotationally optimal block in the same cylinder.
1109  *   3) allocate the next available block on the block rotor for the
1110  *      specified cylinder group.
1111  * Note that this routine only allocates fs_bsize blocks; these
1112  * blocks may be fragmented by the routine that allocates them.
1113  */
1114 static ufs_daddr_t
1115 ffs_alloccgblk(struct inode *ip, struct buf *bp, ufs_daddr_t bpref)
1116 {
1117         struct fs *fs;
1118         struct cg *cgp;
1119         ufs_daddr_t bno, blkno;
1120         int cylno, pos, delta;
1121         short *cylbp;
1122         int i;
1123         uint8_t *blksfree;
1124
1125         fs = ip->i_fs;
1126         cgp = (struct cg *)bp->b_data;
1127         blksfree = cg_blksfree(cgp);
1128         if (bpref == 0 || dtog(fs, bpref) != cgp->cg_cgx) {
1129                 bpref = cgp->cg_rotor;
1130                 goto norot;
1131         }
1132         bpref = blknum(fs, bpref);
1133         bpref = dtogd(fs, bpref);
1134         /*
1135          * if the requested block is available, use it
1136          */
1137         if (ffs_isblock(fs, blksfree, fragstoblks(fs, bpref))) {
1138                 bno = bpref;
1139                 goto gotit;
1140         }
1141         if (fs->fs_nrpos <= 1 || fs->fs_cpc == 0) {
1142                 /*
1143                  * Block layout information is not available.
1144                  * Leaving bpref unchanged means we take the
1145                  * next available free block following the one
1146                  * we just allocated. Hopefully this will at
1147                  * least hit a track cache on drives of unknown
1148                  * geometry (e.g. SCSI).
1149                  */
1150                 goto norot;
1151         }
1152         /*
1153          * check for a block available on the same cylinder
1154          */
1155         cylno = cbtocylno(fs, bpref);
1156         if (cg_blktot(cgp)[cylno] == 0)
1157                 goto norot;
1158         /*
1159          * check the summary information to see if a block is
1160          * available in the requested cylinder starting at the
1161          * requested rotational position and proceeding around.
1162          */
1163         cylbp = cg_blks(fs, cgp, cylno);
1164         pos = cbtorpos(fs, bpref);
1165         for (i = pos; i < fs->fs_nrpos; i++)
1166                 if (cylbp[i] > 0)
1167                         break;
1168         if (i == fs->fs_nrpos)
1169                 for (i = 0; i < pos; i++)
1170                         if (cylbp[i] > 0)
1171                                 break;
1172         if (cylbp[i] > 0) {
1173                 /*
1174                  * found a rotational position, now find the actual
1175                  * block. A panic if none is actually there.
1176                  */
1177                 pos = cylno % fs->fs_cpc;
1178                 bno = (cylno - pos) * fs->fs_spc / NSPB(fs);
1179                 if (fs_postbl(fs, pos)[i] == -1) {
1180                         printf("pos = %d, i = %d, fs = %s\n",
1181                             pos, i, fs->fs_fsmnt);
1182                         panic("ffs_alloccgblk: cyl groups corrupted");
1183                 }
1184                 for (i = fs_postbl(fs, pos)[i];; ) {
1185                         if (ffs_isblock(fs, blksfree, bno + i)) {
1186                                 bno = blkstofrags(fs, (bno + i));
1187                                 goto gotit;
1188                         }
1189                         delta = fs_rotbl(fs)[i];
1190                         if (delta <= 0 ||
1191                             delta + i > fragstoblks(fs, fs->fs_fpg))
1192                                 break;
1193                         i += delta;
1194                 }
1195                 printf("pos = %d, i = %d, fs = %s\n", pos, i, fs->fs_fsmnt);
1196                 panic("ffs_alloccgblk: can't find blk in cyl");
1197         }
1198 norot:
1199         /*
1200          * no blocks in the requested cylinder, so take next
1201          * available one in this cylinder group.
1202          */
1203         bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1204         if (bno < 0)
1205                 return (0);
1206         cgp->cg_rotor = bno;
1207 gotit:
1208         blkno = fragstoblks(fs, bno);
1209         ffs_clrblock(fs, blksfree, (long)blkno);
1210         ffs_clusteracct(fs, cgp, blkno, -1);
1211         cgp->cg_cs.cs_nbfree--;
1212         fs->fs_cstotal.cs_nbfree--;
1213         fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1214         cylno = cbtocylno(fs, bno);
1215         cg_blks(fs, cgp, cylno)[cbtorpos(fs, bno)]--;
1216         cg_blktot(cgp)[cylno]--;
1217         fs->fs_fmod = 1;
1218         blkno = cgp->cg_cgx * fs->fs_fpg + bno;
1219         if (DOINGSOFTDEP(ITOV(ip)))
1220                 softdep_setup_blkmapdep(bp, fs, blkno);
1221         return (blkno);
1222 }
1223
1224 /*
1225  * Determine whether a cluster can be allocated.
1226  *
1227  * We do not currently check for optimal rotational layout if there
1228  * are multiple choices in the same cylinder group. Instead we just
1229  * take the first one that we find following bpref.
1230  */
1231 static ufs_daddr_t
1232 ffs_clusteralloc(struct inode *ip, int cg, ufs_daddr_t bpref, int len)
1233 {
1234         struct fs *fs;
1235         struct cg *cgp;
1236         struct buf *bp;
1237         int i, got, run, bno, bit, map;
1238         u_char *mapp;
1239         int32_t *lp;
1240         uint8_t *blksfree;
1241
1242         fs = ip->i_fs;
1243         if (fs->fs_maxcluster[cg] < len)
1244                 return (0);
1245         if (bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
1246                   (int)fs->fs_cgsize, &bp)) {
1247                 goto fail;
1248         }
1249         cgp = (struct cg *)bp->b_data;
1250         if (!cg_chkmagic(cgp))
1251                 goto fail;
1252         bp->b_xflags |= BX_BKGRDWRITE;
1253         /*
1254          * Check to see if a cluster of the needed size (or bigger) is
1255          * available in this cylinder group.
1256          */
1257         lp = &cg_clustersum(cgp)[len];
1258         for (i = len; i <= fs->fs_contigsumsize; i++)
1259                 if (*lp++ > 0)
1260                         break;
1261         if (i > fs->fs_contigsumsize) {
1262                 /*
1263                  * This is the first time looking for a cluster in this
1264                  * cylinder group. Update the cluster summary information
1265                  * to reflect the true maximum sized cluster so that
1266                  * future cluster allocation requests can avoid reading
1267                  * the cylinder group map only to find no clusters.
1268                  */
1269                 lp = &cg_clustersum(cgp)[len - 1];
1270                 for (i = len - 1; i > 0; i--)
1271                         if (*lp-- > 0)
1272                                 break;
1273                 fs->fs_maxcluster[cg] = i;
1274                 goto fail;
1275         }
1276         /*
1277          * Search the cluster map to find a big enough cluster.
1278          * We take the first one that we find, even if it is larger
1279          * than we need as we prefer to get one close to the previous
1280          * block allocation. We do not search before the current
1281          * preference point as we do not want to allocate a block
1282          * that is allocated before the previous one (as we will
1283          * then have to wait for another pass of the elevator
1284          * algorithm before it will be read). We prefer to fail and
1285          * be recalled to try an allocation in the next cylinder group.
1286          */
1287         if (dtog(fs, bpref) != cg)
1288                 bpref = 0;
1289         else
1290                 bpref = fragstoblks(fs, dtogd(fs, blknum(fs, bpref)));
1291         mapp = &cg_clustersfree(cgp)[bpref / NBBY];
1292         map = *mapp++;
1293         bit = 1 << (bpref % NBBY);
1294         for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
1295                 if ((map & bit) == 0) {
1296                         run = 0;
1297                 } else {
1298                         run++;
1299                         if (run == len)
1300                                 break;
1301                 }
1302                 if ((got & (NBBY - 1)) != (NBBY - 1)) {
1303                         bit <<= 1;
1304                 } else {
1305                         map = *mapp++;
1306                         bit = 1;
1307                 }
1308         }
1309         if (got >= cgp->cg_nclusterblks)
1310                 goto fail;
1311         /*
1312          * Allocate the cluster that we have found.
1313          */
1314         blksfree = cg_blksfree(cgp);
1315         for (i = 1; i <= len; i++) {
1316                 if (!ffs_isblock(fs, blksfree, got - run + i))
1317                         panic("ffs_clusteralloc: map mismatch");
1318         }
1319         bno = cg * fs->fs_fpg + blkstofrags(fs, got - run + 1);
1320         if (dtog(fs, bno) != cg)
1321                 panic("ffs_clusteralloc: allocated out of group");
1322         len = blkstofrags(fs, len);
1323         for (i = 0; i < len; i += fs->fs_frag) {
1324                 if ((got = ffs_alloccgblk(ip, bp, bno + i)) != bno + i)
1325                         panic("ffs_clusteralloc: lost block");
1326         }
1327         bdwrite(bp);
1328         return (bno);
1329
1330 fail:
1331         brelse(bp);
1332         return (0);
1333 }
1334
1335 /*
1336  * Determine whether an inode can be allocated.
1337  *
1338  * Check to see if an inode is available, and if it is,
1339  * allocate it using the following policy:
1340  *   1) allocate the requested inode.
1341  *   2) allocate the next available inode after the requested
1342  *      inode in the specified cylinder group.
1343  *   3) the inode must not already be in the inode hash table.  We
1344  *      can encounter such a case because the vnode reclamation sequence
1345  *      frees the bit
1346  *   3) the inode must not already be in the inode hash, otherwise it
1347  *      may be in the process of being deallocated.  This can occur
1348  *      because the bitmap is updated before the inode is removed from
1349  *      hash.  If we were to reallocate the inode the caller could wind
1350  *      up returning a vnode/inode combination which is in an indeterminate
1351  *      state.
1352  */
1353 static ino_t
1354 ffs_nodealloccg(struct inode *ip, int cg, ufs_daddr_t ipref, int mode)
1355 {
1356         struct fs *fs;
1357         struct cg *cgp;
1358         struct buf *bp;
1359         uint8_t *inosused;
1360         uint8_t map;
1361         int error, len, arraysize, i;
1362         int icheckmiss;
1363         ufs_daddr_t ibase;
1364
1365         fs = ip->i_fs;
1366         if (fs->fs_cs(fs, cg).cs_nifree == 0)
1367                 return (0);
1368         error = bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
1369                       (int)fs->fs_cgsize, &bp);
1370         if (error) {
1371                 brelse(bp);
1372                 return (0);
1373         }
1374         cgp = (struct cg *)bp->b_data;
1375         if (!cg_chkmagic(cgp) || cgp->cg_cs.cs_nifree == 0) {
1376                 brelse(bp);
1377                 return (0);
1378         }
1379         inosused = cg_inosused(cgp);
1380         icheckmiss = 0;
1381
1382         /*
1383          * Quick check, reuse the most recently free inode or continue
1384          * a scan from where we left off the last time.
1385          */
1386         ibase = cg * fs->fs_ipg;
1387         if (ipref) {
1388                 ipref %= fs->fs_ipg;
1389                 if (isclr(inosused, ipref)) {
1390                         if (ufs_ihashcheck(ip->i_dev, ibase + ipref) == 0)
1391                                 goto gotit;
1392                 }
1393         }
1394
1395         /*
1396          * Scan the inode bitmap starting at irotor, be sure to handle
1397          * the edge case by going back to the beginning of the array.
1398          *
1399          * If the number of inodes is not byte-aligned, the unused bits
1400          * should be set to 1.  This will be sanity checked in gotit.  Note
1401          * that we have to be sure not to overlap the beginning and end
1402          * when irotor is in the middle of a byte as this will cause the
1403          * same bitmap byte to be checked twice.  To solve this problem we
1404          * just convert everything to a byte index for the loop.
1405          */
1406         ipref = (cgp->cg_irotor % fs->fs_ipg) >> 3;     /* byte index */
1407         len = (fs->fs_ipg + 7) >> 3;                    /* byte size */
1408         arraysize = len;
1409
1410         while (len > 0) {
1411                 map = inosused[ipref];
1412                 if (map != 255) {
1413                         for (i = 0; i < NBBY; ++i) {
1414                                 /*
1415                                  * If we find a free bit we have to make sure
1416                                  * that the inode is not in the middle of
1417                                  * being destroyed.  The inode should not exist
1418                                  * in the inode hash.
1419                                  *
1420                                  * Adjust the rotor to try to hit the 
1421                                  * quick-check up above.
1422                                  */
1423                                 if ((map & (1 << i)) == 0) {
1424                                         if (ufs_ihashcheck(ip->i_dev, ibase + (ipref << 3) + i) == 0) {
1425                                                 ipref = (ipref << 3) + i;
1426                                                 cgp->cg_irotor = (ipref + 1) % fs->fs_ipg;
1427                                                 goto gotit;
1428                                         }
1429                                         ++icheckmiss;
1430                                 }
1431                         }
1432                 }
1433
1434                 /*
1435                  * Setup for the next byte, start at the beginning again if
1436                  * we hit the end of the array.
1437                  */
1438                 if (++ipref == arraysize)
1439                         ipref = 0;
1440                 --len;
1441         }
1442         if (icheckmiss == cgp->cg_cs.cs_nifree) {
1443                 brelse(bp);
1444                 return(0);
1445         }
1446         printf("fs = %s\n", fs->fs_fsmnt);
1447         panic("ffs_nodealloccg: block not in map, icheckmiss/nfree %d/%d",
1448                 icheckmiss, cgp->cg_cs.cs_nifree);
1449         /* NOTREACHED */
1450
1451         /*
1452          * ipref is a bit index as of the gotit label.
1453          */
1454 gotit:
1455         KKASSERT(ipref >= 0 && ipref < fs->fs_ipg);
1456         if (icheckmiss) {
1457                 printf("Warning: inode free race avoided %d times\n",
1458                         icheckmiss);
1459         }
1460         bp->b_xflags |= BX_BKGRDWRITE;
1461         cgp->cg_time = time_second;
1462         if (DOINGSOFTDEP(ITOV(ip)))
1463                 softdep_setup_inomapdep(bp, ip, ibase + ipref);
1464         setbit(inosused, ipref);
1465         cgp->cg_cs.cs_nifree--;
1466         fs->fs_cstotal.cs_nifree--;
1467         fs->fs_cs(fs, cg).cs_nifree--;
1468         fs->fs_fmod = 1;
1469         if ((mode & IFMT) == IFDIR) {
1470                 cgp->cg_cs.cs_ndir++;
1471                 fs->fs_cstotal.cs_ndir++;
1472                 fs->fs_cs(fs, cg).cs_ndir++;
1473         }
1474         bdwrite(bp);
1475         return (ibase + ipref);
1476 }
1477
1478 /*
1479  * Free a block or fragment.
1480  *
1481  * The specified block or fragment is placed back in the
1482  * free map. If a fragment is deallocated, a possible
1483  * block reassembly is checked.
1484  */
1485 void
1486 ffs_blkfree(struct inode *ip, ufs_daddr_t bno, long size)
1487 {
1488         struct fs *fs;
1489         struct cg *cgp;
1490         struct buf *bp;
1491         ufs_daddr_t blkno;
1492         int i, error, cg, blk, frags, bbase;
1493         uint8_t *blksfree;
1494
1495         fs = ip->i_fs;
1496         VOP_FREEBLKS(ip->i_devvp, fsbtodoff(fs, bno), size);
1497         if ((uint)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
1498             fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
1499                 printf("dev=%s, bno = %ld, bsize = %ld, size = %ld, fs = %s\n",
1500                     devtoname(ip->i_dev), (long)bno, (long)fs->fs_bsize, size,
1501                     fs->fs_fsmnt);
1502                 panic("ffs_blkfree: bad size");
1503         }
1504         cg = dtog(fs, bno);
1505         if ((uint)bno >= fs->fs_size) {
1506                 printf("bad block %ld, ino %lu\n",
1507                     (long)bno, (u_long)ip->i_number);
1508                 ffs_fserr(fs, ip->i_uid, "bad block");
1509                 return;
1510         }
1511
1512         /*
1513          * Load the cylinder group
1514          */
1515         error = bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
1516                       (int)fs->fs_cgsize, &bp);
1517         if (error) {
1518                 brelse(bp);
1519                 return;
1520         }
1521         cgp = (struct cg *)bp->b_data;
1522         if (!cg_chkmagic(cgp)) {
1523                 brelse(bp);
1524                 return;
1525         }
1526         bp->b_xflags |= BX_BKGRDWRITE;
1527         cgp->cg_time = time_second;
1528         bno = dtogd(fs, bno);
1529         blksfree = cg_blksfree(cgp);
1530
1531         if (size == fs->fs_bsize) {
1532                 /*
1533                  * Free a whole block
1534                  */
1535                 blkno = fragstoblks(fs, bno);
1536                 if (!ffs_isfreeblock(fs, blksfree, blkno)) {
1537                         printf("dev = %s, block = %ld, fs = %s\n",
1538                             devtoname(ip->i_dev), (long)bno, fs->fs_fsmnt);
1539                         panic("ffs_blkfree: freeing free block");
1540                 }
1541                 ffs_setblock(fs, blksfree, blkno);
1542                 ffs_clusteracct(fs, cgp, blkno, 1);
1543                 cgp->cg_cs.cs_nbfree++;
1544                 fs->fs_cstotal.cs_nbfree++;
1545                 fs->fs_cs(fs, cg).cs_nbfree++;
1546                 i = cbtocylno(fs, bno);
1547                 cg_blks(fs, cgp, i)[cbtorpos(fs, bno)]++;
1548                 cg_blktot(cgp)[i]++;
1549         } else {
1550                 /*
1551                  * Free a fragment within a block.
1552                  *
1553                  * bno is the starting block number of the fragment being
1554                  * freed.
1555                  *
1556                  * bbase is the starting block number for the filesystem
1557                  * block containing the fragment.
1558                  *
1559                  * blk is the current bitmap for the fragments within the
1560                  * filesystem block containing the fragment.
1561                  *
1562                  * frags is the number of fragments being freed
1563                  *
1564                  * Call ffs_fragacct() to account for the removal of all
1565                  * current fragments, then adjust the bitmap to free the
1566                  * requested fragment, and finally call ffs_fragacct() again
1567                  * to regenerate the accounting.
1568                  */
1569                 bbase = bno - fragnum(fs, bno);
1570                 blk = blkmap(fs, blksfree, bbase);
1571                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
1572                 frags = numfrags(fs, size);
1573                 for (i = 0; i < frags; i++) {
1574                         if (isset(blksfree, bno + i)) {
1575                                 printf("dev = %s, block = %ld, fs = %s\n",
1576                                     devtoname(ip->i_dev), (long)(bno + i),
1577                                     fs->fs_fsmnt);
1578                                 panic("ffs_blkfree: freeing free frag");
1579                         }
1580                         setbit(blksfree, bno + i);
1581                 }
1582                 cgp->cg_cs.cs_nffree += i;
1583                 fs->fs_cstotal.cs_nffree += i;
1584                 fs->fs_cs(fs, cg).cs_nffree += i;
1585
1586                 /*
1587                  * Add back in counts associated with the new frags
1588                  */
1589                 blk = blkmap(fs, blksfree, bbase);
1590                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
1591
1592                 /*
1593                  * If a complete block has been reassembled, account for it
1594                  */
1595                 blkno = fragstoblks(fs, bbase);
1596                 if (ffs_isblock(fs, blksfree, blkno)) {
1597                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
1598                         fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1599                         fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1600                         ffs_clusteracct(fs, cgp, blkno, 1);
1601                         cgp->cg_cs.cs_nbfree++;
1602                         fs->fs_cstotal.cs_nbfree++;
1603                         fs->fs_cs(fs, cg).cs_nbfree++;
1604                         i = cbtocylno(fs, bbase);
1605                         cg_blks(fs, cgp, i)[cbtorpos(fs, bbase)]++;
1606                         cg_blktot(cgp)[i]++;
1607                 }
1608         }
1609         fs->fs_fmod = 1;
1610         bdwrite(bp);
1611 }
1612
1613 #ifdef DIAGNOSTIC
1614 /*
1615  * Verify allocation of a block or fragment. Returns true if block or
1616  * fragment is allocated, false if it is free.
1617  */
1618 static int
1619 ffs_checkblk(struct inode *ip, ufs_daddr_t bno, long size)
1620 {
1621         struct fs *fs;
1622         struct cg *cgp;
1623         struct buf *bp;
1624         int i, error, frags, free;
1625         uint8_t *blksfree;
1626
1627         fs = ip->i_fs;
1628         if ((uint)size > fs->fs_bsize || fragoff(fs, size) != 0) {
1629                 printf("bsize = %ld, size = %ld, fs = %s\n",
1630                     (long)fs->fs_bsize, size, fs->fs_fsmnt);
1631                 panic("ffs_checkblk: bad size");
1632         }
1633         if ((uint)bno >= fs->fs_size)
1634                 panic("ffs_checkblk: bad block %d", bno);
1635         error = bread(ip->i_devvp, fsbtodoff(fs, cgtod(fs, dtog(fs, bno))),
1636                       (int)fs->fs_cgsize, &bp);
1637         if (error)
1638                 panic("ffs_checkblk: cg bread failed");
1639         cgp = (struct cg *)bp->b_data;
1640         if (!cg_chkmagic(cgp))
1641                 panic("ffs_checkblk: cg magic mismatch");
1642         bp->b_xflags |= BX_BKGRDWRITE;
1643         blksfree = cg_blksfree(cgp);
1644         bno = dtogd(fs, bno);
1645         if (size == fs->fs_bsize) {
1646                 free = ffs_isblock(fs, blksfree, fragstoblks(fs, bno));
1647         } else {
1648                 frags = numfrags(fs, size);
1649                 for (free = 0, i = 0; i < frags; i++)
1650                         if (isset(blksfree, bno + i))
1651                                 free++;
1652                 if (free != 0 && free != frags)
1653                         panic("ffs_checkblk: partially free fragment");
1654         }
1655         brelse(bp);
1656         return (!free);
1657 }
1658 #endif /* DIAGNOSTIC */
1659
1660 /*
1661  * Free an inode.
1662  */
1663 int
1664 ffs_vfree(struct vnode *pvp, ino_t ino, int mode)
1665 {
1666         if (DOINGSOFTDEP(pvp)) {
1667                 softdep_freefile(pvp, ino, mode);
1668                 return (0);
1669         }
1670         return (ffs_freefile(pvp, ino, mode));
1671 }
1672
1673 /*
1674  * Do the actual free operation.
1675  * The specified inode is placed back in the free map.
1676  */
1677 int
1678 ffs_freefile(struct vnode *pvp, ino_t ino, int mode)
1679 {
1680         struct fs *fs;
1681         struct cg *cgp;
1682         struct inode *pip;
1683         struct buf *bp;
1684         int error, cg;
1685         uint8_t *inosused;
1686
1687         pip = VTOI(pvp);
1688         fs = pip->i_fs;
1689         if ((uint)ino >= fs->fs_ipg * fs->fs_ncg)
1690                 panic("ffs_vfree: range: dev = (%d,%d), ino = %"PRId64", fs = %s",
1691                     major(pip->i_dev), minor(pip->i_dev), ino, fs->fs_fsmnt);
1692         cg = ino_to_cg(fs, ino);
1693         error = bread(pip->i_devvp, fsbtodoff(fs, cgtod(fs, cg)),
1694                       (int)fs->fs_cgsize, &bp);
1695         if (error) {
1696                 brelse(bp);
1697                 return (error);
1698         }
1699         cgp = (struct cg *)bp->b_data;
1700         if (!cg_chkmagic(cgp)) {
1701                 brelse(bp);
1702                 return (0);
1703         }
1704         bp->b_xflags |= BX_BKGRDWRITE;
1705         cgp->cg_time = time_second;
1706         inosused = cg_inosused(cgp);
1707         ino %= fs->fs_ipg;
1708         if (isclr(inosused, ino)) {
1709                 printf("dev = %s, ino = %lu, fs = %s\n",
1710                     devtoname(pip->i_dev), (u_long)ino, fs->fs_fsmnt);
1711                 if (fs->fs_ronly == 0)
1712                         panic("ffs_vfree: freeing free inode");
1713         }
1714         clrbit(inosused, ino);
1715         if (ino < cgp->cg_irotor)
1716                 cgp->cg_irotor = ino;
1717         cgp->cg_cs.cs_nifree++;
1718         fs->fs_cstotal.cs_nifree++;
1719         fs->fs_cs(fs, cg).cs_nifree++;
1720         if ((mode & IFMT) == IFDIR) {
1721                 cgp->cg_cs.cs_ndir--;
1722                 fs->fs_cstotal.cs_ndir--;
1723                 fs->fs_cs(fs, cg).cs_ndir--;
1724         }
1725         fs->fs_fmod = 1;
1726         bdwrite(bp);
1727         return (0);
1728 }
1729
1730 /*
1731  * Find a block of the specified size in the specified cylinder group.
1732  *
1733  * It is a panic if a request is made to find a block if none are
1734  * available.
1735  */
1736 static ufs_daddr_t
1737 ffs_mapsearch(struct fs *fs, struct cg *cgp, ufs_daddr_t bpref, int allocsiz)
1738 {
1739         ufs_daddr_t bno;
1740         int start, len, loc, i;
1741         int blk, field, subfield, pos;
1742         uint8_t *blksfree;
1743
1744         /*
1745          * find the fragment by searching through the free block
1746          * map for an appropriate bit pattern.
1747          */
1748         if (bpref)
1749                 start = dtogd(fs, bpref) / NBBY;
1750         else
1751                 start = cgp->cg_frotor / NBBY;
1752         blksfree = cg_blksfree(cgp);
1753         len = howmany(fs->fs_fpg, NBBY) - start;
1754         loc = scanc((uint)len, (u_char *)&blksfree[start],
1755                 (u_char *)fragtbl[fs->fs_frag],
1756                 (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1757         if (loc == 0) {
1758                 len = start + 1;        /* XXX why overlap here? */
1759                 start = 0;
1760                 loc = scanc((uint)len, (u_char *)&blksfree[0],
1761                         (u_char *)fragtbl[fs->fs_frag],
1762                         (u_char)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
1763                 if (loc == 0) {
1764                         printf("start = %d, len = %d, fs = %s\n",
1765                             start, len, fs->fs_fsmnt);
1766                         panic("ffs_alloccg: map corrupted");
1767                         /* NOTREACHED */
1768                 }
1769         }
1770         bno = (start + len - loc) * NBBY;
1771         cgp->cg_frotor = bno;
1772         /*
1773          * found the byte in the map
1774          * sift through the bits to find the selected frag
1775          */
1776         for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
1777                 blk = blkmap(fs, blksfree, bno);
1778                 blk <<= 1;
1779                 field = around[allocsiz];
1780                 subfield = inside[allocsiz];
1781                 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
1782                         if ((blk & field) == subfield)
1783                                 return (bno + pos);
1784                         field <<= 1;
1785                         subfield <<= 1;
1786                 }
1787         }
1788         printf("bno = %lu, fs = %s\n", (u_long)bno, fs->fs_fsmnt);
1789         panic("ffs_alloccg: block not in map");
1790         return (-1);
1791 }
1792
1793 /*
1794  * Update the cluster map because of an allocation or free.
1795  *
1796  * Cnt == 1 means free; cnt == -1 means allocating.
1797  */
1798 static void
1799 ffs_clusteracct(struct fs *fs, struct cg *cgp, ufs_daddr_t blkno, int cnt)
1800 {
1801         int32_t *sump;
1802         int32_t *lp;
1803         u_char *freemapp, *mapp;
1804         int i, start, end, forw, back, map, bit;
1805
1806         if (fs->fs_contigsumsize <= 0)
1807                 return;
1808         freemapp = cg_clustersfree(cgp);
1809         sump = cg_clustersum(cgp);
1810         /*
1811          * Allocate or clear the actual block.
1812          */
1813         if (cnt > 0)
1814                 setbit(freemapp, blkno);
1815         else
1816                 clrbit(freemapp, blkno);
1817         /*
1818          * Find the size of the cluster going forward.
1819          */
1820         start = blkno + 1;
1821         end = start + fs->fs_contigsumsize;
1822         if (end >= cgp->cg_nclusterblks)
1823                 end = cgp->cg_nclusterblks;
1824         mapp = &freemapp[start / NBBY];
1825         map = *mapp++;
1826         bit = 1 << (start % NBBY);
1827         for (i = start; i < end; i++) {
1828                 if ((map & bit) == 0)
1829                         break;
1830                 if ((i & (NBBY - 1)) != (NBBY - 1)) {
1831                         bit <<= 1;
1832                 } else {
1833                         map = *mapp++;
1834                         bit = 1;
1835                 }
1836         }
1837         forw = i - start;
1838         /*
1839          * Find the size of the cluster going backward.
1840          */
1841         start = blkno - 1;
1842         end = start - fs->fs_contigsumsize;
1843         if (end < 0)
1844                 end = -1;
1845         mapp = &freemapp[start / NBBY];
1846         map = *mapp--;
1847         bit = 1 << (start % NBBY);
1848         for (i = start; i > end; i--) {
1849                 if ((map & bit) == 0)
1850                         break;
1851                 if ((i & (NBBY - 1)) != 0) {
1852                         bit >>= 1;
1853                 } else {
1854                         map = *mapp--;
1855                         bit = 1 << (NBBY - 1);
1856                 }
1857         }
1858         back = start - i;
1859         /*
1860          * Account for old cluster and the possibly new forward and
1861          * back clusters.
1862          */
1863         i = back + forw + 1;
1864         if (i > fs->fs_contigsumsize)
1865                 i = fs->fs_contigsumsize;
1866         sump[i] += cnt;
1867         if (back > 0)
1868                 sump[back] -= cnt;
1869         if (forw > 0)
1870                 sump[forw] -= cnt;
1871         /*
1872          * Update cluster summary information.
1873          */
1874         lp = &sump[fs->fs_contigsumsize];
1875         for (i = fs->fs_contigsumsize; i > 0; i--)
1876                 if (*lp-- > 0)
1877                         break;
1878         fs->fs_maxcluster[cgp->cg_cgx] = i;
1879 }
1880
1881 /*
1882  * Fserr prints the name of a filesystem with an error diagnostic.
1883  *
1884  * The form of the error message is:
1885  *      fs: error message
1886  */
1887 static void
1888 ffs_fserr(struct fs *fs, uint uid, char *cp)
1889 {
1890         struct thread *td = curthread;
1891         struct proc *p;
1892
1893         if ((p = td->td_proc) != NULL) {
1894             log(LOG_ERR, "pid %d (%s), uid %d on %s: %s\n", p ? p->p_pid : -1,
1895                     p ? p->p_comm : "-", uid, fs->fs_fsmnt, cp);
1896         } else {
1897             log(LOG_ERR, "system thread %p, uid %d on %s: %s\n",
1898                     td, uid, fs->fs_fsmnt, cp);
1899         }
1900 }