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