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