ffs_alloc.c revision 1.166.4.1 1 /* $NetBSD: ffs_alloc.c,v 1.166.4.1 2020/04/20 11:29:14 bouyer Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Wasabi Systems, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 2002 Networks Associates Technology, Inc.
34 * All rights reserved.
35 *
36 * This software was developed for the FreeBSD Project by Marshall
37 * Kirk McKusick and Network Associates Laboratories, the Security
38 * Research Division of Network Associates, Inc. under DARPA/SPAWAR
39 * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
40 * research program
41 *
42 * Copyright (c) 1982, 1986, 1989, 1993
43 * The Regents of the University of California. All rights reserved.
44 *
45 * Redistribution and use in source and binary forms, with or without
46 * modification, are permitted provided that the following conditions
47 * are met:
48 * 1. Redistributions of source code must retain the above copyright
49 * notice, this list of conditions and the following disclaimer.
50 * 2. Redistributions in binary form must reproduce the above copyright
51 * notice, this list of conditions and the following disclaimer in the
52 * documentation and/or other materials provided with the distribution.
53 * 3. Neither the name of the University nor the names of its contributors
54 * may be used to endorse or promote products derived from this software
55 * without specific prior written permission.
56 *
57 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * SUCH DAMAGE.
68 *
69 * @(#)ffs_alloc.c 8.19 (Berkeley) 7/13/95
70 */
71
72 #include <sys/cdefs.h>
73 __KERNEL_RCSID(0, "$NetBSD: ffs_alloc.c,v 1.166.4.1 2020/04/20 11:29:14 bouyer Exp $");
74
75 #if defined(_KERNEL_OPT)
76 #include "opt_ffs.h"
77 #include "opt_quota.h"
78 #include "opt_uvm_page_trkown.h"
79 #endif
80
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/buf.h>
84 #include <sys/cprng.h>
85 #include <sys/kauth.h>
86 #include <sys/kernel.h>
87 #include <sys/mount.h>
88 #include <sys/proc.h>
89 #include <sys/syslog.h>
90 #include <sys/vnode.h>
91 #include <sys/wapbl.h>
92 #include <sys/cprng.h>
93
94 #include <miscfs/specfs/specdev.h>
95 #include <ufs/ufs/quota.h>
96 #include <ufs/ufs/ufsmount.h>
97 #include <ufs/ufs/inode.h>
98 #include <ufs/ufs/ufs_extern.h>
99 #include <ufs/ufs/ufs_bswap.h>
100 #include <ufs/ufs/ufs_wapbl.h>
101
102 #include <ufs/ffs/fs.h>
103 #include <ufs/ffs/ffs_extern.h>
104
105 #ifdef UVM_PAGE_TRKOWN
106 #include <uvm/uvm.h>
107 #endif
108
109 static daddr_t ffs_alloccg(struct inode *, int, daddr_t, int, int, int);
110 static daddr_t ffs_alloccgblk(struct inode *, struct buf *, daddr_t, int, int);
111 static ino_t ffs_dirpref(struct inode *);
112 static daddr_t ffs_fragextend(struct inode *, int, daddr_t, int, int);
113 static void ffs_fserr(struct fs *, kauth_cred_t, const char *);
114 static daddr_t ffs_hashalloc(struct inode *, int, daddr_t, int, int, int,
115 daddr_t (*)(struct inode *, int, daddr_t, int, int, int));
116 static daddr_t ffs_nodealloccg(struct inode *, int, daddr_t, int, int, int);
117 static int32_t ffs_mapsearch(struct fs *, struct cg *,
118 daddr_t, int);
119 static void ffs_blkfree_common(struct ufsmount *, struct fs *, dev_t, struct buf *,
120 daddr_t, long, bool);
121 static void ffs_freefile_common(struct ufsmount *, struct fs *, dev_t, struct buf *, ino_t,
122 int, bool);
123
124 /* if 1, changes in optimalization strategy are logged */
125 int ffs_log_changeopt = 0;
126
127 /* in ffs_tables.c */
128 extern const int inside[], around[];
129 extern const u_char * const fragtbl[];
130
131 /* Basic consistency check for block allocations */
132 static int
133 ffs_check_bad_allocation(const char *func, struct fs *fs, daddr_t bno,
134 long size, dev_t dev, ino_t inum)
135 {
136 if ((u_int)size > fs->fs_bsize || ffs_fragoff(fs, size) != 0 ||
137 ffs_fragnum(fs, bno) + ffs_numfrags(fs, size) > fs->fs_frag) {
138 panic("%s: bad size: dev = 0x%llx, bno = %" PRId64
139 " bsize = %d, size = %ld, fs = %s", func,
140 (long long)dev, bno, fs->fs_bsize, size, fs->fs_fsmnt);
141 }
142
143 if (bno >= fs->fs_size) {
144 printf("%s: bad block %" PRId64 ", ino %llu\n", func, bno,
145 (unsigned long long)inum);
146 ffs_fserr(fs, NOCRED, "bad block");
147 return EINVAL;
148 }
149 return 0;
150 }
151
152 /*
153 * Allocate a block in the file system.
154 *
155 * The size of the requested block is given, which must be some
156 * multiple of fs_fsize and <= fs_bsize.
157 * A preference may be optionally specified. If a preference is given
158 * the following hierarchy is used to allocate a block:
159 * 1) allocate the requested block.
160 * 2) allocate a rotationally optimal block in the same cylinder.
161 * 3) allocate a block in the same cylinder group.
162 * 4) quadradically rehash into other cylinder groups, until an
163 * available block is located.
164 * If no block preference is given the following hierarchy is used
165 * to allocate a block:
166 * 1) allocate a block in the cylinder group that contains the
167 * inode for the file.
168 * 2) quadradically rehash into other cylinder groups, until an
169 * available block is located.
170 *
171 * => called with um_lock held
172 * => releases um_lock before returning
173 */
174 int
175 ffs_alloc(struct inode *ip, daddr_t lbn, daddr_t bpref, int size,
176 int flags, kauth_cred_t cred, daddr_t *bnp)
177 {
178 struct ufsmount *ump;
179 struct fs *fs;
180 daddr_t bno;
181 int cg;
182 #if defined(QUOTA) || defined(QUOTA2)
183 int error;
184 #endif
185
186 fs = ip->i_fs;
187 ump = ip->i_ump;
188
189 KASSERT(mutex_owned(&ump->um_lock));
190
191 #ifdef UVM_PAGE_TRKOWN
192
193 /*
194 * Sanity-check that allocations within the file size
195 * do not allow other threads to read the stale contents
196 * of newly allocated blocks.
197 * Usually pages will exist to cover the new allocation.
198 * There is an optimization in ffs_write() where we skip
199 * creating pages if several conditions are met:
200 * - the file must not be mapped (in any user address space).
201 * - the write must cover whole pages and whole blocks.
202 * If those conditions are not met then pages must exist and
203 * be locked by the current thread.
204 */
205
206 struct vnode *vp = ITOV(ip);
207 if (vp->v_type == VREG &&
208 ffs_lblktosize(fs, (voff_t)lbn) < round_page(vp->v_size) &&
209 ((vp->v_vflag & VV_MAPPED) != 0 || (size & PAGE_MASK) != 0 ||
210 ffs_blkoff(fs, size) != 0)) {
211 struct vm_page *pg __diagused;
212 struct uvm_object *uobj = &vp->v_uobj;
213 voff_t off = trunc_page(ffs_lblktosize(fs, lbn));
214 voff_t endoff = round_page(ffs_lblktosize(fs, lbn) + size);
215
216 rw_enter(uobj->vmobjlock, RW_WRITER);
217 while (off < endoff) {
218 pg = uvm_pagelookup(uobj, off);
219 KASSERT((pg != NULL && pg->owner_tag != NULL &&
220 pg->owner == curproc->p_pid &&
221 pg->lowner == curlwp->l_lid));
222 off += PAGE_SIZE;
223 }
224 rw_exit(uobj->vmobjlock);
225 }
226 #endif
227
228 *bnp = 0;
229
230 KASSERTMSG((cred != NOCRED), "missing credential");
231 KASSERTMSG(((u_int)size <= fs->fs_bsize),
232 "bad size: dev = 0x%llx, bsize = %d, size = %d, fs = %s",
233 (unsigned long long)ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
234 KASSERTMSG((ffs_fragoff(fs, size) == 0),
235 "bad size: dev = 0x%llx, bsize = %d, size = %d, fs = %s",
236 (unsigned long long)ip->i_dev, fs->fs_bsize, size, fs->fs_fsmnt);
237
238 if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
239 goto nospace;
240 if (freespace(fs, fs->fs_minfree) <= 0 &&
241 kauth_authorize_system(cred, KAUTH_SYSTEM_FS_RESERVEDSPACE, 0, NULL,
242 NULL, NULL) != 0)
243 goto nospace;
244 #if defined(QUOTA) || defined(QUOTA2)
245 mutex_exit(&ump->um_lock);
246 if ((error = chkdq(ip, btodb(size), cred, 0)) != 0)
247 return (error);
248 mutex_enter(&ump->um_lock);
249 #endif
250
251 if (bpref >= fs->fs_size)
252 bpref = 0;
253 if (bpref == 0)
254 cg = ino_to_cg(fs, ip->i_number);
255 else
256 cg = dtog(fs, bpref);
257 bno = ffs_hashalloc(ip, cg, bpref, size, 0, flags, ffs_alloccg);
258 if (bno > 0) {
259 DIP_ADD(ip, blocks, btodb(size));
260 if (flags & IO_EXT)
261 ip->i_flag |= IN_CHANGE;
262 else
263 ip->i_flag |= IN_CHANGE | IN_UPDATE;
264 *bnp = bno;
265 return (0);
266 }
267 #if defined(QUOTA) || defined(QUOTA2)
268 /*
269 * Restore user's disk quota because allocation failed.
270 */
271 (void) chkdq(ip, -btodb(size), cred, FORCE);
272 #endif
273 if (flags & B_CONTIG) {
274 /*
275 * XXX ump->um_lock handling is "suspect" at best.
276 * For the case where ffs_hashalloc() fails early
277 * in the B_CONTIG case we reach here with um_lock
278 * already unlocked, so we can't release it again
279 * like in the normal error path. See kern/39206.
280 *
281 *
282 * Fail silently - it's up to our caller to report
283 * errors.
284 */
285 return (ENOSPC);
286 }
287 nospace:
288 mutex_exit(&ump->um_lock);
289 ffs_fserr(fs, cred, "file system full");
290 uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
291 return (ENOSPC);
292 }
293
294 /*
295 * Reallocate a fragment to a bigger size
296 *
297 * The number and size of the old block is given, and a preference
298 * and new size is also specified. The allocator attempts to extend
299 * the original block. Failing that, the regular block allocator is
300 * invoked to get an appropriate block.
301 *
302 * => called with um_lock held
303 * => return with um_lock released
304 */
305 int
306 ffs_realloccg(struct inode *ip, daddr_t lbprev, daddr_t bprev, daddr_t bpref,
307 int osize, int nsize, int flags, kauth_cred_t cred, struct buf **bpp,
308 daddr_t *blknop)
309 {
310 struct ufsmount *ump;
311 struct fs *fs;
312 struct buf *bp;
313 int cg, request, error;
314 daddr_t bno;
315
316 fs = ip->i_fs;
317 ump = ip->i_ump;
318
319 KASSERT(mutex_owned(&ump->um_lock));
320
321 #ifdef UVM_PAGE_TRKOWN
322
323 /*
324 * Sanity-check that allocations within the file size
325 * do not allow other threads to read the stale contents
326 * of newly allocated blocks.
327 * Unlike in ffs_alloc(), here pages must always exist
328 * for such allocations, because only the last block of a file
329 * can be a fragment and ffs_write() will reallocate the
330 * fragment to the new size using ufs_balloc_range(),
331 * which always creates pages to cover blocks it allocates.
332 */
333
334 if (ITOV(ip)->v_type == VREG) {
335 struct vm_page *pg __diagused;
336 struct uvm_object *uobj = &ITOV(ip)->v_uobj;
337 voff_t off = trunc_page(ffs_lblktosize(fs, lbprev));
338 voff_t endoff = round_page(ffs_lblktosize(fs, lbprev) + osize);
339
340 rw_enter(uobj->vmobjlock, RW_WRITER);
341 while (off < endoff) {
342 pg = uvm_pagelookup(uobj, off);
343 KASSERT(pg->owner == curproc->p_pid &&
344 pg->lowner == curlwp->l_lid);
345 off += PAGE_SIZE;
346 }
347 rw_exit(uobj->vmobjlock);
348 }
349 #endif
350
351 KASSERTMSG((cred != NOCRED), "missing credential");
352 KASSERTMSG(((u_int)osize <= fs->fs_bsize),
353 "bad size: dev=0x%llx, bsize=%d, osize=%d, nsize=%d, fs=%s",
354 (unsigned long long)ip->i_dev, fs->fs_bsize, osize, nsize,
355 fs->fs_fsmnt);
356 KASSERTMSG((ffs_fragoff(fs, osize) == 0),
357 "bad size: dev=0x%llx, bsize=%d, osize=%d, nsize=%d, fs=%s",
358 (unsigned long long)ip->i_dev, fs->fs_bsize, osize, nsize,
359 fs->fs_fsmnt);
360 KASSERTMSG(((u_int)nsize <= fs->fs_bsize),
361 "bad size: dev=0x%llx, bsize=%d, osize=%d, nsize=%d, fs=%s",
362 (unsigned long long)ip->i_dev, fs->fs_bsize, osize, nsize,
363 fs->fs_fsmnt);
364 KASSERTMSG((ffs_fragoff(fs, nsize) == 0),
365 "bad size: dev=0x%llx, bsize=%d, osize=%d, nsize=%d, fs=%s",
366 (unsigned long long)ip->i_dev, fs->fs_bsize, osize, nsize,
367 fs->fs_fsmnt);
368
369 if (freespace(fs, fs->fs_minfree) <= 0 &&
370 kauth_authorize_system(cred, KAUTH_SYSTEM_FS_RESERVEDSPACE, 0, NULL,
371 NULL, NULL) != 0) {
372 mutex_exit(&ump->um_lock);
373 goto nospace;
374 }
375
376 if (bprev == 0) {
377 panic("%s: bad bprev: dev = 0x%llx, bsize = %d, bprev = %"
378 PRId64 ", fs = %s", __func__,
379 (unsigned long long)ip->i_dev, fs->fs_bsize, bprev,
380 fs->fs_fsmnt);
381 }
382 mutex_exit(&ump->um_lock);
383
384 /*
385 * Allocate the extra space in the buffer.
386 */
387 if (bpp != NULL &&
388 (error = bread(ITOV(ip), lbprev, osize, 0, &bp)) != 0) {
389 return (error);
390 }
391 #if defined(QUOTA) || defined(QUOTA2)
392 if ((error = chkdq(ip, btodb(nsize - osize), cred, 0)) != 0) {
393 if (bpp != NULL) {
394 brelse(bp, 0);
395 }
396 return (error);
397 }
398 #endif
399 /*
400 * Check for extension in the existing location.
401 */
402 cg = dtog(fs, bprev);
403 mutex_enter(&ump->um_lock);
404 if ((bno = ffs_fragextend(ip, cg, bprev, osize, nsize)) != 0) {
405 DIP_ADD(ip, blocks, btodb(nsize - osize));
406 if (flags & IO_EXT)
407 ip->i_flag |= IN_CHANGE;
408 else
409 ip->i_flag |= IN_CHANGE | IN_UPDATE;
410
411 if (bpp != NULL) {
412 if (bp->b_blkno != FFS_FSBTODB(fs, bno)) {
413 panic("%s: bad blockno %#llx != %#llx",
414 __func__, (unsigned long long) bp->b_blkno,
415 (unsigned long long)FFS_FSBTODB(fs, bno));
416 }
417 allocbuf(bp, nsize, 1);
418 memset((char *)bp->b_data + osize, 0, nsize - osize);
419 mutex_enter(bp->b_objlock);
420 KASSERT(!cv_has_waiters(&bp->b_done));
421 bp->b_oflags |= BO_DONE;
422 mutex_exit(bp->b_objlock);
423 *bpp = bp;
424 }
425 if (blknop != NULL) {
426 *blknop = bno;
427 }
428 return (0);
429 }
430 /*
431 * Allocate a new disk location.
432 */
433 if (bpref >= fs->fs_size)
434 bpref = 0;
435 switch ((int)fs->fs_optim) {
436 case FS_OPTSPACE:
437 /*
438 * Allocate an exact sized fragment. Although this makes
439 * best use of space, we will waste time relocating it if
440 * the file continues to grow. If the fragmentation is
441 * less than half of the minimum free reserve, we choose
442 * to begin optimizing for time.
443 */
444 request = nsize;
445 if (fs->fs_minfree < 5 ||
446 fs->fs_cstotal.cs_nffree >
447 fs->fs_dsize * fs->fs_minfree / (2 * 100))
448 break;
449
450 if (ffs_log_changeopt) {
451 log(LOG_NOTICE,
452 "%s: optimization changed from SPACE to TIME\n",
453 fs->fs_fsmnt);
454 }
455
456 fs->fs_optim = FS_OPTTIME;
457 break;
458 case FS_OPTTIME:
459 /*
460 * At this point we have discovered a file that is trying to
461 * grow a small fragment to a larger fragment. To save time,
462 * we allocate a full sized block, then free the unused portion.
463 * If the file continues to grow, the `ffs_fragextend' call
464 * above will be able to grow it in place without further
465 * copying. If aberrant programs cause disk fragmentation to
466 * grow within 2% of the free reserve, we choose to begin
467 * optimizing for space.
468 */
469 request = fs->fs_bsize;
470 if (fs->fs_cstotal.cs_nffree <
471 fs->fs_dsize * (fs->fs_minfree - 2) / 100)
472 break;
473
474 if (ffs_log_changeopt) {
475 log(LOG_NOTICE,
476 "%s: optimization changed from TIME to SPACE\n",
477 fs->fs_fsmnt);
478 }
479
480 fs->fs_optim = FS_OPTSPACE;
481 break;
482 default:
483 panic("%s: bad optim: dev = 0x%llx, optim = %d, fs = %s",
484 __func__, (unsigned long long)ip->i_dev, fs->fs_optim,
485 fs->fs_fsmnt);
486 /* NOTREACHED */
487 }
488 bno = ffs_hashalloc(ip, cg, bpref, request, nsize, 0, ffs_alloccg);
489 if (bno > 0) {
490 /*
491 * Use forced deallocation registration, we can't handle
492 * failure here. This is safe, as this place is ever hit
493 * maximum once per write operation, when fragment is extended
494 * to longer fragment, or a full block.
495 */
496 if ((ip->i_ump->um_mountp->mnt_wapbl) &&
497 (ITOV(ip)->v_type != VREG)) {
498 /* this should never fail */
499 error = UFS_WAPBL_REGISTER_DEALLOCATION_FORCE(
500 ip->i_ump->um_mountp, FFS_FSBTODB(fs, bprev),
501 osize);
502 if (error)
503 panic("ffs_realloccg: dealloc registration failed");
504 } else {
505 ffs_blkfree(fs, ip->i_devvp, bprev, (long)osize,
506 ip->i_number);
507 }
508 DIP_ADD(ip, blocks, btodb(nsize - osize));
509 if (flags & IO_EXT)
510 ip->i_flag |= IN_CHANGE;
511 else
512 ip->i_flag |= IN_CHANGE | IN_UPDATE;
513 if (bpp != NULL) {
514 bp->b_blkno = FFS_FSBTODB(fs, bno);
515 allocbuf(bp, nsize, 1);
516 memset((char *)bp->b_data + osize, 0, (u_int)nsize - osize);
517 mutex_enter(bp->b_objlock);
518 KASSERT(!cv_has_waiters(&bp->b_done));
519 bp->b_oflags |= BO_DONE;
520 mutex_exit(bp->b_objlock);
521 *bpp = bp;
522 }
523 if (blknop != NULL) {
524 *blknop = bno;
525 }
526 return (0);
527 }
528 mutex_exit(&ump->um_lock);
529
530 #if defined(QUOTA) || defined(QUOTA2)
531 /*
532 * Restore user's disk quota because allocation failed.
533 */
534 (void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
535 #endif
536 if (bpp != NULL) {
537 brelse(bp, 0);
538 }
539
540 nospace:
541 /*
542 * no space available
543 */
544 ffs_fserr(fs, cred, "file system full");
545 uprintf("\n%s: write failed, file system is full\n", fs->fs_fsmnt);
546 return (ENOSPC);
547 }
548
549 /*
550 * Allocate an inode in the file system.
551 *
552 * If allocating a directory, use ffs_dirpref to select the inode.
553 * If allocating in a directory, the following hierarchy is followed:
554 * 1) allocate the preferred inode.
555 * 2) allocate an inode in the same cylinder group.
556 * 3) quadradically rehash into other cylinder groups, until an
557 * available inode is located.
558 * If no inode preference is given the following hierarchy is used
559 * to allocate an inode:
560 * 1) allocate an inode in cylinder group 0.
561 * 2) quadradically rehash into other cylinder groups, until an
562 * available inode is located.
563 *
564 * => um_lock not held upon entry or return
565 */
566 int
567 ffs_valloc(struct vnode *pvp, int mode, kauth_cred_t cred, ino_t *inop)
568 {
569 struct ufsmount *ump;
570 struct inode *pip;
571 struct fs *fs;
572 ino_t ino, ipref;
573 int cg, error;
574
575 UFS_WAPBL_JUNLOCK_ASSERT(pvp->v_mount);
576
577 pip = VTOI(pvp);
578 fs = pip->i_fs;
579 ump = pip->i_ump;
580
581 error = UFS_WAPBL_BEGIN(pvp->v_mount);
582 if (error) {
583 return error;
584 }
585 mutex_enter(&ump->um_lock);
586 if (fs->fs_cstotal.cs_nifree == 0)
587 goto noinodes;
588
589 if ((mode & IFMT) == IFDIR)
590 ipref = ffs_dirpref(pip);
591 else
592 ipref = pip->i_number;
593 if (ipref >= fs->fs_ncg * fs->fs_ipg)
594 ipref = 0;
595 cg = ino_to_cg(fs, ipref);
596 /*
597 * Track number of dirs created one after another
598 * in a same cg without intervening by files.
599 */
600 if ((mode & IFMT) == IFDIR) {
601 if (fs->fs_contigdirs[cg] < 255)
602 fs->fs_contigdirs[cg]++;
603 } else {
604 if (fs->fs_contigdirs[cg] > 0)
605 fs->fs_contigdirs[cg]--;
606 }
607 ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0, 0, ffs_nodealloccg);
608 if (ino == 0)
609 goto noinodes;
610 UFS_WAPBL_END(pvp->v_mount);
611 *inop = ino;
612 return 0;
613
614 noinodes:
615 mutex_exit(&ump->um_lock);
616 UFS_WAPBL_END(pvp->v_mount);
617 ffs_fserr(fs, cred, "out of inodes");
618 uprintf("\n%s: create/symlink failed, no inodes free\n", fs->fs_fsmnt);
619 return ENOSPC;
620 }
621
622 /*
623 * Find a cylinder group in which to place a directory.
624 *
625 * The policy implemented by this algorithm is to allocate a
626 * directory inode in the same cylinder group as its parent
627 * directory, but also to reserve space for its files inodes
628 * and data. Restrict the number of directories which may be
629 * allocated one after another in the same cylinder group
630 * without intervening allocation of files.
631 *
632 * If we allocate a first level directory then force allocation
633 * in another cylinder group.
634 */
635 static ino_t
636 ffs_dirpref(struct inode *pip)
637 {
638 register struct fs *fs;
639 int cg, prefcg;
640 int64_t dirsize, cgsize, curdsz;
641 int avgifree, avgbfree, avgndir;
642 int minifree, minbfree, maxndir;
643 int mincg, minndir;
644 int maxcontigdirs;
645
646 KASSERT(mutex_owned(&pip->i_ump->um_lock));
647
648 fs = pip->i_fs;
649
650 avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
651 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
652 avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
653
654 /*
655 * Force allocation in another cg if creating a first level dir.
656 */
657 if (ITOV(pip)->v_vflag & VV_ROOT) {
658 prefcg = cprng_fast32() % fs->fs_ncg;
659 mincg = prefcg;
660 minndir = fs->fs_ipg;
661 for (cg = prefcg; cg < fs->fs_ncg; cg++)
662 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
663 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
664 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
665 mincg = cg;
666 minndir = fs->fs_cs(fs, cg).cs_ndir;
667 }
668 for (cg = 0; cg < prefcg; cg++)
669 if (fs->fs_cs(fs, cg).cs_ndir < minndir &&
670 fs->fs_cs(fs, cg).cs_nifree >= avgifree &&
671 fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
672 mincg = cg;
673 minndir = fs->fs_cs(fs, cg).cs_ndir;
674 }
675 return ((ino_t)(fs->fs_ipg * mincg));
676 }
677
678 /*
679 * Count various limits which used for
680 * optimal allocation of a directory inode.
681 * Try cylinder groups with >75% avgifree and avgbfree.
682 * Avoid cylinder groups with no free blocks or inodes as that
683 * triggers an I/O-expensive cylinder group scan.
684 */
685 maxndir = uimin(avgndir + fs->fs_ipg / 16, fs->fs_ipg);
686 minifree = avgifree - avgifree / 4;
687 if (minifree < 1)
688 minifree = 1;
689 minbfree = avgbfree - avgbfree / 4;
690 if (minbfree < 1)
691 minbfree = 1;
692 cgsize = (int64_t)fs->fs_fsize * fs->fs_fpg;
693 dirsize = (int64_t)fs->fs_avgfilesize * fs->fs_avgfpdir;
694 if (avgndir != 0) {
695 curdsz = (cgsize - (int64_t)avgbfree * fs->fs_bsize) / avgndir;
696 if (dirsize < curdsz)
697 dirsize = curdsz;
698 }
699 if (cgsize < dirsize * 255)
700 maxcontigdirs = (avgbfree * fs->fs_bsize) / dirsize;
701 else
702 maxcontigdirs = 255;
703 if (fs->fs_avgfpdir > 0)
704 maxcontigdirs = uimin(maxcontigdirs,
705 fs->fs_ipg / fs->fs_avgfpdir);
706 if (maxcontigdirs == 0)
707 maxcontigdirs = 1;
708
709 /*
710 * Limit number of dirs in one cg and reserve space for
711 * regular files, but only if we have no deficit in
712 * inodes or space.
713 */
714 prefcg = ino_to_cg(fs, pip->i_number);
715 for (cg = prefcg; cg < fs->fs_ncg; cg++)
716 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
717 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
718 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
719 if (fs->fs_contigdirs[cg] < maxcontigdirs)
720 return ((ino_t)(fs->fs_ipg * cg));
721 }
722 for (cg = 0; cg < prefcg; cg++)
723 if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
724 fs->fs_cs(fs, cg).cs_nifree >= minifree &&
725 fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
726 if (fs->fs_contigdirs[cg] < maxcontigdirs)
727 return ((ino_t)(fs->fs_ipg * cg));
728 }
729 /*
730 * This is a backstop when we are deficient in space.
731 */
732 for (cg = prefcg; cg < fs->fs_ncg; cg++)
733 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
734 return ((ino_t)(fs->fs_ipg * cg));
735 for (cg = 0; cg < prefcg; cg++)
736 if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
737 break;
738 return ((ino_t)(fs->fs_ipg * cg));
739 }
740
741 /*
742 * Select the desired position for the next block in a file. The file is
743 * logically divided into sections. The first section is composed of the
744 * direct blocks. Each additional section contains fs_maxbpg blocks.
745 *
746 * If no blocks have been allocated in the first section, the policy is to
747 * request a block in the same cylinder group as the inode that describes
748 * the file. If no blocks have been allocated in any other section, the
749 * policy is to place the section in a cylinder group with a greater than
750 * average number of free blocks. An appropriate cylinder group is found
751 * by using a rotor that sweeps the cylinder groups. When a new group of
752 * blocks is needed, the sweep begins in the cylinder group following the
753 * cylinder group from which the previous allocation was made. The sweep
754 * continues until a cylinder group with greater than the average number
755 * of free blocks is found. If the allocation is for the first block in an
756 * indirect block, the information on the previous allocation is unavailable;
757 * here a best guess is made based upon the logical block number being
758 * allocated.
759 *
760 * If a section is already partially allocated, the policy is to
761 * contiguously allocate fs_maxcontig blocks. The end of one of these
762 * contiguous blocks and the beginning of the next is laid out
763 * contigously if possible.
764 *
765 * => um_lock held on entry and exit
766 */
767 daddr_t
768 ffs_blkpref_ufs1(struct inode *ip, daddr_t lbn, int indx, int flags,
769 int32_t *bap /* XXX ondisk32 */)
770 {
771 struct fs *fs;
772 int cg;
773 int avgbfree, startcg;
774
775 KASSERT(mutex_owned(&ip->i_ump->um_lock));
776
777 fs = ip->i_fs;
778
779 /*
780 * If allocating a contiguous file with B_CONTIG, use the hints
781 * in the inode extentions to return the desired block.
782 *
783 * For metadata (indirect blocks) return the address of where
784 * the first indirect block resides - we'll scan for the next
785 * available slot if we need to allocate more than one indirect
786 * block. For data, return the address of the actual block
787 * relative to the address of the first data block.
788 */
789 if (flags & B_CONTIG) {
790 KASSERT(ip->i_ffs_first_data_blk != 0);
791 KASSERT(ip->i_ffs_first_indir_blk != 0);
792 if (flags & B_METAONLY)
793 return ip->i_ffs_first_indir_blk;
794 else
795 return ip->i_ffs_first_data_blk + ffs_blkstofrags(fs, lbn);
796 }
797
798 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
799 if (lbn < UFS_NDADDR + FFS_NINDIR(fs)) {
800 cg = ino_to_cg(fs, ip->i_number);
801 return (cgbase(fs, cg) + fs->fs_frag);
802 }
803 /*
804 * Find a cylinder with greater than average number of
805 * unused data blocks.
806 */
807 if (indx == 0 || bap[indx - 1] == 0)
808 startcg =
809 ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
810 else
811 startcg = dtog(fs,
812 ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
813 startcg %= fs->fs_ncg;
814 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
815 for (cg = startcg; cg < fs->fs_ncg; cg++)
816 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
817 return (cgbase(fs, cg) + fs->fs_frag);
818 }
819 for (cg = 0; cg < startcg; cg++)
820 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
821 return (cgbase(fs, cg) + fs->fs_frag);
822 }
823 return (0);
824 }
825 /*
826 * We just always try to lay things out contiguously.
827 */
828 return ufs_rw32(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
829 }
830
831 daddr_t
832 ffs_blkpref_ufs2(struct inode *ip, daddr_t lbn, int indx, int flags,
833 int64_t *bap)
834 {
835 struct fs *fs;
836 int cg;
837 int avgbfree, startcg;
838
839 KASSERT(mutex_owned(&ip->i_ump->um_lock));
840
841 fs = ip->i_fs;
842
843 /*
844 * If allocating a contiguous file with B_CONTIG, use the hints
845 * in the inode extentions to return the desired block.
846 *
847 * For metadata (indirect blocks) return the address of where
848 * the first indirect block resides - we'll scan for the next
849 * available slot if we need to allocate more than one indirect
850 * block. For data, return the address of the actual block
851 * relative to the address of the first data block.
852 */
853 if (flags & B_CONTIG) {
854 KASSERT(ip->i_ffs_first_data_blk != 0);
855 KASSERT(ip->i_ffs_first_indir_blk != 0);
856 if (flags & B_METAONLY)
857 return ip->i_ffs_first_indir_blk;
858 else
859 return ip->i_ffs_first_data_blk + ffs_blkstofrags(fs, lbn);
860 }
861
862 if (indx % fs->fs_maxbpg == 0 || bap[indx - 1] == 0) {
863 if (lbn < UFS_NDADDR + FFS_NINDIR(fs)) {
864 cg = ino_to_cg(fs, ip->i_number);
865 return (cgbase(fs, cg) + fs->fs_frag);
866 }
867 /*
868 * Find a cylinder with greater than average number of
869 * unused data blocks.
870 */
871 if (indx == 0 || bap[indx - 1] == 0)
872 startcg =
873 ino_to_cg(fs, ip->i_number) + lbn / fs->fs_maxbpg;
874 else
875 startcg = dtog(fs,
876 ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + 1);
877 startcg %= fs->fs_ncg;
878 avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
879 for (cg = startcg; cg < fs->fs_ncg; cg++)
880 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
881 return (cgbase(fs, cg) + fs->fs_frag);
882 }
883 for (cg = 0; cg < startcg; cg++)
884 if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
885 return (cgbase(fs, cg) + fs->fs_frag);
886 }
887 return (0);
888 }
889 /*
890 * We just always try to lay things out contiguously.
891 */
892 return ufs_rw64(bap[indx - 1], UFS_FSNEEDSWAP(fs)) + fs->fs_frag;
893 }
894
895
896 /*
897 * Implement the cylinder overflow algorithm.
898 *
899 * The policy implemented by this algorithm is:
900 * 1) allocate the block in its requested cylinder group.
901 * 2) quadradically rehash on the cylinder group number.
902 * 3) brute force search for a free block.
903 *
904 * => called with um_lock held
905 * => returns with um_lock released on success, held on failure
906 * (*allocator releases lock on success, retains lock on failure)
907 */
908 /*VARARGS5*/
909 static daddr_t
910 ffs_hashalloc(struct inode *ip, int cg, daddr_t pref,
911 int size /* size for data blocks, mode for inodes */,
912 int realsize,
913 int flags,
914 daddr_t (*allocator)(struct inode *, int, daddr_t, int, int, int))
915 {
916 struct fs *fs;
917 daddr_t result;
918 int i, icg = cg;
919
920 fs = ip->i_fs;
921 /*
922 * 1: preferred cylinder group
923 */
924 result = (*allocator)(ip, cg, pref, size, realsize, flags);
925 if (result)
926 return (result);
927
928 if (flags & B_CONTIG)
929 return (result);
930 /*
931 * 2: quadratic rehash
932 */
933 for (i = 1; i < fs->fs_ncg; i *= 2) {
934 cg += i;
935 if (cg >= fs->fs_ncg)
936 cg -= fs->fs_ncg;
937 result = (*allocator)(ip, cg, 0, size, realsize, flags);
938 if (result)
939 return (result);
940 }
941 /*
942 * 3: brute force search
943 * Note that we start at i == 2, since 0 was checked initially,
944 * and 1 is always checked in the quadratic rehash.
945 */
946 cg = (icg + 2) % fs->fs_ncg;
947 for (i = 2; i < fs->fs_ncg; i++) {
948 result = (*allocator)(ip, cg, 0, size, realsize, flags);
949 if (result)
950 return (result);
951 cg++;
952 if (cg == fs->fs_ncg)
953 cg = 0;
954 }
955 return (0);
956 }
957
958 /*
959 * Determine whether a fragment can be extended.
960 *
961 * Check to see if the necessary fragments are available, and
962 * if they are, allocate them.
963 *
964 * => called with um_lock held
965 * => returns with um_lock released on success, held on failure
966 */
967 static daddr_t
968 ffs_fragextend(struct inode *ip, int cg, daddr_t bprev, int osize, int nsize)
969 {
970 struct ufsmount *ump;
971 struct fs *fs;
972 struct cg *cgp;
973 struct buf *bp;
974 daddr_t bno;
975 int frags, bbase;
976 int i, error;
977 u_int8_t *blksfree;
978
979 fs = ip->i_fs;
980 ump = ip->i_ump;
981
982 KASSERT(mutex_owned(&ump->um_lock));
983
984 if (fs->fs_cs(fs, cg).cs_nffree < ffs_numfrags(fs, nsize - osize))
985 return (0);
986 frags = ffs_numfrags(fs, nsize);
987 bbase = ffs_fragnum(fs, bprev);
988 if (bbase > ffs_fragnum(fs, (bprev + frags - 1))) {
989 /* cannot extend across a block boundary */
990 return (0);
991 }
992 mutex_exit(&ump->um_lock);
993 error = bread(ip->i_devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
994 (int)fs->fs_cgsize, B_MODIFY, &bp);
995 if (error)
996 goto fail;
997 cgp = (struct cg *)bp->b_data;
998 if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs)))
999 goto fail;
1000 cgp->cg_old_time = ufs_rw32(time_second, UFS_FSNEEDSWAP(fs));
1001 if ((fs->fs_magic != FS_UFS1_MAGIC) ||
1002 (fs->fs_old_flags & FS_FLAGS_UPDATED))
1003 cgp->cg_time = ufs_rw64(time_second, UFS_FSNEEDSWAP(fs));
1004 bno = dtogd(fs, bprev);
1005 blksfree = cg_blksfree(cgp, UFS_FSNEEDSWAP(fs));
1006 for (i = ffs_numfrags(fs, osize); i < frags; i++)
1007 if (isclr(blksfree, bno + i))
1008 goto fail;
1009 /*
1010 * the current fragment can be extended
1011 * deduct the count on fragment being extended into
1012 * increase the count on the remaining fragment (if any)
1013 * allocate the extended piece
1014 */
1015 for (i = frags; i < fs->fs_frag - bbase; i++)
1016 if (isclr(blksfree, bno + i))
1017 break;
1018 ufs_add32(cgp->cg_frsum[i - ffs_numfrags(fs, osize)], -1, UFS_FSNEEDSWAP(fs));
1019 if (i != frags)
1020 ufs_add32(cgp->cg_frsum[i - frags], 1, UFS_FSNEEDSWAP(fs));
1021 mutex_enter(&ump->um_lock);
1022 for (i = ffs_numfrags(fs, osize); i < frags; i++) {
1023 clrbit(blksfree, bno + i);
1024 ufs_add32(cgp->cg_cs.cs_nffree, -1, UFS_FSNEEDSWAP(fs));
1025 fs->fs_cstotal.cs_nffree--;
1026 fs->fs_cs(fs, cg).cs_nffree--;
1027 }
1028 fs->fs_fmod = 1;
1029 ACTIVECG_CLR(fs, cg);
1030 mutex_exit(&ump->um_lock);
1031 bdwrite(bp);
1032 return (bprev);
1033
1034 fail:
1035 if (bp != NULL)
1036 brelse(bp, 0);
1037 mutex_enter(&ump->um_lock);
1038 return (0);
1039 }
1040
1041 /*
1042 * Determine whether a block can be allocated.
1043 *
1044 * Check to see if a block of the appropriate size is available,
1045 * and if it is, allocate it.
1046 */
1047 static daddr_t
1048 ffs_alloccg(struct inode *ip, int cg, daddr_t bpref, int size, int realsize,
1049 int flags)
1050 {
1051 struct ufsmount *ump;
1052 struct fs *fs = ip->i_fs;
1053 struct cg *cgp;
1054 struct buf *bp;
1055 int32_t bno;
1056 daddr_t blkno;
1057 int error, frags, allocsiz, i;
1058 u_int8_t *blksfree;
1059 const int needswap = UFS_FSNEEDSWAP(fs);
1060
1061 ump = ip->i_ump;
1062
1063 KASSERT(mutex_owned(&ump->um_lock));
1064
1065 if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
1066 return (0);
1067 mutex_exit(&ump->um_lock);
1068 error = bread(ip->i_devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
1069 (int)fs->fs_cgsize, B_MODIFY, &bp);
1070 if (error)
1071 goto fail;
1072 cgp = (struct cg *)bp->b_data;
1073 if (!cg_chkmagic(cgp, needswap) ||
1074 (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize))
1075 goto fail;
1076 cgp->cg_old_time = ufs_rw32(time_second, needswap);
1077 if ((fs->fs_magic != FS_UFS1_MAGIC) ||
1078 (fs->fs_old_flags & FS_FLAGS_UPDATED))
1079 cgp->cg_time = ufs_rw64(time_second, needswap);
1080 if (size == fs->fs_bsize) {
1081 mutex_enter(&ump->um_lock);
1082 blkno = ffs_alloccgblk(ip, bp, bpref, realsize, flags);
1083 ACTIVECG_CLR(fs, cg);
1084 mutex_exit(&ump->um_lock);
1085
1086 /*
1087 * If actually needed size is lower, free the extra blocks now.
1088 * This is safe to call here, there is no outside reference
1089 * to this block yet. It is not necessary to keep um_lock
1090 * locked.
1091 */
1092 if (realsize != 0 && realsize < size) {
1093 ffs_blkfree_common(ip->i_ump, ip->i_fs,
1094 ip->i_devvp->v_rdev,
1095 bp, blkno + ffs_numfrags(fs, realsize),
1096 (long)(size - realsize), false);
1097 }
1098
1099 bdwrite(bp);
1100 return (blkno);
1101 }
1102 /*
1103 * check to see if any fragments are already available
1104 * allocsiz is the size which will be allocated, hacking
1105 * it down to a smaller size if necessary
1106 */
1107 blksfree = cg_blksfree(cgp, needswap);
1108 frags = ffs_numfrags(fs, size);
1109 for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1110 if (cgp->cg_frsum[allocsiz] != 0)
1111 break;
1112 if (allocsiz == fs->fs_frag) {
1113 /*
1114 * no fragments were available, so a block will be
1115 * allocated, and hacked up
1116 */
1117 if (cgp->cg_cs.cs_nbfree == 0)
1118 goto fail;
1119 mutex_enter(&ump->um_lock);
1120 blkno = ffs_alloccgblk(ip, bp, bpref, realsize, flags);
1121 bno = dtogd(fs, blkno);
1122 for (i = frags; i < fs->fs_frag; i++)
1123 setbit(blksfree, bno + i);
1124 i = fs->fs_frag - frags;
1125 ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
1126 fs->fs_cstotal.cs_nffree += i;
1127 fs->fs_cs(fs, cg).cs_nffree += i;
1128 fs->fs_fmod = 1;
1129 ufs_add32(cgp->cg_frsum[i], 1, needswap);
1130 ACTIVECG_CLR(fs, cg);
1131 mutex_exit(&ump->um_lock);
1132 bdwrite(bp);
1133 return (blkno);
1134 }
1135 bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
1136 #if 0
1137 /*
1138 * XXX fvdl mapsearch will panic, and never return -1
1139 * also: returning NULL as daddr_t ?
1140 */
1141 if (bno < 0)
1142 goto fail;
1143 #endif
1144 for (i = 0; i < frags; i++)
1145 clrbit(blksfree, bno + i);
1146 mutex_enter(&ump->um_lock);
1147 ufs_add32(cgp->cg_cs.cs_nffree, -frags, needswap);
1148 fs->fs_cstotal.cs_nffree -= frags;
1149 fs->fs_cs(fs, cg).cs_nffree -= frags;
1150 fs->fs_fmod = 1;
1151 ufs_add32(cgp->cg_frsum[allocsiz], -1, needswap);
1152 if (frags != allocsiz)
1153 ufs_add32(cgp->cg_frsum[allocsiz - frags], 1, needswap);
1154 blkno = cgbase(fs, cg) + bno;
1155 ACTIVECG_CLR(fs, cg);
1156 mutex_exit(&ump->um_lock);
1157 bdwrite(bp);
1158 return blkno;
1159
1160 fail:
1161 if (bp != NULL)
1162 brelse(bp, 0);
1163 mutex_enter(&ump->um_lock);
1164 return (0);
1165 }
1166
1167 /*
1168 * Allocate a block in a cylinder group.
1169 *
1170 * This algorithm implements the following policy:
1171 * 1) allocate the requested block.
1172 * 2) allocate a rotationally optimal block in the same cylinder.
1173 * 3) allocate the next available block on the block rotor for the
1174 * specified cylinder group.
1175 * Note that this routine only allocates fs_bsize blocks; these
1176 * blocks may be fragmented by the routine that allocates them.
1177 */
1178 static daddr_t
1179 ffs_alloccgblk(struct inode *ip, struct buf *bp, daddr_t bpref, int realsize,
1180 int flags)
1181 {
1182 struct fs *fs = ip->i_fs;
1183 struct cg *cgp;
1184 int cg;
1185 daddr_t blkno;
1186 int32_t bno;
1187 u_int8_t *blksfree;
1188 const int needswap = UFS_FSNEEDSWAP(fs);
1189
1190 KASSERT(mutex_owned(&ip->i_ump->um_lock));
1191
1192 cgp = (struct cg *)bp->b_data;
1193 blksfree = cg_blksfree(cgp, needswap);
1194 if (bpref == 0 || dtog(fs, bpref) != ufs_rw32(cgp->cg_cgx, needswap)) {
1195 bpref = ufs_rw32(cgp->cg_rotor, needswap);
1196 } else {
1197 bpref = ffs_blknum(fs, bpref);
1198 bno = dtogd(fs, bpref);
1199 /*
1200 * if the requested block is available, use it
1201 */
1202 if (ffs_isblock(fs, blksfree, ffs_fragstoblks(fs, bno)))
1203 goto gotit;
1204 /*
1205 * if the requested data block isn't available and we are
1206 * trying to allocate a contiguous file, return an error.
1207 */
1208 if ((flags & (B_CONTIG | B_METAONLY)) == B_CONTIG)
1209 return (0);
1210 }
1211
1212 /*
1213 * Take the next available block in this cylinder group.
1214 */
1215 bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1216 #if 0
1217 /*
1218 * XXX jdolecek ffs_mapsearch() succeeds or panics
1219 */
1220 if (bno < 0)
1221 return (0);
1222 #endif
1223 cgp->cg_rotor = ufs_rw32(bno, needswap);
1224 gotit:
1225 blkno = ffs_fragstoblks(fs, bno);
1226 ffs_clrblock(fs, blksfree, blkno);
1227 ffs_clusteracct(fs, cgp, blkno, -1);
1228 ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
1229 fs->fs_cstotal.cs_nbfree--;
1230 fs->fs_cs(fs, ufs_rw32(cgp->cg_cgx, needswap)).cs_nbfree--;
1231 if ((fs->fs_magic == FS_UFS1_MAGIC) &&
1232 ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
1233 int cylno;
1234 cylno = old_cbtocylno(fs, bno);
1235 KASSERT(cylno >= 0);
1236 KASSERT(cylno < fs->fs_old_ncyl);
1237 KASSERT(old_cbtorpos(fs, bno) >= 0);
1238 KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, bno) < fs->fs_old_nrpos);
1239 ufs_add16(old_cg_blks(fs, cgp, cylno, needswap)[old_cbtorpos(fs, bno)], -1,
1240 needswap);
1241 ufs_add32(old_cg_blktot(cgp, needswap)[cylno], -1, needswap);
1242 }
1243 fs->fs_fmod = 1;
1244 cg = ufs_rw32(cgp->cg_cgx, needswap);
1245 blkno = cgbase(fs, cg) + bno;
1246 return (blkno);
1247 }
1248
1249 /*
1250 * Determine whether an inode can be allocated.
1251 *
1252 * Check to see if an inode is available, and if it is,
1253 * allocate it using the following policy:
1254 * 1) allocate the requested inode.
1255 * 2) allocate the next available inode after the requested
1256 * inode in the specified cylinder group.
1257 */
1258 static daddr_t
1259 ffs_nodealloccg(struct inode *ip, int cg, daddr_t ipref, int mode, int realsize,
1260 int flags)
1261 {
1262 struct ufsmount *ump = ip->i_ump;
1263 struct fs *fs = ip->i_fs;
1264 struct cg *cgp;
1265 struct buf *bp, *ibp;
1266 u_int8_t *inosused;
1267 int error, start, len, loc, map, i;
1268 int32_t initediblk, maxiblk, irotor;
1269 daddr_t nalloc;
1270 struct ufs2_dinode *dp2;
1271 const int needswap = UFS_FSNEEDSWAP(fs);
1272
1273 KASSERT(mutex_owned(&ump->um_lock));
1274 UFS_WAPBL_JLOCK_ASSERT(ip->i_ump->um_mountp);
1275
1276 if (fs->fs_cs(fs, cg).cs_nifree == 0)
1277 return (0);
1278 mutex_exit(&ump->um_lock);
1279 ibp = NULL;
1280 if (fs->fs_magic == FS_UFS2_MAGIC) {
1281 initediblk = -1;
1282 } else {
1283 initediblk = fs->fs_ipg;
1284 }
1285 maxiblk = initediblk;
1286
1287 retry:
1288 error = bread(ip->i_devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
1289 (int)fs->fs_cgsize, B_MODIFY, &bp);
1290 if (error)
1291 goto fail;
1292 cgp = (struct cg *)bp->b_data;
1293 if (!cg_chkmagic(cgp, needswap) || cgp->cg_cs.cs_nifree == 0)
1294 goto fail;
1295
1296 if (ibp != NULL &&
1297 initediblk != ufs_rw32(cgp->cg_initediblk, needswap)) {
1298 /* Another thread allocated more inodes so we retry the test. */
1299 brelse(ibp, 0);
1300 ibp = NULL;
1301 }
1302 /*
1303 * Check to see if we need to initialize more inodes.
1304 */
1305 if (fs->fs_magic == FS_UFS2_MAGIC && ibp == NULL) {
1306 initediblk = ufs_rw32(cgp->cg_initediblk, needswap);
1307 maxiblk = initediblk;
1308 nalloc = fs->fs_ipg - ufs_rw32(cgp->cg_cs.cs_nifree, needswap);
1309 if (nalloc + FFS_INOPB(fs) > initediblk &&
1310 initediblk < ufs_rw32(cgp->cg_niblk, needswap)) {
1311 /*
1312 * We have to release the cg buffer here to prevent
1313 * a deadlock when reading the inode block will
1314 * run a copy-on-write that might use this cg.
1315 */
1316 brelse(bp, 0);
1317 bp = NULL;
1318 error = ffs_getblk(ip->i_devvp, FFS_FSBTODB(fs,
1319 ino_to_fsba(fs, cg * fs->fs_ipg + initediblk)),
1320 FFS_NOBLK, fs->fs_bsize, false, &ibp);
1321 if (error)
1322 goto fail;
1323
1324 maxiblk += FFS_INOPB(fs);
1325
1326 goto retry;
1327 }
1328 }
1329
1330 cgp->cg_old_time = ufs_rw32(time_second, needswap);
1331 if ((fs->fs_magic != FS_UFS1_MAGIC) ||
1332 (fs->fs_old_flags & FS_FLAGS_UPDATED))
1333 cgp->cg_time = ufs_rw64(time_second, needswap);
1334 inosused = cg_inosused(cgp, needswap);
1335
1336 if (ipref) {
1337 ipref %= fs->fs_ipg;
1338 /* safeguard to stay in (to be) allocated range */
1339 if (ipref < maxiblk && isclr(inosused, ipref))
1340 goto gotit;
1341 }
1342
1343 irotor = ufs_rw32(cgp->cg_irotor, needswap);
1344
1345 KASSERTMSG(irotor < initediblk, "%s: allocation botch: cg=%d, irotor %d"
1346 " out of bounds, initediblk=%d",
1347 __func__, cg, irotor, initediblk);
1348
1349 start = irotor / NBBY;
1350 len = howmany(maxiblk - irotor, NBBY);
1351 loc = skpc(0xff, len, &inosused[start]);
1352 if (loc == 0) {
1353 len = start + 1;
1354 start = 0;
1355 loc = skpc(0xff, len, &inosused[0]);
1356 if (loc == 0) {
1357 panic("%s: map corrupted: cg=%d, irotor=%d, fs=%s",
1358 __func__, cg, ufs_rw32(cgp->cg_irotor, needswap),
1359 fs->fs_fsmnt);
1360 /* NOTREACHED */
1361 }
1362 }
1363 i = start + len - loc;
1364 map = inosused[i] ^ 0xff;
1365 if (map == 0) {
1366 panic("%s: block not in map: fs=%s", __func__, fs->fs_fsmnt);
1367 }
1368
1369 ipref = i * NBBY + ffs(map) - 1;
1370
1371 cgp->cg_irotor = ufs_rw32(ipref, needswap);
1372
1373 gotit:
1374 KASSERTMSG(ipref < maxiblk, "%s: allocation botch: cg=%d attempt to "
1375 "allocate inode index %d beyond max allocated index %d"
1376 " of %d inodes/cg",
1377 __func__, cg, (int)ipref, maxiblk, cgp->cg_niblk);
1378
1379 UFS_WAPBL_REGISTER_INODE(ip->i_ump->um_mountp, cg * fs->fs_ipg + ipref,
1380 mode);
1381 /*
1382 * Check to see if we need to initialize more inodes.
1383 */
1384 if (ibp != NULL) {
1385 KASSERT(initediblk == ufs_rw32(cgp->cg_initediblk, needswap));
1386 memset(ibp->b_data, 0, fs->fs_bsize);
1387 dp2 = (struct ufs2_dinode *)(ibp->b_data);
1388 for (i = 0; i < FFS_INOPB(fs); i++) {
1389 /*
1390 * Don't bother to swap, it's supposed to be
1391 * random, after all.
1392 */
1393 dp2->di_gen = (cprng_fast32() & INT32_MAX) / 2 + 1;
1394 dp2++;
1395 }
1396 initediblk += FFS_INOPB(fs);
1397 cgp->cg_initediblk = ufs_rw32(initediblk, needswap);
1398 }
1399
1400 mutex_enter(&ump->um_lock);
1401 ACTIVECG_CLR(fs, cg);
1402 setbit(inosused, ipref);
1403 ufs_add32(cgp->cg_cs.cs_nifree, -1, needswap);
1404 fs->fs_cstotal.cs_nifree--;
1405 fs->fs_cs(fs, cg).cs_nifree--;
1406 fs->fs_fmod = 1;
1407 if ((mode & IFMT) == IFDIR) {
1408 ufs_add32(cgp->cg_cs.cs_ndir, 1, needswap);
1409 fs->fs_cstotal.cs_ndir++;
1410 fs->fs_cs(fs, cg).cs_ndir++;
1411 }
1412 mutex_exit(&ump->um_lock);
1413 if (ibp != NULL) {
1414 bwrite(ibp);
1415 bwrite(bp);
1416 } else
1417 bdwrite(bp);
1418 return (cg * fs->fs_ipg + ipref);
1419 fail:
1420 if (bp != NULL)
1421 brelse(bp, 0);
1422 if (ibp != NULL)
1423 brelse(ibp, 0);
1424 mutex_enter(&ump->um_lock);
1425 return (0);
1426 }
1427
1428 /*
1429 * Allocate a block or fragment.
1430 *
1431 * The specified block or fragment is removed from the
1432 * free map, possibly fragmenting a block in the process.
1433 *
1434 * This implementation should mirror fs_blkfree
1435 *
1436 * => um_lock not held on entry or exit
1437 */
1438 int
1439 ffs_blkalloc(struct inode *ip, daddr_t bno, long size)
1440 {
1441 int error;
1442
1443 error = ffs_check_bad_allocation(__func__, ip->i_fs, bno, size,
1444 ip->i_dev, ip->i_uid);
1445 if (error)
1446 return error;
1447
1448 return ffs_blkalloc_ump(ip->i_ump, bno, size);
1449 }
1450
1451 int
1452 ffs_blkalloc_ump(struct ufsmount *ump, daddr_t bno, long size)
1453 {
1454 struct fs *fs = ump->um_fs;
1455 struct cg *cgp;
1456 struct buf *bp;
1457 int32_t fragno, cgbno;
1458 int i, error, cg, blk, frags, bbase;
1459 u_int8_t *blksfree;
1460 const int needswap = UFS_FSNEEDSWAP(fs);
1461
1462 KASSERT((u_int)size <= fs->fs_bsize && ffs_fragoff(fs, size) == 0 &&
1463 ffs_fragnum(fs, bno) + ffs_numfrags(fs, size) <= fs->fs_frag);
1464 KASSERT(bno < fs->fs_size);
1465
1466 cg = dtog(fs, bno);
1467 error = bread(ump->um_devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
1468 (int)fs->fs_cgsize, B_MODIFY, &bp);
1469 if (error) {
1470 return error;
1471 }
1472 cgp = (struct cg *)bp->b_data;
1473 if (!cg_chkmagic(cgp, needswap)) {
1474 brelse(bp, 0);
1475 return EIO;
1476 }
1477 cgp->cg_old_time = ufs_rw32(time_second, needswap);
1478 cgp->cg_time = ufs_rw64(time_second, needswap);
1479 cgbno = dtogd(fs, bno);
1480 blksfree = cg_blksfree(cgp, needswap);
1481
1482 mutex_enter(&ump->um_lock);
1483 if (size == fs->fs_bsize) {
1484 fragno = ffs_fragstoblks(fs, cgbno);
1485 if (!ffs_isblock(fs, blksfree, fragno)) {
1486 mutex_exit(&ump->um_lock);
1487 brelse(bp, 0);
1488 return EBUSY;
1489 }
1490 ffs_clrblock(fs, blksfree, fragno);
1491 ffs_clusteracct(fs, cgp, fragno, -1);
1492 ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
1493 fs->fs_cstotal.cs_nbfree--;
1494 fs->fs_cs(fs, cg).cs_nbfree--;
1495 } else {
1496 bbase = cgbno - ffs_fragnum(fs, cgbno);
1497
1498 frags = ffs_numfrags(fs, size);
1499 for (i = 0; i < frags; i++) {
1500 if (isclr(blksfree, cgbno + i)) {
1501 mutex_exit(&ump->um_lock);
1502 brelse(bp, 0);
1503 return EBUSY;
1504 }
1505 }
1506 /*
1507 * if a complete block is being split, account for it
1508 */
1509 fragno = ffs_fragstoblks(fs, bbase);
1510 if (ffs_isblock(fs, blksfree, fragno)) {
1511 ufs_add32(cgp->cg_cs.cs_nffree, fs->fs_frag, needswap);
1512 fs->fs_cstotal.cs_nffree += fs->fs_frag;
1513 fs->fs_cs(fs, cg).cs_nffree += fs->fs_frag;
1514 ffs_clusteracct(fs, cgp, fragno, -1);
1515 ufs_add32(cgp->cg_cs.cs_nbfree, -1, needswap);
1516 fs->fs_cstotal.cs_nbfree--;
1517 fs->fs_cs(fs, cg).cs_nbfree--;
1518 }
1519 /*
1520 * decrement the counts associated with the old frags
1521 */
1522 blk = blkmap(fs, blksfree, bbase);
1523 ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
1524 /*
1525 * allocate the fragment
1526 */
1527 for (i = 0; i < frags; i++) {
1528 clrbit(blksfree, cgbno + i);
1529 }
1530 ufs_add32(cgp->cg_cs.cs_nffree, -i, needswap);
1531 fs->fs_cstotal.cs_nffree -= i;
1532 fs->fs_cs(fs, cg).cs_nffree -= i;
1533 /*
1534 * add back in counts associated with the new frags
1535 */
1536 blk = blkmap(fs, blksfree, bbase);
1537 ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
1538 }
1539 fs->fs_fmod = 1;
1540 ACTIVECG_CLR(fs, cg);
1541 mutex_exit(&ump->um_lock);
1542 bdwrite(bp);
1543 return 0;
1544 }
1545
1546 /*
1547 * Free a block or fragment.
1548 *
1549 * The specified block or fragment is placed back in the
1550 * free map. If a fragment is deallocated, a possible
1551 * block reassembly is checked.
1552 *
1553 * => um_lock not held on entry or exit
1554 */
1555 static void
1556 ffs_blkfree_cg(struct fs *fs, struct vnode *devvp, daddr_t bno, long size)
1557 {
1558 struct cg *cgp;
1559 struct buf *bp;
1560 struct ufsmount *ump;
1561 daddr_t cgblkno;
1562 int error, cg;
1563 dev_t dev;
1564 const bool devvp_is_snapshot = (devvp->v_type != VBLK);
1565 const int needswap = UFS_FSNEEDSWAP(fs);
1566
1567 KASSERT(!devvp_is_snapshot);
1568
1569 cg = dtog(fs, bno);
1570 dev = devvp->v_rdev;
1571 ump = VFSTOUFS(spec_node_getmountedfs(devvp));
1572 KASSERT(fs == ump->um_fs);
1573 cgblkno = FFS_FSBTODB(fs, cgtod(fs, cg));
1574
1575 error = bread(devvp, cgblkno, (int)fs->fs_cgsize,
1576 B_MODIFY, &bp);
1577 if (error) {
1578 return;
1579 }
1580 cgp = (struct cg *)bp->b_data;
1581 if (!cg_chkmagic(cgp, needswap)) {
1582 brelse(bp, 0);
1583 return;
1584 }
1585
1586 ffs_blkfree_common(ump, fs, dev, bp, bno, size, devvp_is_snapshot);
1587
1588 bdwrite(bp);
1589 }
1590
1591 struct discardopdata {
1592 struct work wk; /* must be first */
1593 struct vnode *devvp;
1594 daddr_t bno;
1595 long size;
1596 };
1597
1598 struct discarddata {
1599 struct fs *fs;
1600 struct discardopdata *entry;
1601 long maxsize;
1602 kmutex_t entrylk;
1603 struct workqueue *wq;
1604 int wqcnt, wqdraining;
1605 kmutex_t wqlk;
1606 kcondvar_t wqcv;
1607 /* timer for flush? */
1608 };
1609
1610 static void
1611 ffs_blkfree_td(struct fs *fs, struct discardopdata *td)
1612 {
1613 struct mount *mp = spec_node_getmountedfs(td->devvp);
1614 long todo;
1615 int error;
1616
1617 while (td->size) {
1618 todo = uimin(td->size,
1619 ffs_lfragtosize(fs, (fs->fs_frag - ffs_fragnum(fs, td->bno))));
1620 error = UFS_WAPBL_BEGIN(mp);
1621 if (error) {
1622 printf("ffs: failed to begin wapbl transaction"
1623 " for discard: %d\n", error);
1624 break;
1625 }
1626 ffs_blkfree_cg(fs, td->devvp, td->bno, todo);
1627 UFS_WAPBL_END(mp);
1628 td->bno += ffs_numfrags(fs, todo);
1629 td->size -= todo;
1630 }
1631 }
1632
1633 static void
1634 ffs_discardcb(struct work *wk, void *arg)
1635 {
1636 struct discardopdata *td = (void *)wk;
1637 struct discarddata *ts = arg;
1638 struct fs *fs = ts->fs;
1639 off_t start, len;
1640 #ifdef TRIMDEBUG
1641 int error;
1642 #endif
1643
1644 /* like FSBTODB but emits bytes; XXX move to fs.h */
1645 #ifndef FFS_FSBTOBYTES
1646 #define FFS_FSBTOBYTES(fs, b) ((b) << (fs)->fs_fshift)
1647 #endif
1648
1649 start = FFS_FSBTOBYTES(fs, td->bno);
1650 len = td->size;
1651 #ifdef TRIMDEBUG
1652 error =
1653 #endif
1654 VOP_FDISCARD(td->devvp, start, len);
1655 #ifdef TRIMDEBUG
1656 printf("trim(%" PRId64 ",%ld):%d\n", td->bno, td->size, error);
1657 #endif
1658
1659 ffs_blkfree_td(fs, td);
1660 kmem_free(td, sizeof(*td));
1661 mutex_enter(&ts->wqlk);
1662 ts->wqcnt--;
1663 if (ts->wqdraining && !ts->wqcnt)
1664 cv_signal(&ts->wqcv);
1665 mutex_exit(&ts->wqlk);
1666 }
1667
1668 void *
1669 ffs_discard_init(struct vnode *devvp, struct fs *fs)
1670 {
1671 struct discarddata *ts;
1672 int error;
1673
1674 ts = kmem_zalloc(sizeof (*ts), KM_SLEEP);
1675 error = workqueue_create(&ts->wq, "trimwq", ffs_discardcb, ts,
1676 PRI_USER, IPL_NONE, 0);
1677 if (error) {
1678 kmem_free(ts, sizeof (*ts));
1679 return NULL;
1680 }
1681 mutex_init(&ts->entrylk, MUTEX_DEFAULT, IPL_NONE);
1682 mutex_init(&ts->wqlk, MUTEX_DEFAULT, IPL_NONE);
1683 cv_init(&ts->wqcv, "trimwqcv");
1684 ts->maxsize = 100*1024; /* XXX */
1685 ts->fs = fs;
1686 return ts;
1687 }
1688
1689 void
1690 ffs_discard_finish(void *vts, int flags)
1691 {
1692 struct discarddata *ts = vts;
1693 struct discardopdata *td = NULL;
1694
1695 /* wait for workqueue to drain */
1696 mutex_enter(&ts->wqlk);
1697 if (ts->wqcnt) {
1698 ts->wqdraining = 1;
1699 cv_wait(&ts->wqcv, &ts->wqlk);
1700 }
1701 mutex_exit(&ts->wqlk);
1702
1703 mutex_enter(&ts->entrylk);
1704 if (ts->entry) {
1705 td = ts->entry;
1706 ts->entry = NULL;
1707 }
1708 mutex_exit(&ts->entrylk);
1709 if (td) {
1710 /* XXX don't tell disk, its optional */
1711 ffs_blkfree_td(ts->fs, td);
1712 #ifdef TRIMDEBUG
1713 printf("finish(%" PRId64 ",%ld)\n", td->bno, td->size);
1714 #endif
1715 kmem_free(td, sizeof(*td));
1716 }
1717
1718 cv_destroy(&ts->wqcv);
1719 mutex_destroy(&ts->entrylk);
1720 mutex_destroy(&ts->wqlk);
1721 workqueue_destroy(ts->wq);
1722 kmem_free(ts, sizeof(*ts));
1723 }
1724
1725 void
1726 ffs_blkfree(struct fs *fs, struct vnode *devvp, daddr_t bno, long size,
1727 ino_t inum)
1728 {
1729 struct ufsmount *ump;
1730 int error;
1731 dev_t dev;
1732 struct discarddata *ts;
1733 struct discardopdata *td;
1734
1735 dev = devvp->v_rdev;
1736 ump = VFSTOUFS(spec_node_getmountedfs(devvp));
1737 if (ffs_snapblkfree(fs, devvp, bno, size, inum))
1738 return;
1739
1740 error = ffs_check_bad_allocation(__func__, fs, bno, size, dev, inum);
1741 if (error)
1742 return;
1743
1744 if (!ump->um_discarddata) {
1745 ffs_blkfree_cg(fs, devvp, bno, size);
1746 return;
1747 }
1748
1749 #ifdef TRIMDEBUG
1750 printf("blkfree(%" PRId64 ",%ld)\n", bno, size);
1751 #endif
1752 ts = ump->um_discarddata;
1753 td = NULL;
1754
1755 mutex_enter(&ts->entrylk);
1756 if (ts->entry) {
1757 td = ts->entry;
1758 /* ffs deallocs backwards, check for prepend only */
1759 if (td->bno == bno + ffs_numfrags(fs, size)
1760 && td->size + size <= ts->maxsize) {
1761 td->bno = bno;
1762 td->size += size;
1763 if (td->size < ts->maxsize) {
1764 #ifdef TRIMDEBUG
1765 printf("defer(%" PRId64 ",%ld)\n", td->bno, td->size);
1766 #endif
1767 mutex_exit(&ts->entrylk);
1768 return;
1769 }
1770 size = 0; /* mark done */
1771 }
1772 ts->entry = NULL;
1773 }
1774 mutex_exit(&ts->entrylk);
1775
1776 if (td) {
1777 #ifdef TRIMDEBUG
1778 printf("enq old(%" PRId64 ",%ld)\n", td->bno, td->size);
1779 #endif
1780 mutex_enter(&ts->wqlk);
1781 ts->wqcnt++;
1782 mutex_exit(&ts->wqlk);
1783 workqueue_enqueue(ts->wq, &td->wk, NULL);
1784 }
1785 if (!size)
1786 return;
1787
1788 td = kmem_alloc(sizeof(*td), KM_SLEEP);
1789 td->devvp = devvp;
1790 td->bno = bno;
1791 td->size = size;
1792
1793 if (td->size < ts->maxsize) { /* XXX always the case */
1794 mutex_enter(&ts->entrylk);
1795 if (!ts->entry) { /* possible race? */
1796 #ifdef TRIMDEBUG
1797 printf("defer(%" PRId64 ",%ld)\n", td->bno, td->size);
1798 #endif
1799 ts->entry = td;
1800 td = NULL;
1801 }
1802 mutex_exit(&ts->entrylk);
1803 }
1804 if (td) {
1805 #ifdef TRIMDEBUG
1806 printf("enq new(%" PRId64 ",%ld)\n", td->bno, td->size);
1807 #endif
1808 mutex_enter(&ts->wqlk);
1809 ts->wqcnt++;
1810 mutex_exit(&ts->wqlk);
1811 workqueue_enqueue(ts->wq, &td->wk, NULL);
1812 }
1813 }
1814
1815 /*
1816 * Free a block or fragment from a snapshot cg copy.
1817 *
1818 * The specified block or fragment is placed back in the
1819 * free map. If a fragment is deallocated, a possible
1820 * block reassembly is checked.
1821 *
1822 * => um_lock not held on entry or exit
1823 */
1824 void
1825 ffs_blkfree_snap(struct fs *fs, struct vnode *devvp, daddr_t bno, long size,
1826 ino_t inum)
1827 {
1828 struct cg *cgp;
1829 struct buf *bp;
1830 struct ufsmount *ump;
1831 daddr_t cgblkno;
1832 int error, cg;
1833 dev_t dev;
1834 const bool devvp_is_snapshot = (devvp->v_type != VBLK);
1835 const int needswap = UFS_FSNEEDSWAP(fs);
1836
1837 KASSERT(devvp_is_snapshot);
1838
1839 cg = dtog(fs, bno);
1840 dev = VTOI(devvp)->i_devvp->v_rdev;
1841 ump = VFSTOUFS(devvp->v_mount);
1842 cgblkno = ffs_fragstoblks(fs, cgtod(fs, cg));
1843
1844 error = ffs_check_bad_allocation(__func__, fs, bno, size, dev, inum);
1845 if (error)
1846 return;
1847
1848 error = bread(devvp, cgblkno, (int)fs->fs_cgsize,
1849 B_MODIFY, &bp);
1850 if (error) {
1851 return;
1852 }
1853 cgp = (struct cg *)bp->b_data;
1854 if (!cg_chkmagic(cgp, needswap)) {
1855 brelse(bp, 0);
1856 return;
1857 }
1858
1859 ffs_blkfree_common(ump, fs, dev, bp, bno, size, devvp_is_snapshot);
1860
1861 bdwrite(bp);
1862 }
1863
1864 static void
1865 ffs_blkfree_common(struct ufsmount *ump, struct fs *fs, dev_t dev,
1866 struct buf *bp, daddr_t bno, long size, bool devvp_is_snapshot)
1867 {
1868 struct cg *cgp;
1869 int32_t fragno, cgbno;
1870 int i, cg, blk, frags, bbase;
1871 u_int8_t *blksfree;
1872 const int needswap = UFS_FSNEEDSWAP(fs);
1873
1874 cg = dtog(fs, bno);
1875 cgp = (struct cg *)bp->b_data;
1876 cgp->cg_old_time = ufs_rw32(time_second, needswap);
1877 if ((fs->fs_magic != FS_UFS1_MAGIC) ||
1878 (fs->fs_old_flags & FS_FLAGS_UPDATED))
1879 cgp->cg_time = ufs_rw64(time_second, needswap);
1880 cgbno = dtogd(fs, bno);
1881 blksfree = cg_blksfree(cgp, needswap);
1882 mutex_enter(&ump->um_lock);
1883 if (size == fs->fs_bsize) {
1884 fragno = ffs_fragstoblks(fs, cgbno);
1885 if (!ffs_isfreeblock(fs, blksfree, fragno)) {
1886 if (devvp_is_snapshot) {
1887 mutex_exit(&ump->um_lock);
1888 return;
1889 }
1890 panic("%s: freeing free block: dev = 0x%llx, block = %"
1891 PRId64 ", fs = %s", __func__,
1892 (unsigned long long)dev, bno, fs->fs_fsmnt);
1893 }
1894 ffs_setblock(fs, blksfree, fragno);
1895 ffs_clusteracct(fs, cgp, fragno, 1);
1896 ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
1897 fs->fs_cstotal.cs_nbfree++;
1898 fs->fs_cs(fs, cg).cs_nbfree++;
1899 if ((fs->fs_magic == FS_UFS1_MAGIC) &&
1900 ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
1901 i = old_cbtocylno(fs, cgbno);
1902 KASSERT(i >= 0);
1903 KASSERT(i < fs->fs_old_ncyl);
1904 KASSERT(old_cbtorpos(fs, cgbno) >= 0);
1905 KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, cgbno) < fs->fs_old_nrpos);
1906 ufs_add16(old_cg_blks(fs, cgp, i, needswap)[old_cbtorpos(fs, cgbno)], 1,
1907 needswap);
1908 ufs_add32(old_cg_blktot(cgp, needswap)[i], 1, needswap);
1909 }
1910 } else {
1911 bbase = cgbno - ffs_fragnum(fs, cgbno);
1912 /*
1913 * decrement the counts associated with the old frags
1914 */
1915 blk = blkmap(fs, blksfree, bbase);
1916 ffs_fragacct(fs, blk, cgp->cg_frsum, -1, needswap);
1917 /*
1918 * deallocate the fragment
1919 */
1920 frags = ffs_numfrags(fs, size);
1921 for (i = 0; i < frags; i++) {
1922 if (isset(blksfree, cgbno + i)) {
1923 panic("%s: freeing free frag: "
1924 "dev = 0x%llx, block = %" PRId64
1925 ", fs = %s", __func__,
1926 (unsigned long long)dev, bno + i,
1927 fs->fs_fsmnt);
1928 }
1929 setbit(blksfree, cgbno + i);
1930 }
1931 ufs_add32(cgp->cg_cs.cs_nffree, i, needswap);
1932 fs->fs_cstotal.cs_nffree += i;
1933 fs->fs_cs(fs, cg).cs_nffree += i;
1934 /*
1935 * add back in counts associated with the new frags
1936 */
1937 blk = blkmap(fs, blksfree, bbase);
1938 ffs_fragacct(fs, blk, cgp->cg_frsum, 1, needswap);
1939 /*
1940 * if a complete block has been reassembled, account for it
1941 */
1942 fragno = ffs_fragstoblks(fs, bbase);
1943 if (ffs_isblock(fs, blksfree, fragno)) {
1944 ufs_add32(cgp->cg_cs.cs_nffree, -fs->fs_frag, needswap);
1945 fs->fs_cstotal.cs_nffree -= fs->fs_frag;
1946 fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
1947 ffs_clusteracct(fs, cgp, fragno, 1);
1948 ufs_add32(cgp->cg_cs.cs_nbfree, 1, needswap);
1949 fs->fs_cstotal.cs_nbfree++;
1950 fs->fs_cs(fs, cg).cs_nbfree++;
1951 if ((fs->fs_magic == FS_UFS1_MAGIC) &&
1952 ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0)) {
1953 i = old_cbtocylno(fs, bbase);
1954 KASSERT(i >= 0);
1955 KASSERT(i < fs->fs_old_ncyl);
1956 KASSERT(old_cbtorpos(fs, bbase) >= 0);
1957 KASSERT(fs->fs_old_nrpos == 0 || old_cbtorpos(fs, bbase) < fs->fs_old_nrpos);
1958 ufs_add16(old_cg_blks(fs, cgp, i, needswap)[old_cbtorpos(fs,
1959 bbase)], 1, needswap);
1960 ufs_add32(old_cg_blktot(cgp, needswap)[i], 1, needswap);
1961 }
1962 }
1963 }
1964 fs->fs_fmod = 1;
1965 ACTIVECG_CLR(fs, cg);
1966 mutex_exit(&ump->um_lock);
1967 }
1968
1969 /*
1970 * Free an inode.
1971 */
1972 int
1973 ffs_vfree(struct vnode *vp, ino_t ino, int mode)
1974 {
1975
1976 return ffs_freefile(vp->v_mount, ino, mode);
1977 }
1978
1979 /*
1980 * Do the actual free operation.
1981 * The specified inode is placed back in the free map.
1982 *
1983 * => um_lock not held on entry or exit
1984 */
1985 int
1986 ffs_freefile(struct mount *mp, ino_t ino, int mode)
1987 {
1988 struct ufsmount *ump = VFSTOUFS(mp);
1989 struct fs *fs = ump->um_fs;
1990 struct vnode *devvp;
1991 struct cg *cgp;
1992 struct buf *bp;
1993 int error, cg;
1994 daddr_t cgbno;
1995 dev_t dev;
1996 const int needswap = UFS_FSNEEDSWAP(fs);
1997
1998 cg = ino_to_cg(fs, ino);
1999 devvp = ump->um_devvp;
2000 dev = devvp->v_rdev;
2001 cgbno = FFS_FSBTODB(fs, cgtod(fs, cg));
2002
2003 if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
2004 panic("%s: range: dev = 0x%llx, ino = %llu, fs = %s", __func__,
2005 (long long)dev, (unsigned long long)ino, fs->fs_fsmnt);
2006 error = bread(devvp, cgbno, (int)fs->fs_cgsize,
2007 B_MODIFY, &bp);
2008 if (error) {
2009 return (error);
2010 }
2011 cgp = (struct cg *)bp->b_data;
2012 if (!cg_chkmagic(cgp, needswap)) {
2013 brelse(bp, 0);
2014 return (0);
2015 }
2016
2017 ffs_freefile_common(ump, fs, dev, bp, ino, mode, false);
2018
2019 bdwrite(bp);
2020
2021 return 0;
2022 }
2023
2024 int
2025 ffs_freefile_snap(struct fs *fs, struct vnode *devvp, ino_t ino, int mode)
2026 {
2027 struct ufsmount *ump;
2028 struct cg *cgp;
2029 struct buf *bp;
2030 int error, cg;
2031 daddr_t cgbno;
2032 dev_t dev;
2033 const int needswap = UFS_FSNEEDSWAP(fs);
2034
2035 KASSERT(devvp->v_type != VBLK);
2036
2037 cg = ino_to_cg(fs, ino);
2038 dev = VTOI(devvp)->i_devvp->v_rdev;
2039 ump = VFSTOUFS(devvp->v_mount);
2040 cgbno = ffs_fragstoblks(fs, cgtod(fs, cg));
2041 if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
2042 panic("%s: range: dev = 0x%llx, ino = %llu, fs = %s", __func__,
2043 (unsigned long long)dev, (unsigned long long)ino,
2044 fs->fs_fsmnt);
2045 error = bread(devvp, cgbno, (int)fs->fs_cgsize,
2046 B_MODIFY, &bp);
2047 if (error) {
2048 return (error);
2049 }
2050 cgp = (struct cg *)bp->b_data;
2051 if (!cg_chkmagic(cgp, needswap)) {
2052 brelse(bp, 0);
2053 return (0);
2054 }
2055 ffs_freefile_common(ump, fs, dev, bp, ino, mode, true);
2056
2057 bdwrite(bp);
2058
2059 return 0;
2060 }
2061
2062 static void
2063 ffs_freefile_common(struct ufsmount *ump, struct fs *fs, dev_t dev,
2064 struct buf *bp, ino_t ino, int mode, bool devvp_is_snapshot)
2065 {
2066 int cg;
2067 struct cg *cgp;
2068 u_int8_t *inosused;
2069 const int needswap = UFS_FSNEEDSWAP(fs);
2070
2071 cg = ino_to_cg(fs, ino);
2072 cgp = (struct cg *)bp->b_data;
2073 cgp->cg_old_time = ufs_rw32(time_second, needswap);
2074 if ((fs->fs_magic != FS_UFS1_MAGIC) ||
2075 (fs->fs_old_flags & FS_FLAGS_UPDATED))
2076 cgp->cg_time = ufs_rw64(time_second, needswap);
2077 inosused = cg_inosused(cgp, needswap);
2078 ino %= fs->fs_ipg;
2079 if (isclr(inosused, ino)) {
2080 printf("ifree: dev = 0x%llx, ino = %llu, fs = %s\n",
2081 (unsigned long long)dev, (unsigned long long)ino +
2082 cg * fs->fs_ipg, fs->fs_fsmnt);
2083 if (fs->fs_ronly == 0)
2084 panic("%s: freeing free inode", __func__);
2085 }
2086 clrbit(inosused, ino);
2087 if (!devvp_is_snapshot)
2088 UFS_WAPBL_UNREGISTER_INODE(ump->um_mountp,
2089 ino + cg * fs->fs_ipg, mode);
2090 if (ino < ufs_rw32(cgp->cg_irotor, needswap))
2091 cgp->cg_irotor = ufs_rw32(ino, needswap);
2092 ufs_add32(cgp->cg_cs.cs_nifree, 1, needswap);
2093 mutex_enter(&ump->um_lock);
2094 fs->fs_cstotal.cs_nifree++;
2095 fs->fs_cs(fs, cg).cs_nifree++;
2096 if ((mode & IFMT) == IFDIR) {
2097 ufs_add32(cgp->cg_cs.cs_ndir, -1, needswap);
2098 fs->fs_cstotal.cs_ndir--;
2099 fs->fs_cs(fs, cg).cs_ndir--;
2100 }
2101 fs->fs_fmod = 1;
2102 ACTIVECG_CLR(fs, cg);
2103 mutex_exit(&ump->um_lock);
2104 }
2105
2106 /*
2107 * Check to see if a file is free.
2108 */
2109 int
2110 ffs_checkfreefile(struct fs *fs, struct vnode *devvp, ino_t ino)
2111 {
2112 struct cg *cgp;
2113 struct buf *bp;
2114 daddr_t cgbno;
2115 int ret, cg;
2116 u_int8_t *inosused;
2117 const bool devvp_is_snapshot = (devvp->v_type != VBLK);
2118
2119 KASSERT(devvp_is_snapshot);
2120
2121 cg = ino_to_cg(fs, ino);
2122 if (devvp_is_snapshot)
2123 cgbno = ffs_fragstoblks(fs, cgtod(fs, cg));
2124 else
2125 cgbno = FFS_FSBTODB(fs, cgtod(fs, cg));
2126 if ((u_int)ino >= fs->fs_ipg * fs->fs_ncg)
2127 return 1;
2128 if (bread(devvp, cgbno, (int)fs->fs_cgsize, 0, &bp)) {
2129 return 1;
2130 }
2131 cgp = (struct cg *)bp->b_data;
2132 if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
2133 brelse(bp, 0);
2134 return 1;
2135 }
2136 inosused = cg_inosused(cgp, UFS_FSNEEDSWAP(fs));
2137 ino %= fs->fs_ipg;
2138 ret = isclr(inosused, ino);
2139 brelse(bp, 0);
2140 return ret;
2141 }
2142
2143 /*
2144 * Find a block of the specified size in the specified cylinder group.
2145 *
2146 * It is a panic if a request is made to find a block if none are
2147 * available.
2148 */
2149 static int32_t
2150 ffs_mapsearch(struct fs *fs, struct cg *cgp, daddr_t bpref, int allocsiz)
2151 {
2152 int32_t bno;
2153 int start, len, loc, i;
2154 int blk, field, subfield, pos;
2155 int ostart, olen;
2156 u_int8_t *blksfree;
2157 const int needswap = UFS_FSNEEDSWAP(fs);
2158
2159 /* KASSERT(mutex_owned(&ump->um_lock)); */
2160
2161 /*
2162 * find the fragment by searching through the free block
2163 * map for an appropriate bit pattern
2164 */
2165 if (bpref)
2166 start = dtogd(fs, bpref) / NBBY;
2167 else
2168 start = ufs_rw32(cgp->cg_frotor, needswap) / NBBY;
2169 blksfree = cg_blksfree(cgp, needswap);
2170 len = howmany(fs->fs_fpg, NBBY) - start;
2171 ostart = start;
2172 olen = len;
2173 loc = scanc((u_int)len,
2174 (const u_char *)&blksfree[start],
2175 (const u_char *)fragtbl[fs->fs_frag],
2176 (1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
2177 if (loc == 0) {
2178 len = start + 1;
2179 start = 0;
2180 loc = scanc((u_int)len,
2181 (const u_char *)&blksfree[0],
2182 (const u_char *)fragtbl[fs->fs_frag],
2183 (1 << (allocsiz - 1 + (fs->fs_frag & (NBBY - 1)))));
2184 if (loc == 0) {
2185 panic("%s: map corrupted: start=%d, len=%d, "
2186 "fs = %s, offset=%d/%ld, cg %d", __func__,
2187 ostart, olen, fs->fs_fsmnt,
2188 ufs_rw32(cgp->cg_freeoff, needswap),
2189 (long)blksfree - (long)cgp, cgp->cg_cgx);
2190 /* NOTREACHED */
2191 }
2192 }
2193 bno = (start + len - loc) * NBBY;
2194 cgp->cg_frotor = ufs_rw32(bno, needswap);
2195 /*
2196 * found the byte in the map
2197 * sift through the bits to find the selected frag
2198 */
2199 for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
2200 blk = blkmap(fs, blksfree, bno);
2201 blk <<= 1;
2202 field = around[allocsiz];
2203 subfield = inside[allocsiz];
2204 for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
2205 if ((blk & field) == subfield)
2206 return (bno + pos);
2207 field <<= 1;
2208 subfield <<= 1;
2209 }
2210 }
2211 panic("%s: block not in map: bno=%d, fs=%s", __func__,
2212 bno, fs->fs_fsmnt);
2213 /* return (-1); */
2214 }
2215
2216 /*
2217 * Fserr prints the name of a file system with an error diagnostic.
2218 *
2219 * The form of the error message is:
2220 * fs: error message
2221 */
2222 static void
2223 ffs_fserr(struct fs *fs, kauth_cred_t cred, const char *cp)
2224 {
2225 KASSERT(cred != NULL);
2226
2227 if (cred == NOCRED || cred == FSCRED) {
2228 log(LOG_ERR, "pid %d, command %s, on %s: %s\n",
2229 curproc->p_pid, curproc->p_comm,
2230 fs->fs_fsmnt, cp);
2231 } else {
2232 log(LOG_ERR, "uid %d, pid %d, command %s, on %s: %s\n",
2233 kauth_cred_getuid(cred), curproc->p_pid, curproc->p_comm,
2234 fs->fs_fsmnt, cp);
2235 }
2236 }
2237