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