]> git.saurik.com Git - apple/xnu.git/blob - bsd/vfs/vfs_bio.c
8f6f0633e77d8ff5f9c8fef8f5661590741210ef
[apple/xnu.git] / bsd / vfs / vfs_bio.c
1 /*
2 * Copyright (c) 2000-2004 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
23 /*-
24 * Copyright (c) 1994 Christopher G. Demetriou
25 * Copyright (c) 1982, 1986, 1989, 1993
26 * The Regents of the University of California. All rights reserved.
27 * (c) UNIX System Laboratories, Inc.
28 * All or some portions of this file are derived from material licensed
29 * to the University of California by American Telephone and Telegraph
30 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
31 * the permission of UNIX System Laboratories, Inc.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
61 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
62 */
63
64 /*
65 * Some references:
66 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
67 * Leffler, et al.: The Design and Implementation of the 4.3BSD
68 * UNIX Operating System (Addison Welley, 1989)
69 */
70
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/proc_internal.h>
74 #include <sys/buf_internal.h>
75 #include <sys/vnode_internal.h>
76 #include <sys/mount_internal.h>
77 #include <sys/trace.h>
78 #include <sys/malloc.h>
79 #include <sys/resourcevar.h>
80 #include <miscfs/specfs/specdev.h>
81 #include <sys/ubc.h>
82 #include <sys/kauth.h>
83 #if DIAGNOSTIC
84 #include <kern/assert.h>
85 #endif /* DIAGNOSTIC */
86 #include <kern/task.h>
87 #include <kern/zalloc.h>
88 #include <kern/lock.h>
89
90 #include <vm/vm_kern.h>
91
92 #include <sys/kdebug.h>
93 #include <machine/spl.h>
94
95 #if BALANCE_QUEUES
96 static __inline__ void bufqinc(int q);
97 static __inline__ void bufqdec(int q);
98 #endif
99
100 static int bcleanbuf(buf_t bp);
101 static int brecover_data(buf_t bp);
102 static boolean_t incore(vnode_t vp, daddr64_t blkno);
103 static buf_t incore_locked(vnode_t vp, daddr64_t blkno);
104 /* timeout is in msecs */
105 static buf_t getnewbuf(int slpflag, int slptimeo, int *queue);
106 static void bremfree_locked(buf_t bp);
107 static void buf_reassign(buf_t bp, vnode_t newvp);
108 static errno_t buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo);
109 static int buf_iterprepare(vnode_t vp, struct buflists *, int flags);
110 static void buf_itercomplete(vnode_t vp, struct buflists *, int flags);
111
112 __private_extern__ int bdwrite_internal(buf_t, int);
113
114 /* zone allocated buffer headers */
115 static void bufzoneinit(void);
116 static void bcleanbuf_thread_init(void);
117 static void bcleanbuf_thread(void);
118
119 static zone_t buf_hdr_zone;
120 static int buf_hdr_count;
121
122
123 /*
124 * Definitions for the buffer hash lists.
125 */
126 #define BUFHASH(dvp, lbn) \
127 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
128 LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
129 u_long bufhash;
130
131 /* Definitions for the buffer stats. */
132 struct bufstats bufstats;
133
134 /* Number of delayed write buffers */
135 int nbdwrite = 0;
136 int blaundrycnt = 0;
137
138
139 static TAILQ_HEAD(ioqueue, buf) iobufqueue;
140 static TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
141 static int needbuffer;
142 static int need_iobuffer;
143
144 static lck_grp_t *buf_mtx_grp;
145 static lck_attr_t *buf_mtx_attr;
146 static lck_grp_attr_t *buf_mtx_grp_attr;
147 static lck_mtx_t *iobuffer_mtxp;
148 static lck_mtx_t *buf_mtxp;
149
150 static __inline__ int
151 buf_timestamp(void)
152 {
153 struct timeval t;
154 microuptime(&t);
155 return (t.tv_sec);
156 }
157
158 /*
159 * Insq/Remq for the buffer free lists.
160 */
161 #if BALANCE_QUEUES
162 #define binsheadfree(bp, dp, whichq) do { \
163 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
164 bufqinc((whichq)); \
165 (bp)->b_whichq = whichq; \
166 (bp)->b_timestamp = buf_timestamp(); \
167 } while (0)
168
169 #define binstailfree(bp, dp, whichq) do { \
170 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
171 bufqinc((whichq)); \
172 (bp)->b_whichq = whichq; \
173 (bp)->b_timestamp = buf_timestamp(); \
174 } while (0)
175 #else
176 #define binsheadfree(bp, dp, whichq) do { \
177 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
178 (bp)->b_whichq = whichq; \
179 (bp)->b_timestamp = buf_timestamp(); \
180 } while (0)
181
182 #define binstailfree(bp, dp, whichq) do { \
183 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
184 (bp)->b_whichq = whichq; \
185 (bp)->b_timestamp = buf_timestamp(); \
186 } while (0)
187 #endif
188
189
190 #define BHASHENTCHECK(bp) \
191 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
192 panic("%x: b_hash.le_prev is not deadbeef", (bp));
193
194 #define BLISTNONE(bp) \
195 (bp)->b_hash.le_next = (struct buf *)0; \
196 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
197
198 /*
199 * Insq/Remq for the vnode usage lists.
200 */
201 #define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
202 #define bufremvn(bp) { \
203 LIST_REMOVE(bp, b_vnbufs); \
204 (bp)->b_vnbufs.le_next = NOLIST; \
205 }
206
207 /*
208 * Time in seconds before a buffer on a list is
209 * considered as a stale buffer
210 */
211 #define LRU_IS_STALE 120 /* default value for the LRU */
212 #define AGE_IS_STALE 60 /* default value for the AGE */
213 #define META_IS_STALE 180 /* default value for the BQ_META */
214
215 int lru_is_stale = LRU_IS_STALE;
216 int age_is_stale = AGE_IS_STALE;
217 int meta_is_stale = META_IS_STALE;
218 static int boot_nbuf = 0;
219
220
221 /* LIST_INSERT_HEAD() with assertions */
222 static __inline__ void
223 blistenterhead(struct bufhashhdr * head, buf_t bp)
224 {
225 if ((bp->b_hash.le_next = (head)->lh_first) != NULL)
226 (head)->lh_first->b_hash.le_prev = &(bp)->b_hash.le_next;
227 (head)->lh_first = bp;
228 bp->b_hash.le_prev = &(head)->lh_first;
229 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
230 panic("blistenterhead: le_prev is deadbeef");
231 }
232
233 static __inline__ void
234 binshash(buf_t bp, struct bufhashhdr *dp)
235 {
236 #if DIAGNOSTIC
237 buf_t nbp;
238 #endif /* DIAGNOSTIC */
239
240 BHASHENTCHECK(bp);
241
242 #if DIAGNOSTIC
243 nbp = dp->lh_first;
244 for(; nbp != NULL; nbp = nbp->b_hash.le_next) {
245 if(nbp == bp)
246 panic("buf already in hashlist");
247 }
248 #endif /* DIAGNOSTIC */
249
250 blistenterhead(dp, bp);
251 }
252
253 static __inline__ void
254 bremhash(buf_t bp)
255 {
256 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
257 panic("bremhash le_prev is deadbeef");
258 if (bp->b_hash.le_next == bp)
259 panic("bremhash: next points to self");
260
261 if (bp->b_hash.le_next != NULL)
262 bp->b_hash.le_next->b_hash.le_prev = bp->b_hash.le_prev;
263 *bp->b_hash.le_prev = (bp)->b_hash.le_next;
264 }
265
266
267
268
269 int
270 buf_valid(buf_t bp) {
271
272 if ( (bp->b_flags & (B_DONE | B_DELWRI)) )
273 return 1;
274 return 0;
275 }
276
277 int
278 buf_fromcache(buf_t bp) {
279
280 if ( (bp->b_flags & B_CACHE) )
281 return 1;
282 return 0;
283 }
284
285 void
286 buf_markinvalid(buf_t bp) {
287
288 SET(bp->b_flags, B_INVAL);
289 }
290
291 void
292 buf_markdelayed(buf_t bp) {
293
294 SET(bp->b_flags, B_DELWRI);
295 buf_reassign(bp, bp->b_vp);
296 }
297
298 void
299 buf_markeintr(buf_t bp) {
300
301 SET(bp->b_flags, B_EINTR);
302 }
303
304 void
305 buf_markaged(buf_t bp) {
306
307 SET(bp->b_flags, B_AGE);
308 }
309
310 errno_t
311 buf_error(buf_t bp) {
312
313 return (bp->b_error);
314 }
315
316 void
317 buf_seterror(buf_t bp, errno_t error) {
318
319 if ((bp->b_error = error))
320 SET(bp->b_flags, B_ERROR);
321 else
322 CLR(bp->b_flags, B_ERROR);
323 }
324
325 void
326 buf_setflags(buf_t bp, int32_t flags) {
327
328 SET(bp->b_flags, (flags & BUF_X_WRFLAGS));
329 }
330
331 void
332 buf_clearflags(buf_t bp, int32_t flags) {
333
334 CLR(bp->b_flags, (flags & BUF_X_WRFLAGS));
335 }
336
337 int32_t
338 buf_flags(buf_t bp) {
339
340 return ((bp->b_flags & BUF_X_RDFLAGS));
341 }
342
343 void
344 buf_reset(buf_t bp, int32_t io_flags) {
345
346 CLR(bp->b_flags, (B_READ | B_WRITE | B_ERROR | B_DONE | B_INVAL | B_ASYNC | B_NOCACHE));
347 SET(bp->b_flags, (io_flags & (B_ASYNC | B_READ | B_WRITE | B_NOCACHE)));
348
349 bp->b_error = 0;
350 }
351
352 uint32_t
353 buf_count(buf_t bp) {
354
355 return (bp->b_bcount);
356 }
357
358 void
359 buf_setcount(buf_t bp, uint32_t bcount) {
360
361 bp->b_bcount = bcount;
362 }
363
364 uint32_t
365 buf_size(buf_t bp) {
366
367 return (bp->b_bufsize);
368 }
369
370 void
371 buf_setsize(buf_t bp, uint32_t bufsize) {
372
373 bp->b_bufsize = bufsize;
374 }
375
376 uint32_t
377 buf_resid(buf_t bp) {
378
379 return (bp->b_resid);
380 }
381
382 void
383 buf_setresid(buf_t bp, uint32_t resid) {
384
385 bp->b_resid = resid;
386 }
387
388 uint32_t
389 buf_dirtyoff(buf_t bp) {
390
391 return (bp->b_dirtyoff);
392 }
393
394 uint32_t
395 buf_dirtyend(buf_t bp) {
396
397 return (bp->b_dirtyend);
398 }
399
400 void
401 buf_setdirtyoff(buf_t bp, uint32_t dirtyoff) {
402
403 bp->b_dirtyoff = dirtyoff;
404 }
405
406 void
407 buf_setdirtyend(buf_t bp, uint32_t dirtyend) {
408
409 bp->b_dirtyend = dirtyend;
410 }
411
412 uintptr_t
413 buf_dataptr(buf_t bp) {
414
415 return (bp->b_datap);
416 }
417
418 void
419 buf_setdataptr(buf_t bp, uintptr_t data) {
420
421 bp->b_datap = data;
422 }
423
424 vnode_t
425 buf_vnode(buf_t bp) {
426
427 return (bp->b_vp);
428 }
429
430 void
431 buf_setvnode(buf_t bp, vnode_t vp) {
432
433 bp->b_vp = vp;
434 }
435
436
437 void *
438 buf_callback(buf_t bp)
439 {
440 if ( !(bp->b_lflags & BL_IOBUF) )
441 return ((void *) NULL);
442 if ( !(bp->b_flags & B_CALL) )
443 return ((void *) NULL);
444
445 return ((void *)bp->b_iodone);
446 }
447
448
449 errno_t
450 buf_setcallback(buf_t bp, void (*callback)(buf_t, void *), void *transaction)
451 {
452
453 if ( !(bp->b_lflags & BL_IOBUF) )
454 return (EINVAL);
455
456 if (callback)
457 bp->b_flags |= (B_CALL | B_ASYNC);
458 else
459 bp->b_flags &= ~B_CALL;
460 bp->b_transaction = transaction;
461 bp->b_iodone = callback;
462
463 return (0);
464 }
465
466 errno_t
467 buf_setupl(buf_t bp, upl_t upl, uint32_t offset)
468 {
469
470 if ( !(bp->b_lflags & BL_IOBUF) )
471 return (EINVAL);
472
473 if (upl)
474 bp->b_flags |= B_CLUSTER;
475 else
476 bp->b_flags &= ~B_CLUSTER;
477 bp->b_upl = upl;
478 bp->b_uploffset = offset;
479
480 return (0);
481 }
482
483 buf_t
484 buf_clone(buf_t bp, int io_offset, int io_size, void (*iodone)(buf_t, void *), void *arg)
485 {
486 buf_t io_bp;
487
488 if (io_offset < 0 || io_size < 0)
489 return (NULL);
490
491 if ((unsigned)(io_offset + io_size) > (unsigned)bp->b_bcount)
492 return (NULL);
493
494 if (bp->b_flags & B_CLUSTER) {
495 if (io_offset && ((bp->b_uploffset + io_offset) & PAGE_MASK))
496 return (NULL);
497
498 if (((bp->b_uploffset + io_offset + io_size) & PAGE_MASK) && ((io_offset + io_size) < bp->b_bcount))
499 return (NULL);
500 }
501 io_bp = alloc_io_buf(bp->b_vp, 0);
502
503 io_bp->b_flags = bp->b_flags & (B_COMMIT_UPL | B_META | B_PAGEIO | B_CLUSTER | B_PHYS | B_ASYNC | B_READ);
504
505 if (iodone) {
506 io_bp->b_transaction = arg;
507 io_bp->b_iodone = iodone;
508 io_bp->b_flags |= B_CALL;
509 }
510 if (bp->b_flags & B_CLUSTER) {
511 io_bp->b_upl = bp->b_upl;
512 io_bp->b_uploffset = bp->b_uploffset + io_offset;
513 } else {
514 io_bp->b_datap = (uintptr_t)(((char *)bp->b_datap) + io_offset);
515 }
516 io_bp->b_bcount = io_size;
517
518 return (io_bp);
519 }
520
521
522
523 void
524 buf_setfilter(buf_t bp, void (*filter)(buf_t, void *), void *transaction,
525 void **old_iodone, void **old_transaction)
526 {
527 if (old_iodone)
528 *old_iodone = (void *)(bp->b_iodone);
529 if (old_transaction)
530 *old_transaction = (void *)(bp->b_transaction);
531
532 bp->b_transaction = transaction;
533 bp->b_iodone = filter;
534 bp->b_flags |= B_FILTER;
535 }
536
537
538 daddr64_t
539 buf_blkno(buf_t bp) {
540
541 return (bp->b_blkno);
542 }
543
544 daddr64_t
545 buf_lblkno(buf_t bp) {
546
547 return (bp->b_lblkno);
548 }
549
550 void
551 buf_setblkno(buf_t bp, daddr64_t blkno) {
552
553 bp->b_blkno = blkno;
554 }
555
556 void
557 buf_setlblkno(buf_t bp, daddr64_t lblkno) {
558
559 bp->b_lblkno = lblkno;
560 }
561
562 dev_t
563 buf_device(buf_t bp) {
564
565 return (bp->b_dev);
566 }
567
568 errno_t
569 buf_setdevice(buf_t bp, vnode_t vp) {
570
571 if ((vp->v_type != VBLK) && (vp->v_type != VCHR))
572 return EINVAL;
573 bp->b_dev = vp->v_rdev;
574
575 return 0;
576 }
577
578
579 void *
580 buf_drvdata(buf_t bp) {
581
582 return (bp->b_drvdata);
583 }
584
585 void
586 buf_setdrvdata(buf_t bp, void *drvdata) {
587
588 bp->b_drvdata = drvdata;
589 }
590
591 void *
592 buf_fsprivate(buf_t bp) {
593
594 return (bp->b_fsprivate);
595 }
596
597 void
598 buf_setfsprivate(buf_t bp, void *fsprivate) {
599
600 bp->b_fsprivate = fsprivate;
601 }
602
603 ucred_t
604 buf_rcred(buf_t bp) {
605
606 return (bp->b_rcred);
607 }
608
609 ucred_t
610 buf_wcred(buf_t bp) {
611
612 return (bp->b_wcred);
613 }
614
615 void *
616 buf_upl(buf_t bp) {
617
618 return (bp->b_upl);
619 }
620
621 uint32_t
622 buf_uploffset(buf_t bp) {
623
624 return ((uint32_t)(bp->b_uploffset));
625 }
626
627 proc_t
628 buf_proc(buf_t bp) {
629
630 return (bp->b_proc);
631 }
632
633
634 errno_t
635 buf_map(buf_t bp, caddr_t *io_addr)
636 {
637 buf_t real_bp;
638 vm_offset_t vaddr;
639 kern_return_t kret;
640
641 if ( !(bp->b_flags & B_CLUSTER)) {
642 *io_addr = (caddr_t)bp->b_datap;
643 return (0);
644 }
645 real_bp = (buf_t)(bp->b_real_bp);
646
647 if (real_bp && real_bp->b_datap) {
648 /*
649 * b_real_bp is only valid if B_CLUSTER is SET
650 * if it's non-zero, than someone did a cluster_bp call
651 * if the backing physical pages were already mapped
652 * in before the call to cluster_bp (non-zero b_datap),
653 * than we just use that mapping
654 */
655 *io_addr = (caddr_t)real_bp->b_datap;
656 return (0);
657 }
658 kret = ubc_upl_map(bp->b_upl, &vaddr); /* Map it in */
659
660 if (kret != KERN_SUCCESS) {
661 *io_addr = 0;
662
663 return(ENOMEM);
664 }
665 vaddr += bp->b_uploffset;
666
667 *io_addr = (caddr_t)vaddr;
668
669 return (0);
670 }
671
672 errno_t
673 buf_unmap(buf_t bp)
674 {
675 buf_t real_bp;
676 kern_return_t kret;
677
678 if ( !(bp->b_flags & B_CLUSTER))
679 return (0);
680 /*
681 * see buf_map for the explanation
682 */
683 real_bp = (buf_t)(bp->b_real_bp);
684
685 if (real_bp && real_bp->b_datap)
686 return (0);
687
688 if (bp->b_lflags & BL_IOBUF) {
689 /*
690 * when we commit these pages, we'll hit
691 * it with UPL_COMMIT_INACTIVE which
692 * will clear the reference bit that got
693 * turned on when we touched the mapping
694 */
695 bp->b_flags |= B_AGE;
696 }
697 kret = ubc_upl_unmap(bp->b_upl);
698
699 if (kret != KERN_SUCCESS)
700 return (EINVAL);
701 return (0);
702 }
703
704
705 void
706 buf_clear(buf_t bp) {
707 caddr_t baddr;
708
709 if (buf_map(bp, &baddr) == 0) {
710 bzero(baddr, bp->b_bcount);
711 buf_unmap(bp);
712 }
713 bp->b_resid = 0;
714 }
715
716
717
718 /*
719 * Read or write a buffer that is not contiguous on disk.
720 * buffer is marked done/error at the conclusion
721 */
722 static int
723 buf_strategy_fragmented(vnode_t devvp, buf_t bp, off_t f_offset, size_t contig_bytes)
724 {
725 vnode_t vp = buf_vnode(bp);
726 buf_t io_bp; /* For reading or writing a single block */
727 int io_direction;
728 int io_resid;
729 size_t io_contig_bytes;
730 daddr64_t io_blkno;
731 int error = 0;
732 int bmap_flags;
733
734 /*
735 * save our starting point... the bp was already mapped
736 * in buf_strategy before we got called
737 * no sense doing it again.
738 */
739 io_blkno = bp->b_blkno;
740 /*
741 * Make sure we redo this mapping for the next I/O
742 * i.e. this can never be a 'permanent' mapping
743 */
744 bp->b_blkno = bp->b_lblkno;
745
746 /*
747 * Get an io buffer to do the deblocking
748 */
749 io_bp = alloc_io_buf(devvp, 0);
750
751 io_bp->b_lblkno = bp->b_lblkno;
752 io_bp->b_datap = bp->b_datap;
753 io_resid = bp->b_bcount;
754 io_direction = bp->b_flags & B_READ;
755 io_contig_bytes = contig_bytes;
756
757 if (bp->b_flags & B_READ)
758 bmap_flags = VNODE_READ;
759 else
760 bmap_flags = VNODE_WRITE;
761
762 for (;;) {
763 if (io_blkno == -1)
764 /*
765 * this is unexepected, but we'll allow for it
766 */
767 bzero((caddr_t)io_bp->b_datap, (int)io_contig_bytes);
768 else {
769 io_bp->b_bcount = io_contig_bytes;
770 io_bp->b_bufsize = io_contig_bytes;
771 io_bp->b_resid = io_contig_bytes;
772 io_bp->b_blkno = io_blkno;
773
774 buf_reset(io_bp, io_direction);
775 /*
776 * Call the device to do the I/O and wait for it
777 */
778 if ((error = VNOP_STRATEGY(io_bp)))
779 break;
780 if ((error = (int)buf_biowait(io_bp)))
781 break;
782 if (io_bp->b_resid) {
783 io_resid -= (io_contig_bytes - io_bp->b_resid);
784 break;
785 }
786 }
787 if ((io_resid -= io_contig_bytes) == 0)
788 break;
789 f_offset += io_contig_bytes;
790 io_bp->b_datap += io_contig_bytes;
791
792 /*
793 * Map the current position to a physical block number
794 */
795 if ((error = VNOP_BLOCKMAP(vp, f_offset, io_resid, &io_blkno, &io_contig_bytes, NULL, bmap_flags, NULL)))
796 break;
797 }
798 buf_free(io_bp);
799
800 if (error)
801 buf_seterror(bp, error);
802 bp->b_resid = io_resid;
803 /*
804 * This I/O is now complete
805 */
806 buf_biodone(bp);
807
808 return error;
809 }
810
811
812 /*
813 * struct vnop_strategy_args {
814 * struct buf *a_bp;
815 * } *ap;
816 */
817 errno_t
818 buf_strategy(vnode_t devvp, void *ap)
819 {
820 buf_t bp = ((struct vnop_strategy_args *)ap)->a_bp;
821 vnode_t vp = bp->b_vp;
822 int bmap_flags;
823 errno_t error;
824
825 if (vp == NULL || vp->v_type == VCHR || vp->v_type == VBLK)
826 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
827 /*
828 * associate the physical device with
829 * with this buf_t even if we don't
830 * end up issuing the I/O...
831 */
832 bp->b_dev = devvp->v_rdev;
833
834 if (bp->b_flags & B_READ)
835 bmap_flags = VNODE_READ;
836 else
837 bmap_flags = VNODE_WRITE;
838
839 if ( !(bp->b_flags & B_CLUSTER)) {
840
841 if ( (bp->b_upl) ) {
842 /*
843 * we have a UPL associated with this bp
844 * go through cluster_bp which knows how
845 * to deal with filesystem block sizes
846 * that aren't equal to the page size
847 */
848 return (cluster_bp(bp));
849 }
850 if (bp->b_blkno == bp->b_lblkno) {
851 off_t f_offset;
852 size_t contig_bytes;
853
854 if ((error = VNOP_BLKTOOFF(vp, bp->b_lblkno, &f_offset))) {
855 buf_seterror(bp, error);
856 buf_biodone(bp);
857
858 return (error);
859 }
860 if ((error = VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))) {
861 buf_seterror(bp, error);
862 buf_biodone(bp);
863
864 return (error);
865 }
866 if (bp->b_blkno == -1)
867 buf_clear(bp);
868 else if ((long)contig_bytes < bp->b_bcount)
869 return (buf_strategy_fragmented(devvp, bp, f_offset, contig_bytes));
870 }
871 if (bp->b_blkno == -1) {
872 buf_biodone(bp);
873 return (0);
874 }
875 }
876 /*
877 * we can issue the I/O because...
878 * either B_CLUSTER is set which
879 * means that the I/O is properly set
880 * up to be a multiple of the page size, or
881 * we were able to successfully set up the
882 * phsyical block mapping
883 */
884 return (VOCALL(devvp->v_op, VOFFSET(vnop_strategy), ap));
885 }
886
887
888
889 buf_t
890 buf_alloc(vnode_t vp)
891 {
892 return(alloc_io_buf(vp, 0));
893 }
894
895 void
896 buf_free(buf_t bp) {
897
898 free_io_buf(bp);
899 }
900
901
902
903 void
904 buf_iterate(vnode_t vp, int (*callout)(buf_t, void *), int flags, void *arg) {
905 buf_t bp;
906 int retval;
907 struct buflists local_iterblkhd;
908 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
909
910 if (flags & BUF_SKIP_LOCKED)
911 lock_flags |= BAC_SKIP_LOCKED;
912 if (flags & BUF_SKIP_NONLOCKED)
913 lock_flags |= BAC_SKIP_NONLOCKED;
914
915 lck_mtx_lock(buf_mtxp);
916
917 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY)) {
918 lck_mtx_unlock(buf_mtxp);
919 return;
920 }
921 while (!LIST_EMPTY(&local_iterblkhd)) {
922 bp = LIST_FIRST(&local_iterblkhd);
923 LIST_REMOVE(bp, b_vnbufs);
924 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
925
926 if (buf_acquire_locked(bp, lock_flags, 0, 0))
927 continue;
928
929 lck_mtx_unlock(buf_mtxp);
930
931 retval = callout(bp, arg);
932
933 switch (retval) {
934 case BUF_RETURNED:
935 buf_brelse(bp);
936 break;
937 case BUF_CLAIMED:
938 break;
939 case BUF_RETURNED_DONE:
940 buf_brelse(bp);
941 lck_mtx_lock(buf_mtxp);
942 goto out;
943 case BUF_CLAIMED_DONE:
944 lck_mtx_lock(buf_mtxp);
945 goto out;
946 }
947 lck_mtx_lock(buf_mtxp);
948 }
949 out:
950 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
951
952 lck_mtx_unlock(buf_mtxp);
953 }
954
955
956 /*
957 * Flush out and invalidate all buffers associated with a vnode.
958 */
959 int
960 buf_invalidateblks(vnode_t vp, int flags, int slpflag, int slptimeo)
961 {
962 buf_t bp;
963 int error = 0;
964 int must_rescan = 1;
965 struct buflists local_iterblkhd;
966
967 lck_mtx_lock(buf_mtxp);
968
969 for (;;) {
970 if (must_rescan == 0)
971 /*
972 * the lists may not be empty, but all that's left at this
973 * point are metadata or B_LOCKED buffers which are being
974 * skipped... we know this because we made it through both
975 * the clean and dirty lists without dropping buf_mtxp...
976 * each time we drop buf_mtxp we bump "must_rescan"
977 */
978 break;
979 if (LIST_EMPTY(&vp->v_cleanblkhd) && LIST_EMPTY(&vp->v_dirtyblkhd))
980 break;
981 must_rescan = 0;
982 /*
983 * iterate the clean list
984 */
985 if (buf_iterprepare(vp, &local_iterblkhd, VBI_CLEAN)) {
986 goto try_dirty_list;
987 }
988 while (!LIST_EMPTY(&local_iterblkhd)) {
989 bp = LIST_FIRST(&local_iterblkhd);
990
991 LIST_REMOVE(bp, b_vnbufs);
992 LIST_INSERT_HEAD(&vp->v_cleanblkhd, bp, b_vnbufs);
993
994 /*
995 * some filesystems distinguish meta data blocks with a negative logical block #
996 */
997 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
998 continue;
999
1000 if ( (error = (int)buf_acquire_locked(bp, BAC_REMOVE | BAC_SKIP_LOCKED, slpflag, slptimeo)) ) {
1001 if (error == EDEADLK)
1002 /*
1003 * this buffer was marked B_LOCKED...
1004 * we didn't drop buf_mtxp, so we
1005 * we don't need to rescan
1006 */
1007 continue;
1008 if (error == EAGAIN) {
1009 /*
1010 * found a busy buffer... we blocked and
1011 * dropped buf_mtxp, so we're going to
1012 * need to rescan after this pass is completed
1013 */
1014 must_rescan++;
1015 continue;
1016 }
1017 /*
1018 * got some kind of 'real' error out of the msleep
1019 * in buf_acquire_locked, terminate the scan and return the error
1020 */
1021 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1022
1023 lck_mtx_unlock(buf_mtxp);
1024 return (error);
1025 }
1026 lck_mtx_unlock(buf_mtxp);
1027
1028 SET(bp->b_flags, B_INVAL);
1029 buf_brelse(bp);
1030
1031 lck_mtx_lock(buf_mtxp);
1032
1033 /*
1034 * by dropping buf_mtxp, we allow new
1035 * buffers to be added to the vnode list(s)
1036 * we'll have to rescan at least once more
1037 * if the queues aren't empty
1038 */
1039 must_rescan++;
1040 }
1041 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1042
1043 try_dirty_list:
1044 /*
1045 * Now iterate on dirty blks
1046 */
1047 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY)) {
1048 continue;
1049 }
1050 while (!LIST_EMPTY(&local_iterblkhd)) {
1051 bp = LIST_FIRST(&local_iterblkhd);
1052
1053 LIST_REMOVE(bp, b_vnbufs);
1054 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
1055
1056 /*
1057 * some filesystems distinguish meta data blocks with a negative logical block #
1058 */
1059 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
1060 continue;
1061
1062 if ( (error = (int)buf_acquire_locked(bp, BAC_REMOVE | BAC_SKIP_LOCKED, slpflag, slptimeo)) ) {
1063 if (error == EDEADLK)
1064 /*
1065 * this buffer was marked B_LOCKED...
1066 * we didn't drop buf_mtxp, so we
1067 * we don't need to rescan
1068 */
1069 continue;
1070 if (error == EAGAIN) {
1071 /*
1072 * found a busy buffer... we blocked and
1073 * dropped buf_mtxp, so we're going to
1074 * need to rescan after this pass is completed
1075 */
1076 must_rescan++;
1077 continue;
1078 }
1079 /*
1080 * got some kind of 'real' error out of the msleep
1081 * in buf_acquire_locked, terminate the scan and return the error
1082 */
1083 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1084
1085 lck_mtx_unlock(buf_mtxp);
1086 return (error);
1087 }
1088 lck_mtx_unlock(buf_mtxp);
1089
1090 SET(bp->b_flags, B_INVAL);
1091
1092 if (ISSET(bp->b_flags, B_DELWRI) && (flags & BUF_WRITE_DATA))
1093 (void) VNOP_BWRITE(bp);
1094 else
1095 buf_brelse(bp);
1096
1097 lck_mtx_lock(buf_mtxp);
1098 /*
1099 * by dropping buf_mtxp, we allow new
1100 * buffers to be added to the vnode list(s)
1101 * we'll have to rescan at least once more
1102 * if the queues aren't empty
1103 */
1104 must_rescan++;
1105 }
1106 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1107 }
1108 lck_mtx_unlock(buf_mtxp);
1109
1110 return (0);
1111 }
1112
1113 void
1114 buf_flushdirtyblks(vnode_t vp, int wait, int flags, char *msg) {
1115 buf_t bp;
1116 int writes_issued = 0;
1117 errno_t error;
1118 int busy = 0;
1119 struct buflists local_iterblkhd;
1120 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
1121
1122 if (flags & BUF_SKIP_LOCKED)
1123 lock_flags |= BAC_SKIP_LOCKED;
1124 if (flags & BUF_SKIP_NONLOCKED)
1125 lock_flags |= BAC_SKIP_NONLOCKED;
1126 loop:
1127 lck_mtx_lock(buf_mtxp);
1128
1129 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY) == 0) {
1130 while (!LIST_EMPTY(&local_iterblkhd)) {
1131 bp = LIST_FIRST(&local_iterblkhd);
1132 LIST_REMOVE(bp, b_vnbufs);
1133 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
1134
1135 if ((error = buf_acquire_locked(bp, lock_flags, 0, 0)) == EBUSY)
1136 busy++;
1137 if (error)
1138 continue;
1139 lck_mtx_unlock(buf_mtxp);
1140
1141 bp->b_flags &= ~B_LOCKED;
1142
1143 /*
1144 * Wait for I/O associated with indirect blocks to complete,
1145 * since there is no way to quickly wait for them below.
1146 */
1147 if ((bp->b_vp == vp) || (wait == 0))
1148 (void) buf_bawrite(bp);
1149 else
1150 (void) VNOP_BWRITE(bp);
1151 writes_issued++;
1152
1153 lck_mtx_lock(buf_mtxp);
1154 }
1155 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1156 }
1157 lck_mtx_unlock(buf_mtxp);
1158
1159 if (wait) {
1160 (void)vnode_waitforwrites(vp, 0, 0, 0, msg);
1161
1162 if (vp->v_dirtyblkhd.lh_first && busy) {
1163 /*
1164 * we had one or more BUSY buffers on
1165 * the dirtyblock list... most likely
1166 * these are due to delayed writes that
1167 * were moved to the bclean queue but
1168 * have not yet been 'written'.
1169 * if we issued some writes on the
1170 * previous pass, we try again immediately
1171 * if we didn't, we'll sleep for some time
1172 * to allow the state to change...
1173 */
1174 if (writes_issued == 0) {
1175 (void)tsleep((caddr_t)&vp->v_numoutput,
1176 PRIBIO + 1, "vnode_flushdirtyblks", hz/20);
1177 }
1178 writes_issued = 0;
1179 busy = 0;
1180
1181 goto loop;
1182 }
1183 }
1184 }
1185
1186
1187 /*
1188 * called with buf_mtxp held...
1189 * this lock protects the queue manipulation
1190 */
1191 static int
1192 buf_iterprepare(vnode_t vp, struct buflists *iterheadp, int flags)
1193 {
1194 struct buflists * listheadp;
1195
1196 if (flags & VBI_DIRTY)
1197 listheadp = &vp->v_dirtyblkhd;
1198 else
1199 listheadp = &vp->v_cleanblkhd;
1200
1201 while (vp->v_iterblkflags & VBI_ITER) {
1202 vp->v_iterblkflags |= VBI_ITERWANT;
1203 msleep(&vp->v_iterblkflags, buf_mtxp, 0, "buf_iterprepare", 0);
1204 }
1205 if (LIST_EMPTY(listheadp)) {
1206 LIST_INIT(iterheadp);
1207 return(EINVAL);
1208 }
1209 vp->v_iterblkflags |= VBI_ITER;
1210
1211 iterheadp->lh_first = listheadp->lh_first;
1212 listheadp->lh_first->b_vnbufs.le_prev = &iterheadp->lh_first;
1213 LIST_INIT(listheadp);
1214
1215 return(0);
1216 }
1217
1218 /*
1219 * called with buf_mtxp held...
1220 * this lock protects the queue manipulation
1221 */
1222 static void
1223 buf_itercomplete(vnode_t vp, struct buflists *iterheadp, int flags)
1224 {
1225 struct buflists * listheadp;
1226 buf_t bp;
1227
1228 if (flags & VBI_DIRTY)
1229 listheadp = &vp->v_dirtyblkhd;
1230 else
1231 listheadp = &vp->v_cleanblkhd;
1232
1233 while (!LIST_EMPTY(iterheadp)) {
1234 bp = LIST_FIRST(iterheadp);
1235 LIST_REMOVE(bp, b_vnbufs);
1236 LIST_INSERT_HEAD(listheadp, bp, b_vnbufs);
1237 }
1238 vp->v_iterblkflags &= ~VBI_ITER;
1239
1240 if (vp->v_iterblkflags & VBI_ITERWANT) {
1241 vp->v_iterblkflags &= ~VBI_ITERWANT;
1242 wakeup(&vp->v_iterblkflags);
1243 }
1244 }
1245
1246
1247 static void
1248 bremfree_locked(buf_t bp)
1249 {
1250 struct bqueues *dp = NULL;
1251 int whichq = -1;
1252
1253 /*
1254 * We only calculate the head of the freelist when removing
1255 * the last element of the list as that is the only time that
1256 * it is needed (e.g. to reset the tail pointer).
1257 *
1258 * NB: This makes an assumption about how tailq's are implemented.
1259 */
1260 if (bp->b_freelist.tqe_next == NULL) {
1261 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
1262 if (dp->tqh_last == &bp->b_freelist.tqe_next)
1263 break;
1264 if (dp == &bufqueues[BQUEUES])
1265 panic("bremfree: lost tail");
1266 }
1267 TAILQ_REMOVE(dp, bp, b_freelist);
1268 whichq = bp->b_whichq;
1269 #if BALANCE_QUEUES
1270 bufqdec(whichq);
1271 #endif
1272 bp->b_whichq = -1;
1273 bp->b_timestamp = 0;
1274 }
1275
1276 /*
1277 * Associate a buffer with a vnode.
1278 */
1279 static void
1280 bgetvp(vnode_t vp, buf_t bp)
1281 {
1282
1283 if (bp->b_vp != vp)
1284 panic("bgetvp: not free");
1285
1286 if (vp->v_type == VBLK || vp->v_type == VCHR)
1287 bp->b_dev = vp->v_rdev;
1288 else
1289 bp->b_dev = NODEV;
1290 /*
1291 * Insert onto list for new vnode.
1292 */
1293 lck_mtx_lock(buf_mtxp);
1294 bufinsvn(bp, &vp->v_cleanblkhd);
1295 lck_mtx_unlock(buf_mtxp);
1296 }
1297
1298 /*
1299 * Disassociate a buffer from a vnode.
1300 */
1301 static void
1302 brelvp(buf_t bp)
1303 {
1304 vnode_t vp;
1305
1306 if ((vp = bp->b_vp) == (vnode_t)NULL)
1307 panic("brelvp: NULL vp");
1308 /*
1309 * Delete from old vnode list, if on one.
1310 */
1311 lck_mtx_lock(buf_mtxp);
1312 if (bp->b_vnbufs.le_next != NOLIST)
1313 bufremvn(bp);
1314 lck_mtx_unlock(buf_mtxp);
1315
1316 bp->b_vp = (vnode_t)NULL;
1317 }
1318
1319 /*
1320 * Reassign a buffer from one vnode to another.
1321 * Used to assign file specific control information
1322 * (indirect blocks) to the vnode to which they belong.
1323 */
1324 static void
1325 buf_reassign(buf_t bp, vnode_t newvp)
1326 {
1327 register struct buflists *listheadp;
1328
1329 if (newvp == NULL) {
1330 printf("buf_reassign: NULL");
1331 return;
1332 }
1333 lck_mtx_lock(buf_mtxp);
1334
1335 /*
1336 * Delete from old vnode list, if on one.
1337 */
1338 if (bp->b_vnbufs.le_next != NOLIST)
1339 bufremvn(bp);
1340 /*
1341 * If dirty, put on list of dirty buffers;
1342 * otherwise insert onto list of clean buffers.
1343 */
1344 if (ISSET(bp->b_flags, B_DELWRI))
1345 listheadp = &newvp->v_dirtyblkhd;
1346 else
1347 listheadp = &newvp->v_cleanblkhd;
1348 bufinsvn(bp, listheadp);
1349
1350 lck_mtx_unlock(buf_mtxp);
1351 }
1352
1353 static __inline__ void
1354 bufhdrinit(buf_t bp)
1355 {
1356 bzero((char *)bp, sizeof *bp);
1357 bp->b_dev = NODEV;
1358 bp->b_rcred = NOCRED;
1359 bp->b_wcred = NOCRED;
1360 bp->b_vnbufs.le_next = NOLIST;
1361 bp->b_flags = B_INVAL;
1362
1363 return;
1364 }
1365
1366 /*
1367 * Initialize buffers and hash links for buffers.
1368 */
1369 __private_extern__ void
1370 bufinit()
1371 {
1372 buf_t bp;
1373 struct bqueues *dp;
1374 int i;
1375 int metabuf;
1376 long whichq;
1377
1378 nbuf = 0;
1379 /* Initialize the buffer queues ('freelists') and the hash table */
1380 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
1381 TAILQ_INIT(dp);
1382 bufhashtbl = hashinit(nbuf_hashelements, M_CACHE, &bufhash);
1383
1384 metabuf = max_nbuf_headers/8; /* reserved for meta buf */
1385
1386 /* Initialize the buffer headers */
1387 for (i = 0; i < max_nbuf_headers; i++) {
1388 nbuf++;
1389 bp = &buf[i];
1390 bufhdrinit(bp);
1391
1392 /*
1393 * metabuf buffer headers on the meta-data list and
1394 * rest of the buffer headers on the empty list
1395 */
1396 if (--metabuf)
1397 whichq = BQ_META;
1398 else
1399 whichq = BQ_EMPTY;
1400
1401 BLISTNONE(bp);
1402 dp = &bufqueues[whichq];
1403 binsheadfree(bp, dp, whichq);
1404 binshash(bp, &invalhash);
1405 }
1406
1407 boot_nbuf = nbuf;
1408
1409 for (; i < nbuf + niobuf; i++) {
1410 bp = &buf[i];
1411 bufhdrinit(bp);
1412 binsheadfree(bp, &iobufqueue, -1);
1413 }
1414
1415 /*
1416 * allocate lock group attribute and group
1417 */
1418 buf_mtx_grp_attr = lck_grp_attr_alloc_init();
1419 buf_mtx_grp = lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr);
1420
1421 /*
1422 * allocate the lock attribute
1423 */
1424 buf_mtx_attr = lck_attr_alloc_init();
1425
1426 /*
1427 * allocate and initialize mutex's for the buffer and iobuffer pools
1428 */
1429 buf_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1430 iobuffer_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1431
1432 if (iobuffer_mtxp == NULL)
1433 panic("couldn't create iobuffer mutex");
1434
1435 if (buf_mtxp == NULL)
1436 panic("couldn't create buf mutex");
1437
1438 /*
1439 * allocate and initialize cluster specific global locks...
1440 */
1441 cluster_init();
1442
1443 printf("using %d buffer headers and %d cluster IO buffer headers\n",
1444 nbuf, niobuf);
1445
1446 /* Set up zones used by the buffer cache */
1447 bufzoneinit();
1448
1449 /* start the bcleanbuf() thread */
1450 bcleanbuf_thread_init();
1451
1452 #if BALANCE_QUEUES
1453 {
1454 static void bufq_balance_thread_init();
1455 /* create a thread to do dynamic buffer queue balancing */
1456 bufq_balance_thread_init();
1457 }
1458 #endif /* notyet */
1459 }
1460
1461 static struct buf *
1462 bio_doread(vnode_t vp, daddr64_t blkno, int size, ucred_t cred, int async, int queuetype)
1463 {
1464 buf_t bp;
1465
1466 bp = buf_getblk(vp, blkno, size, 0, 0, queuetype);
1467
1468 /*
1469 * If buffer does not have data valid, start a read.
1470 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
1471 * Therefore, it's valid if it's I/O has completed or been delayed.
1472 */
1473 if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
1474 struct proc *p;
1475
1476 p = current_proc();
1477
1478 /* Start I/O for the buffer (keeping credentials). */
1479 SET(bp->b_flags, B_READ | async);
1480 if (cred != NOCRED && bp->b_rcred == NOCRED) {
1481 kauth_cred_ref(cred);
1482 bp->b_rcred = cred;
1483 }
1484
1485 VNOP_STRATEGY(bp);
1486
1487 trace(TR_BREADMISS, pack(vp, size), blkno);
1488
1489 /* Pay for the read. */
1490 if (p && p->p_stats)
1491 p->p_stats->p_ru.ru_inblock++; /* XXX */
1492
1493 if (async) {
1494 /*
1495 * since we asked for an ASYNC I/O
1496 * the biodone will do the brelse
1497 * we don't want to pass back a bp
1498 * that we don't 'own'
1499 */
1500 bp = NULL;
1501 }
1502 } else if (async) {
1503 buf_brelse(bp);
1504 bp = NULL;
1505 }
1506
1507 trace(TR_BREADHIT, pack(vp, size), blkno);
1508
1509 return (bp);
1510 }
1511
1512 /*
1513 * Perform the reads for buf_breadn() and buf_meta_breadn().
1514 * Trivial modification to the breada algorithm presented in Bach (p.55).
1515 */
1516 static errno_t
1517 do_breadn_for_type(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes,
1518 int nrablks, ucred_t cred, buf_t *bpp, int queuetype)
1519 {
1520 buf_t bp;
1521 int i;
1522
1523 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, queuetype);
1524
1525 /*
1526 * For each of the read-ahead blocks, start a read, if necessary.
1527 */
1528 for (i = 0; i < nrablks; i++) {
1529 /* If it's in the cache, just go on to next one. */
1530 if (incore(vp, rablks[i]))
1531 continue;
1532
1533 /* Get a buffer for the read-ahead block */
1534 (void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC, queuetype);
1535 }
1536
1537 /* Otherwise, we had to start a read for it; wait until it's valid. */
1538 return (buf_biowait(bp));
1539 }
1540
1541
1542 /*
1543 * Read a disk block.
1544 * This algorithm described in Bach (p.54).
1545 */
1546 errno_t
1547 buf_bread(vnode_t vp, daddr64_t blkno, int size, ucred_t cred, buf_t *bpp)
1548 {
1549 buf_t bp;
1550
1551 /* Get buffer for block. */
1552 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_READ);
1553
1554 /* Wait for the read to complete, and return result. */
1555 return (buf_biowait(bp));
1556 }
1557
1558 /*
1559 * Read a disk block. [bread() for meta-data]
1560 * This algorithm described in Bach (p.54).
1561 */
1562 errno_t
1563 buf_meta_bread(vnode_t vp, daddr64_t blkno, int size, ucred_t cred, buf_t *bpp)
1564 {
1565 buf_t bp;
1566
1567 /* Get buffer for block. */
1568 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_META);
1569
1570 /* Wait for the read to complete, and return result. */
1571 return (buf_biowait(bp));
1572 }
1573
1574 /*
1575 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1576 */
1577 errno_t
1578 buf_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, ucred_t cred, buf_t *bpp)
1579 {
1580 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_READ));
1581 }
1582
1583 /*
1584 * Read-ahead multiple disk blocks. The first is sync, the rest async.
1585 * [buf_breadn() for meta-data]
1586 */
1587 errno_t
1588 buf_meta_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, ucred_t cred, buf_t *bpp)
1589 {
1590 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_META));
1591 }
1592
1593 /*
1594 * Block write. Described in Bach (p.56)
1595 */
1596 errno_t
1597 buf_bwrite(buf_t bp)
1598 {
1599 int sync, wasdelayed;
1600 errno_t rv;
1601 proc_t p = current_proc();
1602 vnode_t vp = bp->b_vp;
1603
1604 if (bp->b_datap == 0) {
1605 if (brecover_data(bp) == 0)
1606 return (0);
1607 }
1608 /* Remember buffer type, to switch on it later. */
1609 sync = !ISSET(bp->b_flags, B_ASYNC);
1610 wasdelayed = ISSET(bp->b_flags, B_DELWRI);
1611 CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
1612
1613 if (wasdelayed)
1614 OSAddAtomic(-1, &nbdwrite);
1615
1616 if (!sync) {
1617 /*
1618 * If not synchronous, pay for the I/O operation and make
1619 * sure the buf is on the correct vnode queue. We have
1620 * to do this now, because if we don't, the vnode may not
1621 * be properly notified that its I/O has completed.
1622 */
1623 if (wasdelayed)
1624 buf_reassign(bp, vp);
1625 else
1626 if (p && p->p_stats)
1627 p->p_stats->p_ru.ru_oublock++; /* XXX */
1628 }
1629 trace(TR_BUFWRITE, pack(vp, bp->b_bcount), bp->b_lblkno);
1630
1631 /* Initiate disk write. Make sure the appropriate party is charged. */
1632
1633 OSAddAtomic(1, &vp->v_numoutput);
1634
1635 VNOP_STRATEGY(bp);
1636
1637 if (sync) {
1638 /*
1639 * If I/O was synchronous, wait for it to complete.
1640 */
1641 rv = buf_biowait(bp);
1642
1643 /*
1644 * Pay for the I/O operation, if it's not been paid for, and
1645 * make sure it's on the correct vnode queue. (async operatings
1646 * were payed for above.)
1647 */
1648 if (wasdelayed)
1649 buf_reassign(bp, vp);
1650 else
1651 if (p && p->p_stats)
1652 p->p_stats->p_ru.ru_oublock++; /* XXX */
1653
1654 /* Release the buffer. */
1655 // XXXdbg - only if the unused bit is set
1656 if (!ISSET(bp->b_flags, B_NORELSE)) {
1657 buf_brelse(bp);
1658 } else {
1659 CLR(bp->b_flags, B_NORELSE);
1660 }
1661
1662 return (rv);
1663 } else {
1664 return (0);
1665 }
1666 }
1667
1668 int
1669 vn_bwrite(ap)
1670 struct vnop_bwrite_args *ap;
1671 {
1672 return (buf_bwrite(ap->a_bp));
1673 }
1674
1675 /*
1676 * Delayed write.
1677 *
1678 * The buffer is marked dirty, but is not queued for I/O.
1679 * This routine should be used when the buffer is expected
1680 * to be modified again soon, typically a small write that
1681 * partially fills a buffer.
1682 *
1683 * NB: magnetic tapes cannot be delayed; they must be
1684 * written in the order that the writes are requested.
1685 *
1686 * Described in Leffler, et al. (pp. 208-213).
1687 *
1688 * Note: With the abilitty to allocate additional buffer
1689 * headers, we can get in to the situation where "too" many
1690 * buf_bdwrite()s can create situation where the kernel can create
1691 * buffers faster than the disks can service. Doing a buf_bawrite() in
1692 * cases were we have "too many" outstanding buf_bdwrite()s avoids that.
1693 */
1694 __private_extern__ int
1695 bdwrite_internal(buf_t bp, int return_error)
1696 {
1697 proc_t p = current_proc();
1698 vnode_t vp = bp->b_vp;
1699
1700 /*
1701 * If the block hasn't been seen before:
1702 * (1) Mark it as having been seen,
1703 * (2) Charge for the write.
1704 * (3) Make sure it's on its vnode's correct block list,
1705 */
1706 if (!ISSET(bp->b_flags, B_DELWRI)) {
1707 SET(bp->b_flags, B_DELWRI);
1708 if (p && p->p_stats)
1709 p->p_stats->p_ru.ru_oublock++; /* XXX */
1710 OSAddAtomic(1, &nbdwrite);
1711 buf_reassign(bp, vp);
1712 }
1713
1714 /* If this is a tape block, write it the block now. */
1715 if (ISSET(bp->b_flags, B_TAPE)) {
1716 VNOP_BWRITE(bp);
1717 return (0);
1718 }
1719
1720 /*
1721 * if we're not LOCKED, but the total number of delayed writes
1722 * has climbed above 75% of the total buffers in the system
1723 * return an error if the caller has indicated that it can
1724 * handle one in this case, otherwise schedule the I/O now
1725 * this is done to prevent us from allocating tons of extra
1726 * buffers when dealing with virtual disks (i.e. DiskImages),
1727 * because additional buffers are dynamically allocated to prevent
1728 * deadlocks from occurring
1729 *
1730 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
1731 * buffer is part of a transaction and can't go to disk until
1732 * the LOCKED bit is cleared.
1733 */
1734 if (!ISSET(bp->b_flags, B_LOCKED) && nbdwrite > ((nbuf/4)*3)) {
1735 if (return_error)
1736 return (EAGAIN);
1737 /*
1738 * If the vnode has "too many" write operations in progress
1739 * wait for them to finish the IO
1740 */
1741 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, (char *)"buf_bdwrite");
1742
1743 return (buf_bawrite(bp));
1744 }
1745
1746 /* Otherwise, the "write" is done, so mark and release the buffer. */
1747 SET(bp->b_flags, B_DONE);
1748 buf_brelse(bp);
1749 return (0);
1750 }
1751
1752 errno_t
1753 buf_bdwrite(buf_t bp)
1754 {
1755 return (bdwrite_internal(bp, 0));
1756 }
1757
1758
1759 /*
1760 * Asynchronous block write; just an asynchronous buf_bwrite().
1761 *
1762 * Note: With the abilitty to allocate additional buffer
1763 * headers, we can get in to the situation where "too" many
1764 * buf_bawrite()s can create situation where the kernel can create
1765 * buffers faster than the disks can service.
1766 * We limit the number of "in flight" writes a vnode can have to
1767 * avoid this.
1768 */
1769 static int
1770 bawrite_internal(buf_t bp, int throttle)
1771 {
1772 vnode_t vp = bp->b_vp;
1773
1774 if (vp) {
1775 if (throttle)
1776 /*
1777 * If the vnode has "too many" write operations in progress
1778 * wait for them to finish the IO
1779 */
1780 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, (const char *)"buf_bawrite");
1781 else if (vp->v_numoutput >= VNODE_ASYNC_THROTTLE)
1782 /*
1783 * return to the caller and
1784 * let him decide what to do
1785 */
1786 return (EWOULDBLOCK);
1787 }
1788 SET(bp->b_flags, B_ASYNC);
1789
1790 return (VNOP_BWRITE(bp));
1791 }
1792
1793 errno_t
1794 buf_bawrite(buf_t bp)
1795 {
1796 return (bawrite_internal(bp, 1));
1797 }
1798
1799
1800 /*
1801 * Release a buffer on to the free lists.
1802 * Described in Bach (p. 46).
1803 */
1804 void
1805 buf_brelse(buf_t bp)
1806 {
1807 struct bqueues *bufq;
1808 long whichq;
1809 upl_t upl;
1810 int need_wakeup = 0;
1811 int need_bp_wakeup = 0;
1812
1813
1814 if (bp->b_whichq != -1 || !(bp->b_lflags & BL_BUSY))
1815 panic("buf_brelse: bad buffer = %x\n", bp);
1816
1817 #ifdef JOE_DEBUG
1818 bp->b_stackbrelse[0] = __builtin_return_address(0);
1819 bp->b_stackbrelse[1] = __builtin_return_address(1);
1820 bp->b_stackbrelse[2] = __builtin_return_address(2);
1821 bp->b_stackbrelse[3] = __builtin_return_address(3);
1822 bp->b_stackbrelse[4] = __builtin_return_address(4);
1823 bp->b_stackbrelse[5] = __builtin_return_address(5);
1824
1825 bp->b_lastbrelse = current_thread();
1826 bp->b_tag = 0;
1827 #endif
1828 if (bp->b_lflags & BL_IOBUF) {
1829 free_io_buf(bp);
1830 return;
1831 }
1832
1833 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_START,
1834 bp->b_lblkno * PAGE_SIZE, (int)bp, (int)bp->b_datap,
1835 bp->b_flags, 0);
1836
1837 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
1838
1839 /*
1840 * if we're invalidating a buffer that has the B_FILTER bit
1841 * set then call the b_iodone function so it gets cleaned
1842 * up properly.
1843 *
1844 * the HFS journal code depends on this
1845 */
1846 if (ISSET(bp->b_flags, B_META) && ISSET(bp->b_flags, B_INVAL)) {
1847 if (ISSET(bp->b_flags, B_FILTER)) { /* if necessary, call out */
1848 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
1849 void *arg = (void *)bp->b_transaction;
1850
1851 CLR(bp->b_flags, B_FILTER); /* but note callout done */
1852 bp->b_iodone = NULL;
1853 bp->b_transaction = NULL;
1854
1855 if (iodone_func == NULL) {
1856 panic("brelse: bp @ 0x%x has NULL b_iodone!\n", bp);
1857 }
1858 (*iodone_func)(bp, arg);
1859 }
1860 }
1861 /*
1862 * I/O is done. Cleanup the UPL state
1863 */
1864 upl = bp->b_upl;
1865
1866 if ( !ISSET(bp->b_flags, B_META) && UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
1867 kern_return_t kret;
1868 int upl_flags;
1869
1870 if ( (upl == NULL) ) {
1871 if ( !ISSET(bp->b_flags, B_INVAL)) {
1872 kret = ubc_create_upl(bp->b_vp,
1873 ubc_blktooff(bp->b_vp, bp->b_lblkno),
1874 bp->b_bufsize,
1875 &upl,
1876 NULL,
1877 UPL_PRECIOUS);
1878
1879 if (kret != KERN_SUCCESS)
1880 panic("brelse: Failed to create UPL");
1881 #ifdef UPL_DEBUG
1882 upl_ubc_alias_set(upl, bp, 5);
1883 #endif /* UPL_DEBUG */
1884 }
1885 } else {
1886 if (bp->b_datap) {
1887 kret = ubc_upl_unmap(upl);
1888
1889 if (kret != KERN_SUCCESS)
1890 panic("ubc_upl_unmap failed");
1891 bp->b_datap = (uintptr_t)NULL;
1892 }
1893 }
1894 if (upl) {
1895 if (bp->b_flags & (B_ERROR | B_INVAL)) {
1896 if (bp->b_flags & (B_READ | B_INVAL))
1897 upl_flags = UPL_ABORT_DUMP_PAGES;
1898 else
1899 upl_flags = 0;
1900
1901 ubc_upl_abort(upl, upl_flags);
1902 } else {
1903 if (ISSET(bp->b_flags, B_DELWRI | B_WASDIRTY))
1904 upl_flags = UPL_COMMIT_SET_DIRTY ;
1905 else
1906 upl_flags = UPL_COMMIT_CLEAR_DIRTY ;
1907
1908 ubc_upl_commit_range(upl, 0, bp->b_bufsize, upl_flags |
1909 UPL_COMMIT_INACTIVATE | UPL_COMMIT_FREE_ON_EMPTY);
1910 }
1911 bp->b_upl = NULL;
1912 }
1913 } else {
1914 if ( (upl) )
1915 panic("brelse: UPL set for non VREG; vp=%x", bp->b_vp);
1916 }
1917
1918 /*
1919 * If it's locked, don't report an error; try again later.
1920 */
1921 if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
1922 CLR(bp->b_flags, B_ERROR);
1923 /*
1924 * If it's not cacheable, or an error, mark it invalid.
1925 */
1926 if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
1927 SET(bp->b_flags, B_INVAL);
1928
1929 if ((bp->b_bufsize <= 0) || ISSET(bp->b_flags, B_INVAL)) {
1930 /*
1931 * If it's invalid or empty, dissociate it from its vnode
1932 * and put on the head of the appropriate queue.
1933 */
1934 if (bp->b_vp)
1935 brelvp(bp);
1936
1937 if (ISSET(bp->b_flags, B_DELWRI))
1938 OSAddAtomic(-1, &nbdwrite);
1939
1940 CLR(bp->b_flags, (B_DELWRI | B_LOCKED | B_AGE | B_ASYNC | B_NOCACHE));
1941 /*
1942 * Determine which queue the buffer should be on, then put it there.
1943 */
1944 if (bp->b_bufsize <= 0)
1945 whichq = BQ_EMPTY; /* no data */
1946 else if (ISSET(bp->b_flags, B_META))
1947 whichq = BQ_META; /* meta-data */
1948 else
1949 whichq = BQ_AGE; /* invalid data */
1950 bufq = &bufqueues[whichq];
1951
1952 lck_mtx_lock(buf_mtxp);
1953
1954 binsheadfree(bp, bufq, whichq);
1955 } else {
1956 /*
1957 * It has valid data. Put it on the end of the appropriate
1958 * queue, so that it'll stick around for as long as possible.
1959 */
1960 if (ISSET(bp->b_flags, B_LOCKED))
1961 whichq = BQ_LOCKED; /* locked in core */
1962 else if (ISSET(bp->b_flags, B_META))
1963 whichq = BQ_META; /* meta-data */
1964 else if (ISSET(bp->b_flags, B_AGE))
1965 whichq = BQ_AGE; /* stale but valid data */
1966 else
1967 whichq = BQ_LRU; /* valid data */
1968 bufq = &bufqueues[whichq];
1969
1970 CLR(bp->b_flags, (B_AGE | B_ASYNC | B_NOCACHE));
1971
1972 lck_mtx_lock(buf_mtxp);
1973
1974 binstailfree(bp, bufq, whichq);
1975 }
1976 if (needbuffer) {
1977 /*
1978 * needbuffer is a global
1979 * we're currently using buf_mtxp to protect it
1980 * delay doing the actual wakeup until after
1981 * we drop buf_mtxp
1982 */
1983 needbuffer = 0;
1984 need_wakeup = 1;
1985 }
1986 if (ISSET(bp->b_lflags, BL_WANTED)) {
1987 /*
1988 * delay the actual wakeup until after we
1989 * clear BL_BUSY and we've dropped buf_mtxp
1990 */
1991 need_bp_wakeup = 1;
1992 }
1993 /*
1994 * Unlock the buffer.
1995 */
1996 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
1997
1998 lck_mtx_unlock(buf_mtxp);
1999
2000 if (need_wakeup) {
2001 /*
2002 * Wake up any processes waiting for any buffer to become free.
2003 */
2004 wakeup(&needbuffer);
2005 }
2006 if (need_bp_wakeup) {
2007 /*
2008 * Wake up any proceeses waiting for _this_ buffer to become free.
2009 */
2010 wakeup(bp);
2011 }
2012 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_END,
2013 (int)bp, (int)bp->b_datap, bp->b_flags, 0, 0);
2014 }
2015
2016 /*
2017 * Determine if a block is in the cache.
2018 * Just look on what would be its hash chain. If it's there, return
2019 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2020 * we normally don't return the buffer, unless the caller explicitly
2021 * wants us to.
2022 */
2023 static boolean_t
2024 incore(vnode_t vp, daddr64_t blkno)
2025 {
2026 boolean_t retval;
2027
2028 lck_mtx_lock(buf_mtxp);
2029
2030 if (incore_locked(vp, blkno))
2031 retval = TRUE;
2032 else
2033 retval = FALSE;
2034 lck_mtx_unlock(buf_mtxp);
2035
2036 return (retval);
2037 }
2038
2039
2040 static buf_t
2041 incore_locked(vnode_t vp, daddr64_t blkno)
2042 {
2043 struct buf *bp;
2044
2045 bp = BUFHASH(vp, blkno)->lh_first;
2046
2047 /* Search hash chain */
2048 for (; bp != NULL; bp = bp->b_hash.le_next) {
2049 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
2050 !ISSET(bp->b_flags, B_INVAL)) {
2051 return (bp);
2052 }
2053 }
2054 return (0);
2055 }
2056
2057
2058 /* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
2059 /*
2060 * Get a block of requested size that is associated with
2061 * a given vnode and block offset. If it is found in the
2062 * block cache, mark it as having been found, make it busy
2063 * and return it. Otherwise, return an empty block of the
2064 * correct size. It is up to the caller to insure that the
2065 * cached blocks be of the correct size.
2066 */
2067 buf_t
2068 buf_getblk(vnode_t vp, daddr64_t blkno, int size, int slpflag, int slptimeo, int operation)
2069 {
2070 buf_t bp;
2071 int err;
2072 upl_t upl;
2073 upl_page_info_t *pl;
2074 kern_return_t kret;
2075 int ret_only_valid;
2076 struct timespec ts;
2077 int upl_flags;
2078
2079 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_START,
2080 (int)(blkno * PAGE_SIZE), size, operation, 0, 0);
2081
2082 ret_only_valid = operation & BLK_ONLYVALID;
2083 operation &= ~BLK_ONLYVALID;
2084 start:
2085 lck_mtx_lock(buf_mtxp);
2086 start_locked:
2087 if ((bp = incore_locked(vp, blkno))) {
2088 /*
2089 * Found in the Buffer Cache
2090 */
2091 if (ISSET(bp->b_lflags, BL_BUSY)) {
2092 /*
2093 * but is busy
2094 */
2095 switch (operation) {
2096 case BLK_READ:
2097 case BLK_WRITE:
2098 case BLK_META:
2099 SET(bp->b_lflags, BL_WANTED);
2100 bufstats.bufs_busyincore++;
2101
2102 /*
2103 * don't retake the mutex after being awakened...
2104 * the time out is in msecs
2105 */
2106 ts.tv_sec = (slptimeo/1000);
2107 ts.tv_nsec = (slptimeo % 1000) * 10 * NSEC_PER_USEC * 1000;
2108
2109 err = msleep(bp, buf_mtxp, slpflag | PDROP | (PRIBIO + 1), "buf_getblk", &ts);
2110
2111 /*
2112 * Callers who call with PCATCH or timeout are
2113 * willing to deal with the NULL pointer
2114 */
2115 if (err && ((slpflag & PCATCH) || ((err == EWOULDBLOCK) && slptimeo)))
2116 return (NULL);
2117 goto start;
2118 /*NOTREACHED*/
2119 break;
2120
2121 default:
2122 /*
2123 * unknown operation requested
2124 */
2125 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation);
2126 /*NOTREACHED*/
2127 break;
2128 }
2129 } else {
2130 /*
2131 * buffer in core and not busy
2132 */
2133 if ( (bp->b_upl) )
2134 panic("buffer has UPL, but not marked BUSY: %x", bp);
2135 SET(bp->b_lflags, BL_BUSY);
2136 SET(bp->b_flags, B_CACHE);
2137 #ifdef JOE_DEBUG
2138 bp->b_owner = current_thread();
2139 bp->b_tag = 1;
2140 #endif
2141 bremfree_locked(bp);
2142 bufstats.bufs_incore++;
2143
2144 lck_mtx_unlock(buf_mtxp);
2145
2146 if ( !ret_only_valid)
2147 allocbuf(bp, size);
2148
2149 upl_flags = 0;
2150 switch (operation) {
2151 case BLK_WRITE:
2152 /*
2153 * "write" operation: let the UPL subsystem
2154 * know that we intend to modify the buffer
2155 * cache pages we're gathering.
2156 */
2157 upl_flags |= UPL_WILL_MODIFY;
2158 case BLK_READ:
2159 upl_flags |= UPL_PRECIOUS;
2160 if (UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
2161 kret = ubc_create_upl(vp,
2162 ubc_blktooff(vp, bp->b_lblkno),
2163 bp->b_bufsize,
2164 &upl,
2165 &pl,
2166 upl_flags);
2167 if (kret != KERN_SUCCESS)
2168 panic("Failed to create UPL");
2169
2170 bp->b_upl = upl;
2171
2172 if (upl_valid_page(pl, 0)) {
2173 if (upl_dirty_page(pl, 0))
2174 SET(bp->b_flags, B_WASDIRTY);
2175 else
2176 CLR(bp->b_flags, B_WASDIRTY);
2177 } else
2178 CLR(bp->b_flags, (B_DONE | B_CACHE | B_WASDIRTY | B_DELWRI));
2179
2180 kret = ubc_upl_map(upl, (vm_address_t *)&(bp->b_datap));
2181
2182 if (kret != KERN_SUCCESS)
2183 panic("getblk: ubc_upl_map() failed with (%d)", kret);
2184 }
2185 break;
2186
2187 case BLK_META:
2188 /*
2189 * VM is not involved in IO for the meta data
2190 * buffer already has valid data
2191 */
2192 break;
2193
2194 default:
2195 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation);
2196 /*NOTREACHED*/
2197 break;
2198 }
2199 }
2200 } else { /* not incore() */
2201 int queue = BQ_EMPTY; /* Start with no preference */
2202
2203 if (ret_only_valid) {
2204 lck_mtx_unlock(buf_mtxp);
2205 return (NULL);
2206 }
2207
2208 if ((UBCINVALID(vp)) || !(UBCINFOEXISTS(vp)))
2209 operation = BLK_META;
2210
2211 if ((bp = getnewbuf(slpflag, slptimeo, &queue)) == NULL)
2212 goto start_locked;
2213
2214 /*
2215 * getnewbuf may block for a number of different reasons...
2216 * if it does, it's then possible for someone else to
2217 * create a buffer for the same block and insert it into
2218 * the hash... if we see it incore at this point we dump
2219 * the buffer we were working on and start over
2220 */
2221 if (incore_locked(vp, blkno)) {
2222 SET(bp->b_flags, B_INVAL);
2223 binshash(bp, &invalhash);
2224
2225 lck_mtx_unlock(buf_mtxp);
2226
2227 buf_brelse(bp);
2228 goto start;
2229 }
2230 /*
2231 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
2232 * CALLED! BE CAREFUL.
2233 */
2234
2235 /*
2236 * mark the buffer as B_META if indicated
2237 * so that when buffer is released it will goto META queue
2238 */
2239 if (operation == BLK_META)
2240 SET(bp->b_flags, B_META);
2241
2242 bp->b_blkno = bp->b_lblkno = blkno;
2243 bp->b_vp = vp;
2244
2245 /*
2246 * Insert in the hash so that incore() can find it
2247 */
2248 binshash(bp, BUFHASH(vp, blkno));
2249
2250 lck_mtx_unlock(buf_mtxp);
2251
2252 bgetvp(vp, bp);
2253
2254 allocbuf(bp, size);
2255
2256 upl_flags = 0;
2257 switch (operation) {
2258 case BLK_META:
2259 /*
2260 * buffer data is invalid...
2261 *
2262 * I don't want to have to retake buf_mtxp,
2263 * so the miss and vmhits counters are done
2264 * with Atomic updates... all other counters
2265 * in bufstats are protected with either
2266 * buf_mtxp or iobuffer_mtxp
2267 */
2268 OSAddAtomic(1, &bufstats.bufs_miss);
2269 break;
2270
2271 case BLK_WRITE:
2272 /*
2273 * "write" operation: let the UPL subsystem know
2274 * that we intend to modify the buffer cache pages
2275 * we're gathering.
2276 */
2277 upl_flags |= UPL_WILL_MODIFY;
2278 case BLK_READ:
2279 { off_t f_offset;
2280 size_t contig_bytes;
2281 int bmap_flags;
2282
2283 if ( (bp->b_upl) )
2284 panic("bp already has UPL: %x",bp);
2285
2286 f_offset = ubc_blktooff(vp, blkno);
2287
2288 upl_flags |= UPL_PRECIOUS;
2289 kret = ubc_create_upl(vp,
2290 f_offset,
2291 bp->b_bufsize,
2292 &upl,
2293 &pl,
2294 upl_flags);
2295
2296 if (kret != KERN_SUCCESS)
2297 panic("Failed to create UPL");
2298 #ifdef UPL_DEBUG
2299 upl_ubc_alias_set(upl, bp, 4);
2300 #endif /* UPL_DEBUG */
2301 bp->b_upl = upl;
2302
2303 if (upl_valid_page(pl, 0)) {
2304
2305 if (operation == BLK_READ)
2306 bmap_flags = VNODE_READ;
2307 else
2308 bmap_flags = VNODE_WRITE;
2309
2310 SET(bp->b_flags, B_CACHE | B_DONE);
2311
2312 OSAddAtomic(1, &bufstats.bufs_vmhits);
2313
2314 bp->b_validoff = 0;
2315 bp->b_dirtyoff = 0;
2316
2317 if (upl_dirty_page(pl, 0)) {
2318 /* page is dirty */
2319 SET(bp->b_flags, B_WASDIRTY);
2320
2321 bp->b_validend = bp->b_bcount;
2322 bp->b_dirtyend = bp->b_bcount;
2323 } else {
2324 /* page is clean */
2325 bp->b_validend = bp->b_bcount;
2326 bp->b_dirtyend = 0;
2327 }
2328 /*
2329 * try to recreate the physical block number associated with
2330 * this buffer...
2331 */
2332 if (VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))
2333 panic("getblk: VNOP_BLOCKMAP failed");
2334 /*
2335 * if the extent represented by this buffer
2336 * is not completely physically contiguous on
2337 * disk, than we can't cache the physical mapping
2338 * in the buffer header
2339 */
2340 if ((long)contig_bytes < bp->b_bcount)
2341 bp->b_blkno = bp->b_lblkno;
2342 } else {
2343 OSAddAtomic(1, &bufstats.bufs_miss);
2344 }
2345 kret = ubc_upl_map(upl, (vm_address_t *)&(bp->b_datap));
2346
2347 if (kret != KERN_SUCCESS)
2348 panic("getblk: ubc_upl_map() failed with (%d)", kret);
2349 break;
2350 }
2351 default:
2352 panic("getblk: paging or unknown operation - %x", operation);
2353 /*NOTREACHED*/
2354 break;
2355 }
2356 }
2357 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_END,
2358 (int)bp, (int)bp->b_datap, bp->b_flags, 3, 0);
2359
2360 #ifdef JOE_DEBUG
2361 bp->b_stackgetblk[0] = __builtin_return_address(0);
2362 bp->b_stackgetblk[1] = __builtin_return_address(1);
2363 bp->b_stackgetblk[2] = __builtin_return_address(2);
2364 bp->b_stackgetblk[3] = __builtin_return_address(3);
2365 bp->b_stackgetblk[4] = __builtin_return_address(4);
2366 bp->b_stackgetblk[5] = __builtin_return_address(5);
2367 #endif
2368 return (bp);
2369 }
2370
2371 /*
2372 * Get an empty, disassociated buffer of given size.
2373 */
2374 buf_t
2375 buf_geteblk(size)
2376 int size;
2377 {
2378 buf_t bp;
2379 int queue = BQ_EMPTY;
2380
2381 lck_mtx_lock(buf_mtxp);
2382
2383 while ((bp = getnewbuf(0, 0, &queue)) == 0)
2384 ;
2385 SET(bp->b_flags, (B_META|B_INVAL));
2386
2387 #if DIAGNOSTIC
2388 assert(queue == BQ_EMPTY);
2389 #endif /* DIAGNOSTIC */
2390 /* XXX need to implement logic to deal with other queues */
2391
2392 binshash(bp, &invalhash);
2393 bufstats.bufs_eblk++;
2394
2395 lck_mtx_unlock(buf_mtxp);
2396
2397 allocbuf(bp, size);
2398
2399 return (bp);
2400 }
2401
2402 /*
2403 * Zones for the meta data buffers
2404 */
2405
2406 #define MINMETA 512
2407 #define MAXMETA 4096
2408
2409 struct meta_zone_entry {
2410 zone_t mz_zone;
2411 vm_size_t mz_size;
2412 vm_size_t mz_max;
2413 char *mz_name;
2414 };
2415
2416 struct meta_zone_entry meta_zones[] = {
2417 {NULL, (MINMETA * 1), 128 * (MINMETA * 1), "buf.512" },
2418 {NULL, (MINMETA * 2), 64 * (MINMETA * 2), "buf.1024" },
2419 {NULL, (MINMETA * 4), 16 * (MINMETA * 4), "buf.2048" },
2420 {NULL, (MINMETA * 8), 512 * (MINMETA * 8), "buf.4096" },
2421 {NULL, 0, 0, "" } /* End */
2422 };
2423
2424 /*
2425 * Initialize the meta data zones
2426 */
2427 static void
2428 bufzoneinit(void)
2429 {
2430 int i;
2431
2432 for (i = 0; meta_zones[i].mz_size != 0; i++) {
2433 meta_zones[i].mz_zone =
2434 zinit(meta_zones[i].mz_size,
2435 meta_zones[i].mz_max,
2436 PAGE_SIZE,
2437 meta_zones[i].mz_name);
2438 }
2439 buf_hdr_zone = zinit(sizeof(struct buf), 32, PAGE_SIZE, "buf headers");
2440 }
2441
2442 static __inline__ zone_t
2443 getbufzone(size_t size)
2444 {
2445 int i;
2446
2447 if ((size % 512) || (size < MINMETA) || (size > MAXMETA))
2448 panic("getbufzone: incorect size = %d", size);
2449
2450 for (i = 0; meta_zones[i].mz_size != 0; i++) {
2451 if (meta_zones[i].mz_size >= size)
2452 break;
2453 }
2454
2455 return (meta_zones[i].mz_zone);
2456 }
2457
2458 /*
2459 * With UBC, there is no need to expand / shrink the file data
2460 * buffer. The VM uses the same pages, hence no waste.
2461 * All the file data buffers can have one size.
2462 * In fact expand / shrink would be an expensive operation.
2463 *
2464 * Only exception to this is meta-data buffers. Most of the
2465 * meta data operations are smaller than PAGE_SIZE. Having the
2466 * meta-data buffers grow and shrink as needed, optimizes use
2467 * of the kernel wired memory.
2468 */
2469
2470 int
2471 allocbuf(buf_t bp, int size)
2472 {
2473 vm_size_t desired_size;
2474
2475 desired_size = roundup(size, CLBYTES);
2476
2477 if (desired_size < PAGE_SIZE)
2478 desired_size = PAGE_SIZE;
2479 if (desired_size > MAXBSIZE)
2480 panic("allocbuf: buffer larger than MAXBSIZE requested");
2481
2482 if (ISSET(bp->b_flags, B_META)) {
2483 zone_t zprev, z;
2484 int nsize = roundup(size, MINMETA);
2485
2486 if (bp->b_datap) {
2487 vm_offset_t elem = (vm_offset_t)bp->b_datap;
2488
2489 if (ISSET(bp->b_flags, B_ZALLOC)) {
2490 if (bp->b_bufsize < nsize) {
2491 /* reallocate to a bigger size */
2492
2493 zprev = getbufzone(bp->b_bufsize);
2494 if (nsize <= MAXMETA) {
2495 desired_size = nsize;
2496 z = getbufzone(nsize);
2497 bp->b_datap = (uintptr_t)zalloc(z);
2498 } else {
2499 bp->b_datap = (uintptr_t)NULL;
2500 kmem_alloc_wired(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2501 CLR(bp->b_flags, B_ZALLOC);
2502 }
2503 bcopy((void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
2504 zfree(zprev, (void *)elem);
2505 } else {
2506 desired_size = bp->b_bufsize;
2507 }
2508
2509 } else {
2510 if ((vm_size_t)bp->b_bufsize < desired_size) {
2511 /* reallocate to a bigger size */
2512 bp->b_datap = (uintptr_t)NULL;
2513 kmem_alloc_wired(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2514 bcopy((const void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
2515 kmem_free(kernel_map, elem, bp->b_bufsize);
2516 } else {
2517 desired_size = bp->b_bufsize;
2518 }
2519 }
2520 } else {
2521 /* new allocation */
2522 if (nsize <= MAXMETA) {
2523 desired_size = nsize;
2524 z = getbufzone(nsize);
2525 bp->b_datap = (uintptr_t)zalloc(z);
2526 SET(bp->b_flags, B_ZALLOC);
2527 } else
2528 kmem_alloc_wired(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size);
2529 }
2530 }
2531 bp->b_bufsize = desired_size;
2532 bp->b_bcount = size;
2533
2534 return (0);
2535 }
2536
2537 /*
2538 * Get a new buffer from one of the free lists.
2539 *
2540 * Request for a queue is passes in. The queue from which the buffer was taken
2541 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
2542 * BQUEUE means no preference. Use heuristics in that case.
2543 * Heuristics is as follows:
2544 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
2545 * If none available block till one is made available.
2546 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
2547 * Pick the most stale buffer.
2548 * If found buffer was marked delayed write, start the async. write
2549 * and restart the search.
2550 * Initialize the fields and disassociate the buffer from the vnode.
2551 * Remove the buffer from the hash. Return the buffer and the queue
2552 * on which it was found.
2553 *
2554 * buf_mtxp is held upon entry
2555 * returns with buf_mtxp locked
2556 */
2557
2558 static buf_t
2559 getnewbuf(int slpflag, int slptimeo, int * queue)
2560 {
2561 buf_t bp;
2562 buf_t lru_bp;
2563 buf_t age_bp;
2564 buf_t meta_bp;
2565 int age_time, lru_time, bp_time, meta_time;
2566 int req = *queue; /* save it for restarts */
2567 struct timespec ts;
2568
2569 start:
2570 /*
2571 * invalid request gets empty queue
2572 */
2573 if ((*queue > BQUEUES) || (*queue < 0)
2574 || (*queue == BQ_LAUNDRY) || (*queue == BQ_LOCKED))
2575 *queue = BQ_EMPTY;
2576 /* need to grow number of bufs, add another one rather than recycling */
2577 if (nbuf < max_nbuf_headers) {
2578 /*
2579 * Increment count now as lock
2580 * is dropped for allocation.
2581 * That avoids over commits
2582 */
2583 nbuf++;
2584 goto add_newbufs;
2585 }
2586
2587 /*
2588 * (*queue == BQUEUES) means no preference
2589 */
2590 if (*queue != BQUEUES) {
2591 /* Try for the requested queue first */
2592 bp = bufqueues[*queue].tqh_first;
2593 if (bp)
2594 goto found;
2595 }
2596
2597 /* Unable to use requested queue */
2598 age_bp = bufqueues[BQ_AGE].tqh_first;
2599 lru_bp = bufqueues[BQ_LRU].tqh_first;
2600 meta_bp = bufqueues[BQ_META].tqh_first;
2601
2602 if (!age_bp && !lru_bp && !meta_bp) {
2603 /*
2604 * Unavailble on AGE or LRU or META queues
2605 * Try the empty list first
2606 */
2607 bp = bufqueues[BQ_EMPTY].tqh_first;
2608 if (bp) {
2609 *queue = BQ_EMPTY;
2610 goto found;
2611 }
2612 /*
2613 * We have seen is this is hard to trigger.
2614 * This is an overcommit of nbufs but needed
2615 * in some scenarios with diskiamges
2616 */
2617
2618 add_newbufs:
2619 lck_mtx_unlock(buf_mtxp);
2620
2621 /* Create a new temporary buffer header */
2622 bp = (struct buf *)zalloc(buf_hdr_zone);
2623
2624 lck_mtx_lock(buf_mtxp);
2625
2626 if (bp) {
2627 bufhdrinit(bp);
2628 BLISTNONE(bp);
2629 binshash(bp, &invalhash);
2630 SET(bp->b_flags, B_HDRALLOC);
2631 *queue = BQ_EMPTY;
2632 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
2633 buf_hdr_count++;
2634 goto found;
2635 }
2636 /* subtract already accounted bufcount */
2637 nbuf--;
2638
2639 bufstats.bufs_sleeps++;
2640
2641 /* wait for a free buffer of any kind */
2642 needbuffer = 1;
2643 /* hz value is 100 */
2644 ts.tv_sec = (slptimeo/1000);
2645 /* the hz value is 100; which leads to 10ms */
2646 ts.tv_nsec = (slptimeo % 1000) * NSEC_PER_USEC * 1000 * 10;
2647 msleep(&needbuffer, buf_mtxp, slpflag|(PRIBIO+1), (char *)"getnewbuf", &ts);
2648 return (0);
2649 }
2650
2651 /* Buffer available either on AGE or LRU or META */
2652 bp = NULL;
2653 *queue = -1;
2654
2655 /* Buffer available either on AGE or LRU */
2656 if (!age_bp) {
2657 bp = lru_bp;
2658 *queue = BQ_LRU;
2659 } else if (!lru_bp) {
2660 bp = age_bp;
2661 *queue = BQ_AGE;
2662 } else { /* buffer available on both AGE and LRU */
2663 int t = buf_timestamp();
2664
2665 age_time = t - age_bp->b_timestamp;
2666 lru_time = t - lru_bp->b_timestamp;
2667 if ((age_time < 0) || (lru_time < 0)) { /* time set backwards */
2668 bp = age_bp;
2669 *queue = BQ_AGE;
2670 /*
2671 * we should probably re-timestamp eveything in the
2672 * queues at this point with the current time
2673 */
2674 } else {
2675 if ((lru_time >= lru_is_stale) && (age_time < age_is_stale)) {
2676 bp = lru_bp;
2677 *queue = BQ_LRU;
2678 } else {
2679 bp = age_bp;
2680 *queue = BQ_AGE;
2681 }
2682 }
2683 }
2684
2685 if (!bp) { /* Neither on AGE nor on LRU */
2686 bp = meta_bp;
2687 *queue = BQ_META;
2688 } else if (meta_bp) {
2689 int t = buf_timestamp();
2690
2691 bp_time = t - bp->b_timestamp;
2692 meta_time = t - meta_bp->b_timestamp;
2693
2694 if (!(bp_time < 0) && !(meta_time < 0)) {
2695 /* time not set backwards */
2696 int bp_is_stale;
2697 bp_is_stale = (*queue == BQ_LRU) ?
2698 lru_is_stale : age_is_stale;
2699
2700 if ((meta_time >= meta_is_stale) &&
2701 (bp_time < bp_is_stale)) {
2702 bp = meta_bp;
2703 *queue = BQ_META;
2704 }
2705 }
2706 }
2707 found:
2708 if (ISSET(bp->b_flags, B_LOCKED) || ISSET(bp->b_lflags, BL_BUSY))
2709 panic("getnewbuf: bp @ 0x%x is LOCKED or BUSY! (flags 0x%x)\n", bp, bp->b_flags);
2710
2711 /* Clean it */
2712 if (bcleanbuf(bp)) {
2713 /*
2714 * moved to the laundry thread, buffer not ready
2715 */
2716 *queue = req;
2717 goto start;
2718 }
2719 return (bp);
2720 }
2721
2722
2723 /*
2724 * Clean a buffer.
2725 * Returns 0 is buffer is ready to use,
2726 * Returns 1 if issued a buf_bawrite() to indicate
2727 * that the buffer is not ready.
2728 *
2729 * buf_mtxp is held upon entry
2730 * returns with buf_mtxp locked
2731 */
2732 static int
2733 bcleanbuf(buf_t bp)
2734 {
2735 ucred_t cred;
2736
2737
2738 /* Remove from the queue */
2739 bremfree_locked(bp);
2740
2741 /* Buffer is no longer on free lists. */
2742 SET(bp->b_lflags, BL_BUSY);
2743 #ifdef JOE_DEBUG
2744 bp->b_owner = current_thread();
2745 bp->b_tag = 2;
2746 #endif
2747 /*
2748 * If buffer was a delayed write, start the IO by queuing
2749 * it on the LAUNDRY queue, and return 1
2750 */
2751 if (ISSET(bp->b_flags, B_DELWRI)) {
2752 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
2753 blaundrycnt++;
2754
2755 lck_mtx_unlock(buf_mtxp);
2756
2757 wakeup(&blaundrycnt);
2758 /* and give it a chance to run */
2759 (void)thread_block(THREAD_CONTINUE_NULL);
2760
2761 lck_mtx_lock(buf_mtxp);
2762 return (1);
2763 }
2764 bremhash(bp);
2765
2766 lck_mtx_unlock(buf_mtxp);
2767
2768 BLISTNONE(bp);
2769 /*
2770 * disassociate us from our vnode, if we had one...
2771 */
2772 if (bp->b_vp)
2773 brelvp(bp);
2774
2775 if (ISSET(bp->b_flags, B_META)) {
2776 vm_offset_t elem;
2777
2778 elem = (vm_offset_t)bp->b_datap;
2779 bp->b_datap = (uintptr_t)0xdeadbeef;
2780
2781 if (ISSET(bp->b_flags, B_ZALLOC)) {
2782 zone_t z;
2783
2784 z = getbufzone(bp->b_bufsize);
2785 zfree(z, (void *)elem);
2786 } else
2787 kmem_free(kernel_map, elem, bp->b_bufsize);
2788 }
2789
2790 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
2791
2792 /* clear out various other fields */
2793 bp->b_bufsize = 0;
2794 bp->b_datap = (uintptr_t)NULL;
2795 bp->b_upl = (void *)NULL;
2796 /*
2797 * preserve the state of whether this buffer
2798 * was allocated on the fly or not...
2799 * the only other flag that should be set at
2800 * this point is BL_BUSY...
2801 */
2802 #ifdef JOE_DEBUG
2803 bp->b_owner = current_thread();
2804 bp->b_tag = 3;
2805 #endif
2806 bp->b_lflags = BL_BUSY;
2807 bp->b_flags = (bp->b_flags & B_HDRALLOC);
2808 bp->b_dev = NODEV;
2809 bp->b_blkno = bp->b_lblkno = 0;
2810 bp->b_iodone = NULL;
2811 bp->b_error = 0;
2812 bp->b_resid = 0;
2813 bp->b_bcount = 0;
2814 bp->b_dirtyoff = bp->b_dirtyend = 0;
2815 bp->b_validoff = bp->b_validend = 0;
2816
2817 /* nuke any credentials we were holding */
2818 cred = bp->b_rcred;
2819 if (cred != NOCRED) {
2820 bp->b_rcred = NOCRED;
2821 kauth_cred_rele(cred);
2822 }
2823 cred = bp->b_wcred;
2824 if (cred != NOCRED) {
2825 bp->b_wcred = NOCRED;
2826 kauth_cred_rele(cred);
2827 }
2828 lck_mtx_lock(buf_mtxp);
2829
2830 return (0);
2831 }
2832
2833
2834
2835 errno_t
2836 buf_invalblkno(vnode_t vp, daddr64_t lblkno, int flags)
2837 {
2838 buf_t bp;
2839 errno_t error;
2840
2841 lck_mtx_lock(buf_mtxp);
2842 relook:
2843 if ((bp = incore_locked(vp, lblkno)) == (struct buf *)0) {
2844 lck_mtx_unlock(buf_mtxp);
2845 return (0);
2846 }
2847 if (ISSET(bp->b_lflags, BL_BUSY)) {
2848 if ( !ISSET(flags, BUF_WAIT)) {
2849 lck_mtx_unlock(buf_mtxp);
2850 return (EBUSY);
2851 }
2852 SET(bp->b_lflags, BL_WANTED);
2853
2854 error = msleep((caddr_t)bp, buf_mtxp, (PRIBIO + 1), (char *)"buf_invalblkno", 0);
2855
2856 if (error)
2857 return (error);
2858 goto relook;
2859 }
2860 bremfree_locked(bp);
2861 SET(bp->b_lflags, BL_BUSY);
2862 SET(bp->b_flags, B_INVAL);
2863 #ifdef JOE_DEBUG
2864 bp->b_owner = current_thread();
2865 bp->b_tag = 4;
2866 #endif
2867 lck_mtx_unlock(buf_mtxp);
2868 buf_brelse(bp);
2869
2870 return (0);
2871 }
2872
2873
2874 void
2875 buf_drop(buf_t bp)
2876 {
2877 int need_wakeup = 0;
2878
2879 lck_mtx_lock(buf_mtxp);
2880
2881 if (ISSET(bp->b_lflags, BL_WANTED)) {
2882 /*
2883 * delay the actual wakeup until after we
2884 * clear BL_BUSY and we've dropped buf_mtxp
2885 */
2886 need_wakeup = 1;
2887 }
2888 /*
2889 * Unlock the buffer.
2890 */
2891 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
2892
2893 lck_mtx_unlock(buf_mtxp);
2894
2895 if (need_wakeup) {
2896 /*
2897 * Wake up any proceeses waiting for _this_ buffer to become free.
2898 */
2899 wakeup(bp);
2900 }
2901 }
2902
2903
2904 errno_t
2905 buf_acquire(buf_t bp, int flags, int slpflag, int slptimeo) {
2906 errno_t error;
2907
2908 lck_mtx_lock(buf_mtxp);
2909
2910 error = buf_acquire_locked(bp, flags, slpflag, slptimeo);
2911
2912 lck_mtx_unlock(buf_mtxp);
2913
2914 return (error);
2915 }
2916
2917
2918 static errno_t
2919 buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo)
2920 {
2921 errno_t error;
2922 struct timespec ts;
2923
2924 if (ISSET(bp->b_flags, B_LOCKED)) {
2925 if ((flags & BAC_SKIP_LOCKED))
2926 return (EDEADLK);
2927 } else {
2928 if ((flags & BAC_SKIP_NONLOCKED))
2929 return (EDEADLK);
2930 }
2931 if (ISSET(bp->b_lflags, BL_BUSY)) {
2932 /*
2933 * since the mutex_lock may block, the buffer
2934 * may become BUSY, so we need to
2935 * recheck for a NOWAIT request
2936 */
2937 if (flags & BAC_NOWAIT)
2938 return (EBUSY);
2939 SET(bp->b_lflags, BL_WANTED);
2940
2941 /* the hz value is 100; which leads to 10ms */
2942 ts.tv_sec = (slptimeo/100);
2943 ts.tv_nsec = (slptimeo % 100) * 10 * NSEC_PER_USEC * 1000;
2944 error = msleep((caddr_t)bp, buf_mtxp, slpflag | (PRIBIO + 1), (char *)"buf_acquire", &ts);
2945
2946 if (error)
2947 return (error);
2948 return (EAGAIN);
2949 }
2950 if (flags & BAC_REMOVE)
2951 bremfree_locked(bp);
2952 SET(bp->b_lflags, BL_BUSY);
2953 #ifdef JOE_DEBUG
2954 bp->b_owner = current_thread();
2955 bp->b_tag = 5;
2956 #endif
2957 return (0);
2958 }
2959
2960
2961 /*
2962 * Wait for operations on the buffer to complete.
2963 * When they do, extract and return the I/O's error value.
2964 */
2965 errno_t
2966 buf_biowait(buf_t bp)
2967 {
2968 lck_mtx_lock(buf_mtxp);
2969
2970 while (!ISSET(bp->b_flags, B_DONE))
2971 (void) msleep(bp, buf_mtxp, (PRIBIO+1), (char *)"buf_biowait", 0);
2972
2973 lck_mtx_unlock(buf_mtxp);
2974
2975 /* check for interruption of I/O (e.g. via NFS), then errors. */
2976 if (ISSET(bp->b_flags, B_EINTR)) {
2977 CLR(bp->b_flags, B_EINTR);
2978 return (EINTR);
2979 } else if (ISSET(bp->b_flags, B_ERROR))
2980 return (bp->b_error ? bp->b_error : EIO);
2981 else
2982 return (0);
2983 }
2984
2985 /*
2986 * Mark I/O complete on a buffer.
2987 *
2988 * If a callback has been requested, e.g. the pageout
2989 * daemon, do so. Otherwise, awaken waiting processes.
2990 *
2991 * [ Leffler, et al., says on p.247:
2992 * "This routine wakes up the blocked process, frees the buffer
2993 * for an asynchronous write, or, for a request by the pagedaemon
2994 * process, invokes a procedure specified in the buffer structure" ]
2995 *
2996 * In real life, the pagedaemon (or other system processes) wants
2997 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
2998 * (for swap pager, that puts swap buffers on the free lists (!!!),
2999 * for the vn device, that puts malloc'd buffers on the free lists!)
3000 */
3001 extern struct timeval priority_IO_timestamp_for_root;
3002 extern int hard_throttle_on_root;
3003
3004 void
3005 buf_biodone(buf_t bp)
3006 {
3007 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_START,
3008 (int)bp, (int)bp->b_datap, bp->b_flags, 0, 0);
3009
3010 if (ISSET(bp->b_flags, B_DONE))
3011 panic("biodone already");
3012
3013 if (kdebug_enable) {
3014 int code = DKIO_DONE;
3015
3016 if (bp->b_flags & B_READ)
3017 code |= DKIO_READ;
3018 if (bp->b_flags & B_ASYNC)
3019 code |= DKIO_ASYNC;
3020
3021 if (bp->b_flags & B_META)
3022 code |= DKIO_META;
3023 else if (bp->b_flags & B_PAGEIO)
3024 code |= DKIO_PAGING;
3025
3026 KERNEL_DEBUG_CONSTANT(FSDBG_CODE(DBG_DKRW, code) | DBG_FUNC_NONE,
3027 (unsigned int)bp, (unsigned int)bp->b_vp,
3028 bp->b_resid, bp->b_error, 0);
3029 }
3030 if ((bp->b_vp != NULLVP) &&
3031 ((bp->b_flags & (B_PAGEIO | B_READ)) == (B_PAGEIO | B_READ)) &&
3032 (bp->b_vp->v_mount->mnt_kern_flag & MNTK_ROOTDEV)) {
3033 microuptime(&priority_IO_timestamp_for_root);
3034 hard_throttle_on_root = 0;
3035 }
3036 /*
3037 * I/O was done, so don't believe
3038 * the DIRTY state from VM anymore
3039 */
3040 CLR(bp->b_flags, B_WASDIRTY);
3041
3042 if (!ISSET(bp->b_flags, B_READ) && !ISSET(bp->b_flags, B_RAW))
3043 /*
3044 * wake up any writer's blocked
3045 * on throttle or waiting for I/O
3046 * to drain
3047 */
3048 vnode_writedone(bp->b_vp);
3049
3050 if (ISSET(bp->b_flags, (B_CALL | B_FILTER))) { /* if necessary, call out */
3051 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
3052 void *arg = (void *)bp->b_transaction;
3053 int callout = ISSET(bp->b_flags, B_CALL);
3054
3055 CLR(bp->b_flags, (B_CALL | B_FILTER)); /* filters and callouts are one-shot */
3056 bp->b_iodone = NULL;
3057 bp->b_transaction = NULL;
3058
3059 if (iodone_func == NULL) {
3060 panic("biodone: bp @ 0x%x has NULL b_iodone!\n", bp);
3061 } else {
3062 if (callout)
3063 SET(bp->b_flags, B_DONE); /* note that it's done */
3064 (*iodone_func)(bp, arg);
3065 }
3066 if (callout)
3067 /*
3068 * assumes that the call back function takes
3069 * ownership of the bp and deals with releasing it if necessary
3070 */
3071 goto biodone_done;
3072 /*
3073 * in this case the call back function is acting
3074 * strictly as a filter... it does not take
3075 * ownership of the bp and is expecting us
3076 * to finish cleaning up... this is currently used
3077 * by the HFS journaling code
3078 */
3079 }
3080 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release it */
3081 SET(bp->b_flags, B_DONE); /* note that it's done */
3082
3083 buf_brelse(bp);
3084 } else { /* or just wakeup the buffer */
3085 /*
3086 * by taking the mutex, we serialize
3087 * the buf owner calling buf_biowait so that we'll
3088 * only see him in one of 2 states...
3089 * state 1: B_DONE wasn't set and he's
3090 * blocked in msleep
3091 * state 2: he's blocked trying to take the
3092 * mutex before looking at B_DONE
3093 * BL_WANTED is cleared in case anyone else
3094 * is blocked waiting for the buffer... note
3095 * that we haven't cleared B_BUSY yet, so if
3096 * they do get to run, their going to re-set
3097 * BL_WANTED and go back to sleep
3098 */
3099 lck_mtx_lock(buf_mtxp);
3100
3101 CLR(bp->b_lflags, BL_WANTED);
3102 SET(bp->b_flags, B_DONE); /* note that it's done */
3103
3104 lck_mtx_unlock(buf_mtxp);
3105
3106 wakeup(bp);
3107 }
3108 biodone_done:
3109 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_END,
3110 (int)bp, (int)bp->b_datap, bp->b_flags, 0, 0);
3111 }
3112
3113 /*
3114 * Return a count of buffers on the "locked" queue.
3115 */
3116 int
3117 count_lock_queue(void)
3118 {
3119 buf_t bp;
3120 int n = 0;
3121
3122 lck_mtx_lock(buf_mtxp);
3123
3124 for (bp = bufqueues[BQ_LOCKED].tqh_first; bp;
3125 bp = bp->b_freelist.tqe_next)
3126 n++;
3127 lck_mtx_unlock(buf_mtxp);
3128
3129 return (n);
3130 }
3131
3132 /*
3133 * Return a count of 'busy' buffers. Used at the time of shutdown.
3134 */
3135 int
3136 count_busy_buffers(void)
3137 {
3138 buf_t bp;
3139 int nbusy = 0;
3140
3141 lck_mtx_lock(buf_mtxp);
3142 for (bp = &buf[boot_nbuf]; --bp >= buf; )
3143 if (!ISSET(bp->b_flags, B_INVAL) && ISSET(bp->b_lflags, BL_BUSY))
3144 nbusy++;
3145 lck_mtx_unlock(buf_mtxp);
3146
3147 return (nbusy);
3148 }
3149
3150 #if DIAGNOSTIC
3151 /*
3152 * Print out statistics on the current allocation of the buffer pool.
3153 * Can be enabled to print out on every ``sync'' by setting "syncprt"
3154 * in vfs_syscalls.c using sysctl.
3155 */
3156 void
3157 vfs_bufstats()
3158 {
3159 int i, j, count;
3160 register struct buf *bp;
3161 register struct bqueues *dp;
3162 int counts[MAXBSIZE/CLBYTES+1];
3163 static char *bname[BQUEUES] =
3164 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3165
3166 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
3167 count = 0;
3168 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
3169 counts[j] = 0;
3170
3171 lck_mtx_lock(buf_mtxp);
3172
3173 for (bp = dp->tqh_first; bp; bp = bp->b_freelist.tqe_next) {
3174 counts[bp->b_bufsize/CLBYTES]++;
3175 count++;
3176 }
3177 lck_mtx_unlock(buf_mtxp);
3178
3179 printf("%s: total-%d", bname[i], count);
3180 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
3181 if (counts[j] != 0)
3182 printf(", %d-%d", j * CLBYTES, counts[j]);
3183 printf("\n");
3184 }
3185 }
3186 #endif /* DIAGNOSTIC */
3187
3188 #define NRESERVEDIOBUFS 64
3189
3190
3191 buf_t
3192 alloc_io_buf(vnode_t vp, int priv)
3193 {
3194 buf_t bp;
3195
3196 lck_mtx_lock(iobuffer_mtxp);
3197
3198 while (((niobuf - NRESERVEDIOBUFS < bufstats.bufs_iobufinuse) && !priv) ||
3199 (bp = iobufqueue.tqh_first) == NULL) {
3200 bufstats.bufs_iobufsleeps++;
3201
3202 need_iobuffer = 1;
3203 (void) msleep(&need_iobuffer, iobuffer_mtxp, (PRIBIO+1), (const char *)"alloc_io_buf", 0);
3204 }
3205 TAILQ_REMOVE(&iobufqueue, bp, b_freelist);
3206
3207 bufstats.bufs_iobufinuse++;
3208 if (bufstats.bufs_iobufinuse > bufstats.bufs_iobufmax)
3209 bufstats.bufs_iobufmax = bufstats.bufs_iobufinuse;
3210
3211 lck_mtx_unlock(iobuffer_mtxp);
3212
3213 /*
3214 * initialize various fields
3215 * we don't need to hold the mutex since the buffer
3216 * is now private... the vp should have a reference
3217 * on it and is not protected by this mutex in any event
3218 */
3219 bp->b_timestamp = 0;
3220 bp->b_proc = NULL;
3221
3222 bp->b_datap = 0;
3223 bp->b_flags = 0;
3224 bp->b_lflags = BL_BUSY | BL_IOBUF;
3225 bp->b_blkno = bp->b_lblkno = 0;
3226 #ifdef JOE_DEBUG
3227 bp->b_owner = current_thread();
3228 bp->b_tag = 6;
3229 #endif
3230 bp->b_iodone = NULL;
3231 bp->b_error = 0;
3232 bp->b_resid = 0;
3233 bp->b_bcount = 0;
3234 bp->b_bufsize = 0;
3235 bp->b_upl = NULL;
3236 bp->b_vp = vp;
3237
3238 if (vp && (vp->v_type == VBLK || vp->v_type == VCHR))
3239 bp->b_dev = vp->v_rdev;
3240 else
3241 bp->b_dev = NODEV;
3242
3243 return (bp);
3244 }
3245
3246
3247 void
3248 free_io_buf(buf_t bp)
3249 {
3250 int need_wakeup = 0;
3251
3252 /*
3253 * put buffer back on the head of the iobufqueue
3254 */
3255 bp->b_vp = NULL;
3256 bp->b_flags = B_INVAL;
3257
3258 lck_mtx_lock(iobuffer_mtxp);
3259
3260 binsheadfree(bp, &iobufqueue, -1);
3261
3262 if (need_iobuffer) {
3263 /*
3264 * Wake up any processes waiting because they need an io buffer
3265 *
3266 * do the wakeup after we drop the mutex... it's possible that the
3267 * wakeup will be superfluous if need_iobuffer gets set again and
3268 * another thread runs this path, but it's highly unlikely, doesn't
3269 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
3270 * trying to grab a task related lock...
3271 */
3272 need_iobuffer = 0;
3273 need_wakeup = 1;
3274 }
3275 bufstats.bufs_iobufinuse--;
3276
3277 lck_mtx_unlock(iobuffer_mtxp);
3278
3279 if (need_wakeup)
3280 wakeup(&need_iobuffer);
3281 }
3282
3283
3284
3285 /*
3286 * If getnewbuf() calls bcleanbuf() on the same thread
3287 * there is a potential for stack overrun and deadlocks.
3288 * So we always handoff the work to a worker thread for completion
3289 */
3290 #include <mach/mach_types.h>
3291 #include <mach/memory_object_types.h>
3292 #include <kern/sched_prim.h>
3293
3294
3295 static void
3296 bcleanbuf_thread_init(void)
3297 {
3298 /* create worker thread */
3299 kernel_thread(kernel_task, bcleanbuf_thread);
3300 }
3301
3302 static void
3303 bcleanbuf_thread(void)
3304 {
3305 struct buf *bp;
3306 int error = 0;
3307 int loopcnt = 0;
3308
3309 for (;;) {
3310 lck_mtx_lock(buf_mtxp);
3311
3312 while (blaundrycnt == 0)
3313 (void)msleep((void *)&blaundrycnt, buf_mtxp, PRIBIO, "blaundry", 0);
3314
3315 bp = TAILQ_FIRST(&bufqueues[BQ_LAUNDRY]);
3316 /*
3317 * Remove from the queue
3318 */
3319 bremfree_locked(bp);
3320 blaundrycnt--;
3321
3322 lck_mtx_unlock(buf_mtxp);
3323 /*
3324 * do the IO
3325 */
3326 error = bawrite_internal(bp, 0);
3327
3328 if (error) {
3329 lck_mtx_lock(buf_mtxp);
3330
3331 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
3332 blaundrycnt++;
3333
3334 lck_mtx_unlock(buf_mtxp);
3335
3336 if (loopcnt > 10) {
3337 (void)tsleep((void *)&blaundrycnt, PRIBIO, "blaundry", 1);
3338 loopcnt = 0;
3339 } else {
3340 (void)thread_block(THREAD_CONTINUE_NULL);
3341 loopcnt++;
3342 }
3343 }
3344 }
3345 }
3346
3347
3348 static int
3349 brecover_data(buf_t bp)
3350 {
3351 int upl_offset;
3352 upl_t upl;
3353 upl_page_info_t *pl;
3354 kern_return_t kret;
3355 vnode_t vp = bp->b_vp;
3356 int upl_flags;
3357
3358
3359 if ( !UBCINFOEXISTS(vp) || bp->b_bufsize == 0)
3360 goto dump_buffer;
3361
3362 upl_flags = UPL_PRECIOUS;
3363 if (! (buf_flags(bp) & B_READ)) {
3364 /*
3365 * "write" operation: let the UPL subsystem know
3366 * that we intend to modify the buffer cache pages we're
3367 * gathering.
3368 */
3369 upl_flags |= UPL_WILL_MODIFY;
3370 }
3371
3372 kret = ubc_create_upl(vp,
3373 ubc_blktooff(vp, bp->b_lblkno),
3374 bp->b_bufsize,
3375 &upl,
3376 &pl,
3377 upl_flags);
3378 if (kret != KERN_SUCCESS)
3379 panic("Failed to create UPL");
3380
3381 for (upl_offset = 0; upl_offset < bp->b_bufsize; upl_offset += PAGE_SIZE) {
3382
3383 if (!upl_valid_page(pl, upl_offset / PAGE_SIZE) || !upl_dirty_page(pl, upl_offset / PAGE_SIZE)) {
3384 ubc_upl_abort(upl, 0);
3385 goto dump_buffer;
3386 }
3387 }
3388 bp->b_upl = upl;
3389
3390 kret = ubc_upl_map(upl, (vm_address_t *)&(bp->b_datap));
3391
3392 if (kret != KERN_SUCCESS)
3393 panic("getblk: ubc_upl_map() failed with (%d)", kret);
3394 return (1);
3395
3396 dump_buffer:
3397 bp->b_bufsize = 0;
3398 SET(bp->b_flags, B_INVAL);
3399 buf_brelse(bp);
3400
3401 return(0);
3402 }
3403
3404
3405
3406 /*
3407 * disabled for now
3408 */
3409
3410 #if FLUSH_QUEUES
3411
3412 #define NFLUSH 32
3413
3414 static int
3415 bp_cmp(void *a, void *b)
3416 {
3417 buf_t *bp_a = *(buf_t **)a,
3418 *bp_b = *(buf_t **)b;
3419 daddr64_t res;
3420
3421 // don't have to worry about negative block
3422 // numbers so this is ok to do.
3423 //
3424 res = (bp_a->b_blkno - bp_b->b_blkno);
3425
3426 return (int)res;
3427 }
3428
3429
3430 int
3431 bflushq(int whichq, mount_t mp)
3432 {
3433 buf_t bp, next;
3434 int i, buf_count;
3435 int total_writes = 0;
3436 static buf_t flush_table[NFLUSH];
3437
3438 if (whichq < 0 || whichq >= BQUEUES) {
3439 return (0);
3440 }
3441
3442 restart:
3443 lck_mtx_lock(buf_mtxp);
3444
3445 bp = TAILQ_FIRST(&bufqueues[whichq]);
3446
3447 for (buf_count = 0; bp; bp = next) {
3448 next = bp->b_freelist.tqe_next;
3449
3450 if (bp->b_vp == NULL || bp->b_vp->v_mount != mp) {
3451 continue;
3452 }
3453
3454 if (ISSET(bp->b_flags, B_DELWRI) && !ISSET(bp->b_lflags, BL_BUSY)) {
3455
3456 bremfree_locked(bp);
3457 #ifdef JOE_DEBUG
3458 bp->b_owner = current_thread();
3459 bp->b_tag = 7;
3460 #endif
3461 SET(bp->b_lflags, BL_BUSY);
3462 flush_table[buf_count] = bp;
3463 buf_count++;
3464 total_writes++;
3465
3466 if (buf_count >= NFLUSH) {
3467 lck_mtx_unlock(buf_mtxp);
3468
3469 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
3470
3471 for (i = 0; i < buf_count; i++) {
3472 buf_bawrite(flush_table[i]);
3473 }
3474 goto restart;
3475 }
3476 }
3477 }
3478 lck_mtx_unlock(buf_mtxp);
3479
3480 if (buf_count > 0) {
3481 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
3482
3483 for (i = 0; i < buf_count; i++) {
3484 buf_bawrite(flush_table[i]);
3485 }
3486 }
3487
3488 return (total_writes);
3489 }
3490 #endif
3491
3492
3493 #if BALANCE_QUEUES
3494
3495 /* XXX move this to a separate file */
3496
3497 /*
3498 * NOTE: THIS CODE HAS NOT BEEN UPDATED
3499 * WITH RESPECT TO THE NEW LOCKING MODEL
3500 */
3501
3502
3503 /*
3504 * Dynamic Scaling of the Buffer Queues
3505 */
3506
3507 typedef long long blsize_t;
3508
3509 blsize_t MAXNBUF; /* initialize to (sane_size / PAGE_SIZE) */
3510 /* Global tunable limits */
3511 blsize_t nbufh; /* number of buffer headers */
3512 blsize_t nbuflow; /* minimum number of buffer headers required */
3513 blsize_t nbufhigh; /* maximum number of buffer headers allowed */
3514 blsize_t nbuftarget; /* preferred number of buffer headers */
3515
3516 /*
3517 * assertions:
3518 *
3519 * 1. 0 < nbuflow <= nbufh <= nbufhigh
3520 * 2. nbufhigh <= MAXNBUF
3521 * 3. 0 < nbuflow <= nbuftarget <= nbufhigh
3522 * 4. nbufh can not be set by sysctl().
3523 */
3524
3525 /* Per queue tunable limits */
3526
3527 struct bufqlim {
3528 blsize_t bl_nlow; /* minimum number of buffer headers required */
3529 blsize_t bl_num; /* number of buffer headers on the queue */
3530 blsize_t bl_nlhigh; /* maximum number of buffer headers allowed */
3531 blsize_t bl_target; /* preferred number of buffer headers */
3532 long bl_stale; /* Seconds after which a buffer is considered stale */
3533 } bufqlim[BQUEUES];
3534
3535 /*
3536 * assertions:
3537 *
3538 * 1. 0 <= bl_nlow <= bl_num <= bl_nlhigh
3539 * 2. bl_nlhigh <= MAXNBUF
3540 * 3. bufqlim[BQ_META].bl_nlow != 0
3541 * 4. bufqlim[BQ_META].bl_nlow > (number of possible concurrent
3542 * file system IO operations)
3543 * 5. bl_num can not be set by sysctl().
3544 * 6. bl_nhigh <= nbufhigh
3545 */
3546
3547 /*
3548 * Rationale:
3549 * ----------
3550 * Defining it blsize_t as long permits 2^31 buffer headers per queue.
3551 * Which can describe (2^31 * PAGE_SIZE) memory per queue.
3552 *
3553 * These limits are exported to by means of sysctl().
3554 * It was decided to define blsize_t as a 64 bit quantity.
3555 * This will make sure that we will not be required to change it
3556 * as long as we do not exceed 64 bit address space for the kernel.
3557 *
3558 * low and high numbers parameters initialized at compile time
3559 * and boot arguments can be used to override them. sysctl()
3560 * would not change the value. sysctl() can get all the values
3561 * but can set only target. num is the current level.
3562 *
3563 * Advantages of having a "bufqscan" thread doing the balancing are,
3564 * Keep enough bufs on BQ_EMPTY.
3565 * getnewbuf() by default will always select a buffer from the BQ_EMPTY.
3566 * getnewbuf() perfoms best if a buffer was found there.
3567 * Also this minimizes the possibility of starting IO
3568 * from getnewbuf(). That's a performance win, too.
3569 *
3570 * Localize complex logic [balancing as well as time aging]
3571 * to balancebufq().
3572 *
3573 * Simplify getnewbuf() logic by elimination of time aging code.
3574 */
3575
3576 /*
3577 * Algorithm:
3578 * -----------
3579 * The goal of the dynamic scaling of the buffer queues to to keep
3580 * the size of the LRU close to bl_target. Buffers on a queue would
3581 * be time aged.
3582 *
3583 * There would be a thread which will be responsible for "balancing"
3584 * the buffer cache queues.
3585 *
3586 * The scan order would be: AGE, LRU, META, EMPTY.
3587 */
3588
3589 long bufqscanwait = 0;
3590
3591 static void bufqscan_thread();
3592 static int balancebufq(int q);
3593 static int btrimempty(int n);
3594 static __inline__ int initbufqscan(void);
3595 static __inline__ int nextbufq(int q);
3596 static void buqlimprt(int all);
3597
3598
3599 static __inline__ void
3600 bufqinc(int q)
3601 {
3602 if ((q < 0) || (q >= BQUEUES))
3603 return;
3604
3605 bufqlim[q].bl_num++;
3606 return;
3607 }
3608
3609 static __inline__ void
3610 bufqdec(int q)
3611 {
3612 if ((q < 0) || (q >= BQUEUES))
3613 return;
3614
3615 bufqlim[q].bl_num--;
3616 return;
3617 }
3618
3619 static void
3620 bufq_balance_thread_init()
3621 {
3622
3623 if (bufqscanwait++ == 0) {
3624
3625 /* Initalize globals */
3626 MAXNBUF = (sane_size / PAGE_SIZE);
3627 nbufh = nbuf;
3628 nbuflow = min(nbufh, 100);
3629 nbufhigh = min(MAXNBUF, max(nbufh, 2048));
3630 nbuftarget = (sane_size >> 5) / PAGE_SIZE;
3631 nbuftarget = max(nbuflow, nbuftarget);
3632 nbuftarget = min(nbufhigh, nbuftarget);
3633
3634 /*
3635 * Initialize the bufqlim
3636 */
3637
3638 /* LOCKED queue */
3639 bufqlim[BQ_LOCKED].bl_nlow = 0;
3640 bufqlim[BQ_LOCKED].bl_nlhigh = 32;
3641 bufqlim[BQ_LOCKED].bl_target = 0;
3642 bufqlim[BQ_LOCKED].bl_stale = 30;
3643
3644 /* LRU queue */
3645 bufqlim[BQ_LRU].bl_nlow = 0;
3646 bufqlim[BQ_LRU].bl_nlhigh = nbufhigh/4;
3647 bufqlim[BQ_LRU].bl_target = nbuftarget/4;
3648 bufqlim[BQ_LRU].bl_stale = LRU_IS_STALE;
3649
3650 /* AGE queue */
3651 bufqlim[BQ_AGE].bl_nlow = 0;
3652 bufqlim[BQ_AGE].bl_nlhigh = nbufhigh/4;
3653 bufqlim[BQ_AGE].bl_target = nbuftarget/4;
3654 bufqlim[BQ_AGE].bl_stale = AGE_IS_STALE;
3655
3656 /* EMPTY queue */
3657 bufqlim[BQ_EMPTY].bl_nlow = 0;
3658 bufqlim[BQ_EMPTY].bl_nlhigh = nbufhigh/4;
3659 bufqlim[BQ_EMPTY].bl_target = nbuftarget/4;
3660 bufqlim[BQ_EMPTY].bl_stale = 600000;
3661
3662 /* META queue */
3663 bufqlim[BQ_META].bl_nlow = 0;
3664 bufqlim[BQ_META].bl_nlhigh = nbufhigh/4;
3665 bufqlim[BQ_META].bl_target = nbuftarget/4;
3666 bufqlim[BQ_META].bl_stale = META_IS_STALE;
3667
3668 /* LAUNDRY queue */
3669 bufqlim[BQ_LOCKED].bl_nlow = 0;
3670 bufqlim[BQ_LOCKED].bl_nlhigh = 32;
3671 bufqlim[BQ_LOCKED].bl_target = 0;
3672 bufqlim[BQ_LOCKED].bl_stale = 30;
3673
3674 buqlimprt(1);
3675 }
3676
3677 /* create worker thread */
3678 kernel_thread(kernel_task, bufqscan_thread);
3679 }
3680
3681 /* The workloop for the buffer balancing thread */
3682 static void
3683 bufqscan_thread()
3684 {
3685 int moretodo = 0;
3686
3687 for(;;) {
3688 do {
3689 int q; /* buffer queue to process */
3690
3691 q = initbufqscan();
3692 for (; q; ) {
3693 moretodo |= balancebufq(q);
3694 q = nextbufq(q);
3695 }
3696 } while (moretodo);
3697
3698 #if DIAGNOSTIC
3699 vfs_bufstats();
3700 buqlimprt(0);
3701 #endif
3702 (void)tsleep((void *)&bufqscanwait, PRIBIO, "bufqscanwait", 60 * hz);
3703 moretodo = 0;
3704 }
3705 }
3706
3707 /* Seed for the buffer queue balancing */
3708 static __inline__ int
3709 initbufqscan()
3710 {
3711 /* Start with AGE queue */
3712 return (BQ_AGE);
3713 }
3714
3715 /* Pick next buffer queue to balance */
3716 static __inline__ int
3717 nextbufq(int q)
3718 {
3719 int order[] = { BQ_AGE, BQ_LRU, BQ_META, BQ_EMPTY, 0 };
3720
3721 q++;
3722 q %= sizeof(order);
3723 return (order[q]);
3724 }
3725
3726 /* function to balance the buffer queues */
3727 static int
3728 balancebufq(int q)
3729 {
3730 int moretodo = 0;
3731 int s = splbio();
3732 int n, t;
3733
3734 /* reject invalid q */
3735 if ((q < 0) || (q >= BQUEUES))
3736 goto out;
3737
3738 /* LOCKED or LAUNDRY queue MUST not be balanced */
3739 if ((q == BQ_LOCKED) || (q == BQ_LAUNDRY))
3740 goto out;
3741
3742 n = (bufqlim[q].bl_num - bufqlim[q].bl_target);
3743
3744 /* If queue has less than target nothing more to do */
3745 if (n < 0)
3746 goto out;
3747
3748 if ( n > 8 ) {
3749 /* Balance only a small amount (12.5%) at a time */
3750 n >>= 3;
3751 }
3752
3753 /* EMPTY queue needs special handling */
3754 if (q == BQ_EMPTY) {
3755 moretodo |= btrimempty(n);
3756 goto out;
3757 }
3758
3759 t = buf_timestamp():
3760
3761 for (; n > 0; n--) {
3762 struct buf *bp = bufqueues[q].tqh_first;
3763 if (!bp)
3764 break;
3765
3766 /* check if it's stale */
3767 if ((t - bp->b_timestamp) > bufqlim[q].bl_stale) {
3768 if (bcleanbuf(bp)) {
3769 /* buf_bawrite() issued, bp not ready */
3770 moretodo = 1;
3771 } else {
3772 /* release the cleaned buffer to BQ_EMPTY */
3773 SET(bp->b_flags, B_INVAL);
3774 buf_brelse(bp);
3775 }
3776 } else
3777 break;
3778 }
3779
3780 out:
3781 splx(s);
3782 return (moretodo);
3783 }
3784
3785 static int
3786 btrimempty(int n)
3787 {
3788 /*
3789 * When struct buf are allocated dynamically, this would
3790 * reclaim upto 'n' struct buf from the empty queue.
3791 */
3792
3793 return (0);
3794 }
3795
3796 static void
3797 buqlimprt(int all)
3798 {
3799 int i;
3800 static char *bname[BQUEUES] =
3801 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
3802
3803 if (all)
3804 for (i = 0; i < BQUEUES; i++) {
3805 printf("%s : ", bname[i]);
3806 printf("min = %ld, ", (long)bufqlim[i].bl_nlow);
3807 printf("cur = %ld, ", (long)bufqlim[i].bl_num);
3808 printf("max = %ld, ", (long)bufqlim[i].bl_nlhigh);
3809 printf("target = %ld, ", (long)bufqlim[i].bl_target);
3810 printf("stale after %ld seconds\n", bufqlim[i].bl_stale);
3811 }
3812 else
3813 for (i = 0; i < BQUEUES; i++) {
3814 printf("%s : ", bname[i]);
3815 printf("cur = %ld, ", (long)bufqlim[i].bl_num);
3816 }
3817 }
3818
3819 #endif
3820
3821