]> git.saurik.com Git - apple/xnu.git/blame - bsd/vfs/vfs_bio.c
xnu-3789.41.3.tar.gz
[apple/xnu.git] / bsd / vfs / vfs_bio.c
CommitLineData
1c79356b 1/*
39037602 2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
8f6c56a5 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29/*-
30 * Copyright (c) 1994 Christopher G. Demetriou
31 * Copyright (c) 1982, 1986, 1989, 1993
32 * The Regents of the University of California. All rights reserved.
33 * (c) UNIX System Laboratories, Inc.
34 * All or some portions of this file are derived from material licensed
35 * to the University of California by American Telephone and Telegraph
36 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37 * the permission of UNIX System Laboratories, Inc.
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 * notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 * notice, this list of conditions and the following disclaimer in the
46 * documentation and/or other materials provided with the distribution.
47 * 3. All advertising materials mentioning features or use of this software
48 * must display the following acknowledgement:
49 * This product includes software developed by the University of
50 * California, Berkeley and its contributors.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
54 *
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 * SUCH DAMAGE.
66 *
1c79356b
A
67 * @(#)vfs_bio.c 8.6 (Berkeley) 1/11/94
68 */
69
70/*
71 * Some references:
72 * Bach: The Design of the UNIX Operating System (Prentice Hall, 1986)
73 * Leffler, et al.: The Design and Implementation of the 4.3BSD
74 * UNIX Operating System (Addison Welley, 1989)
75 */
1c79356b
A
76
77#include <sys/param.h>
78#include <sys/systm.h>
91447636
A
79#include <sys/proc_internal.h>
80#include <sys/buf_internal.h>
81#include <sys/vnode_internal.h>
82#include <sys/mount_internal.h>
1c79356b
A
83#include <sys/trace.h>
84#include <sys/malloc.h>
85#include <sys/resourcevar.h>
86#include <miscfs/specfs/specdev.h>
87#include <sys/ubc.h>
91447636 88#include <sys/kauth.h>
1c79356b
A
89#if DIAGNOSTIC
90#include <kern/assert.h>
91#endif /* DIAGNOSTIC */
92#include <kern/task.h>
93#include <kern/zalloc.h>
fe8ab488
A
94#include <kern/locks.h>
95#include <kern/thread.h>
91447636 96
2d21ac55 97#include <sys/fslog.h> /* fslog_io_error() */
d190cdc3 98#include <sys/disk.h> /* dk_error_description_t */
2d21ac55
A
99
100#include <mach/mach_types.h>
101#include <mach/memory_object_types.h>
102#include <kern/sched_prim.h> /* thread_block() */
103
91447636 104#include <vm/vm_kern.h>
b0d623f7 105#include <vm/vm_pageout.h>
1c79356b
A
106
107#include <sys/kdebug.h>
2d21ac55
A
108
109#include <libkern/OSAtomic.h>
b0d623f7 110#include <libkern/OSDebug.h>
2d21ac55
A
111#include <sys/ubc_internal.h>
112
113#include <sys/sdt.h>
1c79356b 114
6d2010ae 115int bcleanbuf(buf_t bp, boolean_t discard);
91447636
A
116static int brecover_data(buf_t bp);
117static boolean_t incore(vnode_t vp, daddr64_t blkno);
91447636
A
118/* timeout is in msecs */
119static buf_t getnewbuf(int slpflag, int slptimeo, int *queue);
120static void bremfree_locked(buf_t bp);
121static void buf_reassign(buf_t bp, vnode_t newvp);
122static errno_t buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo);
123static int buf_iterprepare(vnode_t vp, struct buflists *, int flags);
124static void buf_itercomplete(vnode_t vp, struct buflists *, int flags);
6d2010ae
A
125static boolean_t buffer_cache_gc(int);
126static buf_t buf_brelse_shadow(buf_t bp);
127static void buf_free_meta_store(buf_t bp);
128
129static buf_t buf_create_shadow_internal(buf_t bp, boolean_t force_copy,
130 uintptr_t external_storage, void (*iodone)(buf_t, void *), void *arg, int priv);
131
1c79356b 132
39037602 133int bdwrite_internal(buf_t, int);
1c79356b 134
d52fe63f 135/* zone allocated buffer headers */
39236c6e
A
136static void bufzoneinit(void);
137static void bcleanbuf_thread_init(void);
91447636
A
138static void bcleanbuf_thread(void);
139
140static zone_t buf_hdr_zone;
141static int buf_hdr_count;
d52fe63f 142
1c79356b
A
143
144/*
145 * Definitions for the buffer hash lists.
146 */
147#define BUFHASH(dvp, lbn) \
148 (&bufhashtbl[((long)(dvp) / sizeof(*(dvp)) + (int)(lbn)) & bufhash])
149LIST_HEAD(bufhashhdr, buf) *bufhashtbl, invalhash;
150u_long bufhash;
151
2d21ac55
A
152static buf_t incore_locked(vnode_t vp, daddr64_t blkno, struct bufhashhdr *dp);
153
1c79356b
A
154/* Definitions for the buffer stats. */
155struct bufstats bufstats;
156
d52fe63f 157/* Number of delayed write buffers */
2d21ac55 158long nbdwrite = 0;
91447636 159int blaundrycnt = 0;
2d21ac55 160static int boot_nbuf_headers = 0;
d52fe63f 161
6d2010ae 162static TAILQ_HEAD(delayqueue, buf) delaybufqueue;
1c79356b 163
91447636
A
164static TAILQ_HEAD(ioqueue, buf) iobufqueue;
165static TAILQ_HEAD(bqueues, buf) bufqueues[BQUEUES];
d52fe63f
A
166static int needbuffer;
167static int need_iobuffer;
1c79356b 168
91447636
A
169static lck_grp_t *buf_mtx_grp;
170static lck_attr_t *buf_mtx_attr;
171static lck_grp_attr_t *buf_mtx_grp_attr;
172static lck_mtx_t *iobuffer_mtxp;
173static lck_mtx_t *buf_mtxp;
174
b0d623f7
A
175static int buf_busycount;
176
91447636
A
177static __inline__ int
178buf_timestamp(void)
179{
180 struct timeval t;
181 microuptime(&t);
182 return (t.tv_sec);
183}
184
1c79356b
A
185/*
186 * Insq/Remq for the buffer free lists.
187 */
91447636
A
188#define binsheadfree(bp, dp, whichq) do { \
189 TAILQ_INSERT_HEAD(dp, bp, b_freelist); \
1c79356b
A
190 } while (0)
191
91447636
A
192#define binstailfree(bp, dp, whichq) do { \
193 TAILQ_INSERT_TAIL(dp, bp, b_freelist); \
91447636 194 } while (0)
91447636 195
1c79356b
A
196#define BHASHENTCHECK(bp) \
197 if ((bp)->b_hash.le_prev != (struct buf **)0xdeadbeef) \
2d21ac55 198 panic("%p: b_hash.le_prev is not deadbeef", (bp));
1c79356b
A
199
200#define BLISTNONE(bp) \
201 (bp)->b_hash.le_next = (struct buf *)0; \
202 (bp)->b_hash.le_prev = (struct buf **)0xdeadbeef;
203
9bccf70c
A
204/*
205 * Insq/Remq for the vnode usage lists.
206 */
207#define bufinsvn(bp, dp) LIST_INSERT_HEAD(dp, bp, b_vnbufs)
208#define bufremvn(bp) { \
209 LIST_REMOVE(bp, b_vnbufs); \
210 (bp)->b_vnbufs.le_next = NOLIST; \
211}
212
1c79356b
A
213/*
214 * Time in seconds before a buffer on a list is
215 * considered as a stale buffer
216 */
217#define LRU_IS_STALE 120 /* default value for the LRU */
218#define AGE_IS_STALE 60 /* default value for the AGE */
219#define META_IS_STALE 180 /* default value for the BQ_META */
220
221int lru_is_stale = LRU_IS_STALE;
222int age_is_stale = AGE_IS_STALE;
223int meta_is_stale = META_IS_STALE;
2d21ac55 224
6d2010ae 225#define MAXLAUNDRY 10
91447636 226
9bccf70c
A
227/* LIST_INSERT_HEAD() with assertions */
228static __inline__ void
91447636 229blistenterhead(struct bufhashhdr * head, buf_t bp)
1c79356b
A
230{
231 if ((bp->b_hash.le_next = (head)->lh_first) != NULL)
232 (head)->lh_first->b_hash.le_prev = &(bp)->b_hash.le_next;
233 (head)->lh_first = bp;
234 bp->b_hash.le_prev = &(head)->lh_first;
235 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
236 panic("blistenterhead: le_prev is deadbeef");
1c79356b 237}
1c79356b 238
9bccf70c 239static __inline__ void
91447636 240binshash(buf_t bp, struct bufhashhdr *dp)
1c79356b 241{
0c530ab8 242#if DIAGNOSTIC
91447636 243 buf_t nbp;
0c530ab8 244#endif /* DIAGNOSTIC */
9bccf70c 245
1c79356b 246 BHASHENTCHECK(bp);
9bccf70c 247
0c530ab8 248#if DIAGNOSTIC
1c79356b
A
249 nbp = dp->lh_first;
250 for(; nbp != NULL; nbp = nbp->b_hash.le_next) {
251 if(nbp == bp)
252 panic("buf already in hashlist");
253 }
0c530ab8 254#endif /* DIAGNOSTIC */
1c79356b 255
1c79356b 256 blistenterhead(dp, bp);
1c79356b
A
257}
258
9bccf70c 259static __inline__ void
91447636 260bremhash(buf_t bp)
1c79356b 261{
1c79356b
A
262 if (bp->b_hash.le_prev == (struct buf **)0xdeadbeef)
263 panic("bremhash le_prev is deadbeef");
264 if (bp->b_hash.le_next == bp)
265 panic("bremhash: next points to self");
266
267 if (bp->b_hash.le_next != NULL)
268 bp->b_hash.le_next->b_hash.le_prev = bp->b_hash.le_prev;
269 *bp->b_hash.le_prev = (bp)->b_hash.le_next;
1c79356b
A
270}
271
6d2010ae
A
272/*
273 * buf_mtxp held.
274 */
275static __inline__ void
276bmovelaundry(buf_t bp)
277{
278 bp->b_whichq = BQ_LAUNDRY;
279 bp->b_timestamp = buf_timestamp();
280 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
281 blaundrycnt++;
282}
1c79356b 283
6d2010ae
A
284static __inline__ void
285buf_release_credentials(buf_t bp)
286{
287 if (IS_VALID_CRED(bp->b_rcred)) {
288 kauth_cred_unref(&bp->b_rcred);
289 }
290 if (IS_VALID_CRED(bp->b_wcred)) {
291 kauth_cred_unref(&bp->b_wcred);
292 }
293}
1c79356b 294
9bccf70c 295
91447636
A
296int
297buf_valid(buf_t bp) {
298
299 if ( (bp->b_flags & (B_DONE | B_DELWRI)) )
300 return 1;
301 return 0;
9bccf70c
A
302}
303
91447636
A
304int
305buf_fromcache(buf_t bp) {
9bccf70c 306
91447636
A
307 if ( (bp->b_flags & B_CACHE) )
308 return 1;
309 return 0;
9bccf70c
A
310}
311
9bccf70c 312void
91447636
A
313buf_markinvalid(buf_t bp) {
314
315 SET(bp->b_flags, B_INVAL);
316}
9bccf70c 317
91447636
A
318void
319buf_markdelayed(buf_t bp) {
320
2d21ac55
A
321 if (!ISSET(bp->b_flags, B_DELWRI)) {
322 SET(bp->b_flags, B_DELWRI);
323
b0d623f7 324 OSAddAtomicLong(1, &nbdwrite);
2d21ac55
A
325 buf_reassign(bp, bp->b_vp);
326 }
327 SET(bp->b_flags, B_DONE);
9bccf70c
A
328}
329
6d2010ae
A
330void
331buf_markclean(buf_t bp) {
332
333 if (ISSET(bp->b_flags, B_DELWRI)) {
334 CLR(bp->b_flags, B_DELWRI);
335
336 OSAddAtomicLong(-1, &nbdwrite);
337 buf_reassign(bp, bp->b_vp);
338 }
339}
340
91447636
A
341void
342buf_markeintr(buf_t bp) {
343
344 SET(bp->b_flags, B_EINTR);
345}
765c9de3 346
2d21ac55 347
91447636
A
348void
349buf_markaged(buf_t bp) {
350
351 SET(bp->b_flags, B_AGE);
765c9de3
A
352}
353
2d21ac55
A
354int
355buf_fua(buf_t bp) {
356
357 if ((bp->b_flags & B_FUA) == B_FUA)
358 return 1;
359 return 0;
360}
361
362void
363buf_markfua(buf_t bp) {
364
365 SET(bp->b_flags, B_FUA);
366}
367
316670eb 368#if CONFIG_PROTECT
3e170ce0
A
369cpx_t bufattr_cpx(bufattr_t bap)
370{
371 return bap->ba_cpx;
372}
373
374void bufattr_setcpx(bufattr_t bap, cpx_t cpx)
375{
376 bap->ba_cpx = cpx;
316670eb
A
377}
378
379void
380buf_setcpoff (buf_t bp, uint64_t foffset) {
381 bp->b_attr.ba_cp_file_off = foffset;
382}
383
316670eb
A
384uint64_t
385bufattr_cpoff(bufattr_t bap) {
3e170ce0 386 return bap->ba_cp_file_off;
316670eb
A
387}
388
389void
390bufattr_setcpoff(bufattr_t bap, uint64_t foffset) {
3e170ce0 391 bap->ba_cp_file_off = foffset;
d1ecb069
A
392}
393
3e170ce0 394#else // !CONTECT_PROTECT
d1ecb069 395
316670eb
A
396uint64_t
397bufattr_cpoff(bufattr_t bap __unused) {
398 return 0;
399}
400
316670eb
A
401void
402bufattr_setcpoff(__unused bufattr_t bap, __unused uint64_t foffset) {
d1ecb069
A
403 return;
404}
3e170ce0
A
405
406struct cpx *bufattr_cpx(__unused bufattr_t bap)
407{
408 return NULL;
409}
410
411void bufattr_setcpx(__unused bufattr_t bap, __unused struct cpx *cpx)
412{
413}
414
415#endif /* !CONFIG_PROTECT */
d1ecb069 416
316670eb
A
417bufattr_t
418bufattr_alloc() {
419 bufattr_t bap;
420 MALLOC(bap, bufattr_t, sizeof(struct bufattr), M_TEMP, M_WAITOK);
421 if (bap == NULL)
422 return NULL;
423
424 bzero(bap, sizeof(struct bufattr));
425 return bap;
426}
427
428void
429bufattr_free(bufattr_t bap) {
430 if (bap)
431 FREE(bap, M_TEMP);
432}
433
fe8ab488
A
434bufattr_t
435bufattr_dup(bufattr_t bap) {
436 bufattr_t new_bufattr;
437 MALLOC(new_bufattr, bufattr_t, sizeof(struct bufattr), M_TEMP, M_WAITOK);
438 if (new_bufattr == NULL)
439 return NULL;
440
441 /* Copy the provided one into the new copy */
442 memcpy (new_bufattr, bap, sizeof(struct bufattr));
443 return new_bufattr;
444}
445
316670eb
A
446int
447bufattr_rawencrypted(bufattr_t bap) {
448 if ( (bap->ba_flags & BA_RAW_ENCRYPTED_IO) )
449 return 1;
450 return 0;
451}
452
7ddcb079
A
453int
454bufattr_throttled(bufattr_t bap) {
39236c6e 455 return (GET_BUFATTR_IO_TIER(bap));
7ddcb079
A
456}
457
fe8ab488
A
458int
459bufattr_passive(bufattr_t bap) {
460 if ( (bap->ba_flags & BA_PASSIVE) )
461 return 1;
462 return 0;
463}
464
316670eb
A
465int
466bufattr_nocache(bufattr_t bap) {
467 if ( (bap->ba_flags & BA_NOCACHE) )
468 return 1;
469 return 0;
470}
471
472int
473bufattr_meta(bufattr_t bap) {
474 if ( (bap->ba_flags & BA_META) )
475 return 1;
476 return 0;
477}
478
fe8ab488
A
479void
480bufattr_markmeta(bufattr_t bap) {
481 SET(bap->ba_flags, BA_META);
482}
483
316670eb 484int
316670eb 485bufattr_delayidlesleep(bufattr_t bap)
316670eb 486{
316670eb
A
487 if ( (bap->ba_flags & BA_DELAYIDLESLEEP) )
488 return 1;
316670eb
A
489 return 0;
490}
491
7ddcb079
A
492bufattr_t
493buf_attr(buf_t bp) {
494 return &bp->b_attr;
495}
496
316670eb
A
497void
498buf_markstatic(buf_t bp __unused) {
499 SET(bp->b_flags, B_STATICCONTENT);
500}
501
502int
503buf_static(buf_t bp) {
504 if ( (bp->b_flags & B_STATICCONTENT) )
505 return 1;
506 return 0;
507}
508
39236c6e
A
509void
510bufattr_markgreedymode(bufattr_t bap) {
511 SET(bap->ba_flags, BA_GREEDY_MODE);
512}
513
514int
515bufattr_greedymode(bufattr_t bap) {
516 if ( (bap->ba_flags & BA_GREEDY_MODE) )
517 return 1;
518 return 0;
519}
520
fe8ab488
A
521void
522bufattr_markisochronous(bufattr_t bap) {
523 SET(bap->ba_flags, BA_ISOCHRONOUS);
524}
525
526int
527bufattr_isochronous(bufattr_t bap) {
528 if ( (bap->ba_flags & BA_ISOCHRONOUS) )
529 return 1;
530 return 0;
531}
532
39236c6e
A
533void
534bufattr_markquickcomplete(bufattr_t bap) {
535 SET(bap->ba_flags, BA_QUICK_COMPLETE);
536}
537
538int
539bufattr_quickcomplete(bufattr_t bap) {
540 if ( (bap->ba_flags & BA_QUICK_COMPLETE) )
541 return 1;
542 return 0;
543}
544
91447636
A
545errno_t
546buf_error(buf_t bp) {
547
548 return (bp->b_error);
549}
1c79356b 550
91447636
A
551void
552buf_seterror(buf_t bp, errno_t error) {
1c79356b 553
91447636
A
554 if ((bp->b_error = error))
555 SET(bp->b_flags, B_ERROR);
556 else
557 CLR(bp->b_flags, B_ERROR);
558}
1c79356b 559
91447636
A
560void
561buf_setflags(buf_t bp, int32_t flags) {
1c79356b 562
91447636
A
563 SET(bp->b_flags, (flags & BUF_X_WRFLAGS));
564}
765c9de3 565
91447636
A
566void
567buf_clearflags(buf_t bp, int32_t flags) {
1c79356b 568
91447636
A
569 CLR(bp->b_flags, (flags & BUF_X_WRFLAGS));
570}
1c79356b 571
91447636
A
572int32_t
573buf_flags(buf_t bp) {
574
575 return ((bp->b_flags & BUF_X_RDFLAGS));
576}
1c79356b 577
91447636
A
578void
579buf_reset(buf_t bp, int32_t io_flags) {
580
2d21ac55 581 CLR(bp->b_flags, (B_READ | B_WRITE | B_ERROR | B_DONE | B_INVAL | B_ASYNC | B_NOCACHE | B_FUA));
91447636 582 SET(bp->b_flags, (io_flags & (B_ASYNC | B_READ | B_WRITE | B_NOCACHE)));
1c79356b 583
91447636
A
584 bp->b_error = 0;
585}
1c79356b 586
91447636
A
587uint32_t
588buf_count(buf_t bp) {
589
590 return (bp->b_bcount);
591}
765c9de3 592
91447636
A
593void
594buf_setcount(buf_t bp, uint32_t bcount) {
595
596 bp->b_bcount = bcount;
1c79356b
A
597}
598
91447636
A
599uint32_t
600buf_size(buf_t bp) {
601
602 return (bp->b_bufsize);
603}
1c79356b 604
91447636
A
605void
606buf_setsize(buf_t bp, uint32_t bufsize) {
607
608 bp->b_bufsize = bufsize;
609}
1c79356b 610
91447636
A
611uint32_t
612buf_resid(buf_t bp) {
613
614 return (bp->b_resid);
615}
b4c24cb9 616
91447636
A
617void
618buf_setresid(buf_t bp, uint32_t resid) {
619
620 bp->b_resid = resid;
621}
1c79356b 622
91447636
A
623uint32_t
624buf_dirtyoff(buf_t bp) {
1c79356b 625
91447636
A
626 return (bp->b_dirtyoff);
627}
1c79356b 628
91447636
A
629uint32_t
630buf_dirtyend(buf_t bp) {
1c79356b 631
91447636 632 return (bp->b_dirtyend);
1c79356b 633}
1c79356b 634
91447636
A
635void
636buf_setdirtyoff(buf_t bp, uint32_t dirtyoff) {
637
638 bp->b_dirtyoff = dirtyoff;
639}
1c79356b 640
91447636
A
641void
642buf_setdirtyend(buf_t bp, uint32_t dirtyend) {
643
644 bp->b_dirtyend = dirtyend;
1c79356b
A
645}
646
91447636
A
647uintptr_t
648buf_dataptr(buf_t bp) {
649
650 return (bp->b_datap);
651}
1c79356b 652
91447636
A
653void
654buf_setdataptr(buf_t bp, uintptr_t data) {
655
656 bp->b_datap = data;
657}
658
659vnode_t
660buf_vnode(buf_t bp) {
661
662 return (bp->b_vp);
663}
664
665void
666buf_setvnode(buf_t bp, vnode_t vp) {
667
668 bp->b_vp = vp;
669}
670
671
672void *
673buf_callback(buf_t bp)
674{
91447636
A
675 if ( !(bp->b_flags & B_CALL) )
676 return ((void *) NULL);
677
678 return ((void *)bp->b_iodone);
679}
680
681
682errno_t
683buf_setcallback(buf_t bp, void (*callback)(buf_t, void *), void *transaction)
684{
3e170ce0
A
685 assert(!ISSET(bp->b_flags, B_FILTER) && ISSET(bp->b_lflags, BL_BUSY));
686
91447636
A
687 if (callback)
688 bp->b_flags |= (B_CALL | B_ASYNC);
689 else
690 bp->b_flags &= ~B_CALL;
691 bp->b_transaction = transaction;
692 bp->b_iodone = callback;
693
694 return (0);
695}
696
697errno_t
698buf_setupl(buf_t bp, upl_t upl, uint32_t offset)
699{
700
701 if ( !(bp->b_lflags & BL_IOBUF) )
702 return (EINVAL);
703
704 if (upl)
705 bp->b_flags |= B_CLUSTER;
706 else
707 bp->b_flags &= ~B_CLUSTER;
708 bp->b_upl = upl;
709 bp->b_uploffset = offset;
710
711 return (0);
712}
713
714buf_t
715buf_clone(buf_t bp, int io_offset, int io_size, void (*iodone)(buf_t, void *), void *arg)
716{
717 buf_t io_bp;
718
719 if (io_offset < 0 || io_size < 0)
720 return (NULL);
721
722 if ((unsigned)(io_offset + io_size) > (unsigned)bp->b_bcount)
723 return (NULL);
724
725 if (bp->b_flags & B_CLUSTER) {
726 if (io_offset && ((bp->b_uploffset + io_offset) & PAGE_MASK))
727 return (NULL);
728
729 if (((bp->b_uploffset + io_offset + io_size) & PAGE_MASK) && ((io_offset + io_size) < bp->b_bcount))
730 return (NULL);
731 }
732 io_bp = alloc_io_buf(bp->b_vp, 0);
733
2d21ac55 734 io_bp->b_flags = bp->b_flags & (B_COMMIT_UPL | B_META | B_PAGEIO | B_CLUSTER | B_PHYS | B_RAW | B_ASYNC | B_READ | B_FUA);
91447636
A
735
736 if (iodone) {
737 io_bp->b_transaction = arg;
738 io_bp->b_iodone = iodone;
739 io_bp->b_flags |= B_CALL;
740 }
741 if (bp->b_flags & B_CLUSTER) {
742 io_bp->b_upl = bp->b_upl;
743 io_bp->b_uploffset = bp->b_uploffset + io_offset;
744 } else {
745 io_bp->b_datap = (uintptr_t)(((char *)bp->b_datap) + io_offset);
746 }
747 io_bp->b_bcount = io_size;
748
749 return (io_bp);
750}
751
752
6d2010ae
A
753int
754buf_shadow(buf_t bp)
755{
756 if (bp->b_lflags & BL_SHADOW)
757 return 1;
758 return 0;
759}
760
761
762buf_t
763buf_create_shadow_priv(buf_t bp, boolean_t force_copy, uintptr_t external_storage, void (*iodone)(buf_t, void *), void *arg)
764{
765 return (buf_create_shadow_internal(bp, force_copy, external_storage, iodone, arg, 1));
766}
767
768buf_t
769buf_create_shadow(buf_t bp, boolean_t force_copy, uintptr_t external_storage, void (*iodone)(buf_t, void *), void *arg)
770{
771 return (buf_create_shadow_internal(bp, force_copy, external_storage, iodone, arg, 0));
772}
773
774
775static buf_t
776buf_create_shadow_internal(buf_t bp, boolean_t force_copy, uintptr_t external_storage, void (*iodone)(buf_t, void *), void *arg, int priv)
777{
778 buf_t io_bp;
779
780 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_START, bp, 0, 0, 0, 0);
781
782 if ( !(bp->b_flags & B_META) || (bp->b_lflags & BL_IOBUF)) {
783
784 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END, bp, 0, 0, 0, 0);
785 return (NULL);
786 }
787#ifdef BUF_MAKE_PRIVATE
788 if (bp->b_shadow_ref && bp->b_data_ref == 0 && external_storage == 0)
789 panic("buf_create_shadow: %p is in the private state (%d, %d)", bp, bp->b_shadow_ref, bp->b_data_ref);
790#endif
791 io_bp = alloc_io_buf(bp->b_vp, priv);
792
793 io_bp->b_flags = bp->b_flags & (B_META | B_ZALLOC | B_ASYNC | B_READ | B_FUA);
794 io_bp->b_blkno = bp->b_blkno;
795 io_bp->b_lblkno = bp->b_lblkno;
796
797 if (iodone) {
798 io_bp->b_transaction = arg;
799 io_bp->b_iodone = iodone;
800 io_bp->b_flags |= B_CALL;
801 }
802 if (force_copy == FALSE) {
803 io_bp->b_bcount = bp->b_bcount;
804 io_bp->b_bufsize = bp->b_bufsize;
805
806 if (external_storage) {
807 io_bp->b_datap = external_storage;
808#ifdef BUF_MAKE_PRIVATE
809 io_bp->b_data_store = NULL;
810#endif
811 } else {
812 io_bp->b_datap = bp->b_datap;
813#ifdef BUF_MAKE_PRIVATE
814 io_bp->b_data_store = bp;
815#endif
816 }
817 *(buf_t *)(&io_bp->b_orig) = bp;
818
819 lck_mtx_lock_spin(buf_mtxp);
820
821 io_bp->b_lflags |= BL_SHADOW;
822 io_bp->b_shadow = bp->b_shadow;
823 bp->b_shadow = io_bp;
824 bp->b_shadow_ref++;
825
826#ifdef BUF_MAKE_PRIVATE
827 if (external_storage)
828 io_bp->b_lflags |= BL_EXTERNAL;
829 else
830 bp->b_data_ref++;
831#endif
832 lck_mtx_unlock(buf_mtxp);
833 } else {
834 if (external_storage) {
835#ifdef BUF_MAKE_PRIVATE
836 io_bp->b_lflags |= BL_EXTERNAL;
837#endif
838 io_bp->b_bcount = bp->b_bcount;
839 io_bp->b_bufsize = bp->b_bufsize;
840 io_bp->b_datap = external_storage;
841 } else {
842 allocbuf(io_bp, bp->b_bcount);
843
844 io_bp->b_lflags |= BL_IOBUF_ALLOC;
845 }
846 bcopy((caddr_t)bp->b_datap, (caddr_t)io_bp->b_datap, bp->b_bcount);
847
848#ifdef BUF_MAKE_PRIVATE
849 io_bp->b_data_store = NULL;
850#endif
851 }
852 KERNEL_DEBUG(0xbbbbc000 | DBG_FUNC_END, bp, bp->b_shadow_ref, 0, io_bp, 0);
853
854 return (io_bp);
855}
856
857
858#ifdef BUF_MAKE_PRIVATE
859errno_t
860buf_make_private(buf_t bp)
861{
862 buf_t ds_bp;
863 buf_t t_bp;
864 struct buf my_buf;
865
866 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_START, bp, bp->b_shadow_ref, 0, 0, 0);
867
868 if (bp->b_shadow_ref == 0 || bp->b_data_ref == 0 || ISSET(bp->b_lflags, BL_SHADOW)) {
869
870 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END, bp, bp->b_shadow_ref, 0, EINVAL, 0);
871 return (EINVAL);
872 }
873 my_buf.b_flags = B_META;
874 my_buf.b_datap = (uintptr_t)NULL;
875 allocbuf(&my_buf, bp->b_bcount);
876
877 bcopy((caddr_t)bp->b_datap, (caddr_t)my_buf.b_datap, bp->b_bcount);
878
879 lck_mtx_lock_spin(buf_mtxp);
880
881 for (t_bp = bp->b_shadow; t_bp; t_bp = t_bp->b_shadow) {
882 if ( !ISSET(bp->b_lflags, BL_EXTERNAL))
883 break;
884 }
885 ds_bp = t_bp;
886
887 if (ds_bp == NULL && bp->b_data_ref)
888 panic("buf_make_private: b_data_ref != 0 && ds_bp == NULL");
889
890 if (ds_bp && (bp->b_data_ref == 0 || bp->b_shadow_ref == 0))
891 panic("buf_make_private: ref_count == 0 && ds_bp != NULL");
892
893 if (ds_bp == NULL) {
894 lck_mtx_unlock(buf_mtxp);
895
896 buf_free_meta_store(&my_buf);
897
898 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END, bp, bp->b_shadow_ref, 0, EINVAL, 0);
899 return (EINVAL);
900 }
901 for (t_bp = bp->b_shadow; t_bp; t_bp = t_bp->b_shadow) {
902 if ( !ISSET(t_bp->b_lflags, BL_EXTERNAL))
903 t_bp->b_data_store = ds_bp;
904 }
905 ds_bp->b_data_ref = bp->b_data_ref;
906
907 bp->b_data_ref = 0;
908 bp->b_datap = my_buf.b_datap;
909
910 lck_mtx_unlock(buf_mtxp);
911
912 KERNEL_DEBUG(0xbbbbc004 | DBG_FUNC_END, bp, bp->b_shadow_ref, 0, 0, 0);
913 return (0);
914}
915#endif
916
91447636
A
917
918void
919buf_setfilter(buf_t bp, void (*filter)(buf_t, void *), void *transaction,
6d2010ae 920 void (**old_iodone)(buf_t, void *), void **old_transaction)
91447636 921{
3e170ce0
A
922 assert(ISSET(bp->b_lflags, BL_BUSY));
923
6d2010ae
A
924 if (old_iodone)
925 *old_iodone = bp->b_iodone;
91447636 926 if (old_transaction)
6d2010ae 927 *old_transaction = bp->b_transaction;
91447636
A
928
929 bp->b_transaction = transaction;
930 bp->b_iodone = filter;
2d21ac55
A
931 if (filter)
932 bp->b_flags |= B_FILTER;
933 else
934 bp->b_flags &= ~B_FILTER;
91447636
A
935}
936
937
938daddr64_t
939buf_blkno(buf_t bp) {
940
941 return (bp->b_blkno);
942}
943
944daddr64_t
945buf_lblkno(buf_t bp) {
946
947 return (bp->b_lblkno);
948}
949
950void
951buf_setblkno(buf_t bp, daddr64_t blkno) {
952
953 bp->b_blkno = blkno;
954}
955
956void
957buf_setlblkno(buf_t bp, daddr64_t lblkno) {
958
959 bp->b_lblkno = lblkno;
960}
961
962dev_t
963buf_device(buf_t bp) {
964
965 return (bp->b_dev);
966}
967
968errno_t
969buf_setdevice(buf_t bp, vnode_t vp) {
970
971 if ((vp->v_type != VBLK) && (vp->v_type != VCHR))
972 return EINVAL;
973 bp->b_dev = vp->v_rdev;
974
975 return 0;
976}
977
978
979void *
980buf_drvdata(buf_t bp) {
981
982 return (bp->b_drvdata);
983}
984
985void
986buf_setdrvdata(buf_t bp, void *drvdata) {
987
988 bp->b_drvdata = drvdata;
989}
990
991void *
992buf_fsprivate(buf_t bp) {
993
994 return (bp->b_fsprivate);
995}
996
997void
998buf_setfsprivate(buf_t bp, void *fsprivate) {
999
1000 bp->b_fsprivate = fsprivate;
1001}
1002
b0d623f7 1003kauth_cred_t
91447636
A
1004buf_rcred(buf_t bp) {
1005
1006 return (bp->b_rcred);
1007}
1008
b0d623f7 1009kauth_cred_t
91447636
A
1010buf_wcred(buf_t bp) {
1011
1012 return (bp->b_wcred);
1013}
1014
1015void *
1016buf_upl(buf_t bp) {
1017
1018 return (bp->b_upl);
1019}
1020
1021uint32_t
1022buf_uploffset(buf_t bp) {
1023
1024 return ((uint32_t)(bp->b_uploffset));
1025}
1026
1027proc_t
1028buf_proc(buf_t bp) {
1029
1030 return (bp->b_proc);
1031}
1032
1033
1034errno_t
1035buf_map(buf_t bp, caddr_t *io_addr)
1036{
1037 buf_t real_bp;
b0d623f7 1038 vm_offset_t vaddr;
91447636
A
1039 kern_return_t kret;
1040
1041 if ( !(bp->b_flags & B_CLUSTER)) {
1042 *io_addr = (caddr_t)bp->b_datap;
1043 return (0);
1044 }
1045 real_bp = (buf_t)(bp->b_real_bp);
1046
1047 if (real_bp && real_bp->b_datap) {
1048 /*
1049 * b_real_bp is only valid if B_CLUSTER is SET
1050 * if it's non-zero, than someone did a cluster_bp call
1051 * if the backing physical pages were already mapped
1052 * in before the call to cluster_bp (non-zero b_datap),
1053 * than we just use that mapping
1054 */
1055 *io_addr = (caddr_t)real_bp->b_datap;
1056 return (0);
1057 }
1058 kret = ubc_upl_map(bp->b_upl, &vaddr); /* Map it in */
1059
1060 if (kret != KERN_SUCCESS) {
2d21ac55 1061 *io_addr = NULL;
91447636
A
1062
1063 return(ENOMEM);
1064 }
1065 vaddr += bp->b_uploffset;
1066
1067 *io_addr = (caddr_t)vaddr;
1068
1069 return (0);
1070}
1071
1072errno_t
1073buf_unmap(buf_t bp)
1074{
1075 buf_t real_bp;
1076 kern_return_t kret;
1077
1078 if ( !(bp->b_flags & B_CLUSTER))
1079 return (0);
1080 /*
1081 * see buf_map for the explanation
1082 */
1083 real_bp = (buf_t)(bp->b_real_bp);
1084
1085 if (real_bp && real_bp->b_datap)
1086 return (0);
1087
2d21ac55
A
1088 if ((bp->b_lflags & BL_IOBUF) &&
1089 ((bp->b_flags & (B_PAGEIO | B_READ)) != (B_PAGEIO | B_READ))) {
91447636 1090 /*
2d21ac55
A
1091 * ignore pageins... the 'right' thing will
1092 * happen due to the way we handle speculative
1093 * clusters...
1094 *
91447636
A
1095 * when we commit these pages, we'll hit
1096 * it with UPL_COMMIT_INACTIVE which
1097 * will clear the reference bit that got
1098 * turned on when we touched the mapping
1099 */
1100 bp->b_flags |= B_AGE;
1101 }
1102 kret = ubc_upl_unmap(bp->b_upl);
1103
1104 if (kret != KERN_SUCCESS)
1105 return (EINVAL);
1106 return (0);
1107}
1108
1109
1110void
1111buf_clear(buf_t bp) {
1112 caddr_t baddr;
1113
1114 if (buf_map(bp, &baddr) == 0) {
1115 bzero(baddr, bp->b_bcount);
1116 buf_unmap(bp);
1117 }
1118 bp->b_resid = 0;
1119}
1120
91447636
A
1121/*
1122 * Read or write a buffer that is not contiguous on disk.
1123 * buffer is marked done/error at the conclusion
1124 */
1125static int
1126buf_strategy_fragmented(vnode_t devvp, buf_t bp, off_t f_offset, size_t contig_bytes)
1127{
1128 vnode_t vp = buf_vnode(bp);
1129 buf_t io_bp; /* For reading or writing a single block */
1130 int io_direction;
1131 int io_resid;
1132 size_t io_contig_bytes;
1133 daddr64_t io_blkno;
1134 int error = 0;
1135 int bmap_flags;
1136
1137 /*
1138 * save our starting point... the bp was already mapped
1139 * in buf_strategy before we got called
1140 * no sense doing it again.
1141 */
1142 io_blkno = bp->b_blkno;
1143 /*
1144 * Make sure we redo this mapping for the next I/O
1145 * i.e. this can never be a 'permanent' mapping
1146 */
1147 bp->b_blkno = bp->b_lblkno;
1148
1149 /*
1150 * Get an io buffer to do the deblocking
1151 */
1152 io_bp = alloc_io_buf(devvp, 0);
1153
1154 io_bp->b_lblkno = bp->b_lblkno;
1155 io_bp->b_datap = bp->b_datap;
1156 io_resid = bp->b_bcount;
1157 io_direction = bp->b_flags & B_READ;
1158 io_contig_bytes = contig_bytes;
1159
1160 if (bp->b_flags & B_READ)
1161 bmap_flags = VNODE_READ;
1162 else
1163 bmap_flags = VNODE_WRITE;
1164
1165 for (;;) {
1166 if (io_blkno == -1)
1167 /*
1168 * this is unexepected, but we'll allow for it
1169 */
1170 bzero((caddr_t)io_bp->b_datap, (int)io_contig_bytes);
1171 else {
1172 io_bp->b_bcount = io_contig_bytes;
1173 io_bp->b_bufsize = io_contig_bytes;
1174 io_bp->b_resid = io_contig_bytes;
1175 io_bp->b_blkno = io_blkno;
1176
1177 buf_reset(io_bp, io_direction);
2d21ac55 1178
91447636 1179 /*
2d21ac55 1180 * Call the device to do the I/O and wait for it. Make sure the appropriate party is charged for write
91447636 1181 */
2d21ac55
A
1182
1183 if (!ISSET(bp->b_flags, B_READ))
1184 OSAddAtomic(1, &devvp->v_numoutput);
1185
91447636
A
1186 if ((error = VNOP_STRATEGY(io_bp)))
1187 break;
1188 if ((error = (int)buf_biowait(io_bp)))
1189 break;
1190 if (io_bp->b_resid) {
1191 io_resid -= (io_contig_bytes - io_bp->b_resid);
1192 break;
1193 }
1194 }
1195 if ((io_resid -= io_contig_bytes) == 0)
1196 break;
1197 f_offset += io_contig_bytes;
1198 io_bp->b_datap += io_contig_bytes;
1199
1200 /*
1201 * Map the current position to a physical block number
1202 */
1203 if ((error = VNOP_BLOCKMAP(vp, f_offset, io_resid, &io_blkno, &io_contig_bytes, NULL, bmap_flags, NULL)))
1204 break;
1205 }
1206 buf_free(io_bp);
1207
1208 if (error)
1209 buf_seterror(bp, error);
1210 bp->b_resid = io_resid;
1211 /*
1212 * This I/O is now complete
1213 */
1214 buf_biodone(bp);
1215
1216 return error;
1217}
1218
1219
1220/*
1221 * struct vnop_strategy_args {
1222 * struct buf *a_bp;
1223 * } *ap;
1224 */
1225errno_t
1226buf_strategy(vnode_t devvp, void *ap)
1227{
1228 buf_t bp = ((struct vnop_strategy_args *)ap)->a_bp;
1229 vnode_t vp = bp->b_vp;
1230 int bmap_flags;
1231 errno_t error;
6d2010ae
A
1232#if CONFIG_DTRACE
1233 int dtrace_io_start_flag = 0; /* We only want to trip the io:::start
39236c6e 1234 * probe once, with the true physical
6d2010ae
A
1235 * block in place (b_blkno)
1236 */
1237
1238#endif
91447636
A
1239
1240 if (vp == NULL || vp->v_type == VCHR || vp->v_type == VBLK)
1241 panic("buf_strategy: b_vp == NULL || vtype == VCHR | VBLK\n");
1242 /*
1243 * associate the physical device with
1244 * with this buf_t even if we don't
1245 * end up issuing the I/O...
1246 */
1247 bp->b_dev = devvp->v_rdev;
1248
1249 if (bp->b_flags & B_READ)
1250 bmap_flags = VNODE_READ;
1251 else
1252 bmap_flags = VNODE_WRITE;
1253
1254 if ( !(bp->b_flags & B_CLUSTER)) {
1255
1256 if ( (bp->b_upl) ) {
1257 /*
1258 * we have a UPL associated with this bp
1259 * go through cluster_bp which knows how
1260 * to deal with filesystem block sizes
1261 * that aren't equal to the page size
1262 */
6d2010ae 1263 DTRACE_IO1(start, buf_t, bp);
91447636
A
1264 return (cluster_bp(bp));
1265 }
1266 if (bp->b_blkno == bp->b_lblkno) {
316670eb 1267 off_t f_offset;
91447636
A
1268 size_t contig_bytes;
1269
1270 if ((error = VNOP_BLKTOOFF(vp, bp->b_lblkno, &f_offset))) {
6d2010ae 1271 DTRACE_IO1(start, buf_t, bp);
91447636
A
1272 buf_seterror(bp, error);
1273 buf_biodone(bp);
1274
316670eb 1275 return (error);
91447636 1276 }
316670eb
A
1277
1278 if ((error = VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))) {
6d2010ae 1279 DTRACE_IO1(start, buf_t, bp);
91447636
A
1280 buf_seterror(bp, error);
1281 buf_biodone(bp);
1282
1283 return (error);
1284 }
316670eb 1285
6d2010ae
A
1286 DTRACE_IO1(start, buf_t, bp);
1287#if CONFIG_DTRACE
1288 dtrace_io_start_flag = 1;
1289#endif /* CONFIG_DTRACE */
316670eb 1290
b0d623f7
A
1291 if ((bp->b_blkno == -1) || (contig_bytes == 0)) {
1292 /* Set block number to force biodone later */
1293 bp->b_blkno = -1;
91447636 1294 buf_clear(bp);
b0d623f7 1295 }
6d2010ae 1296 else if ((long)contig_bytes < bp->b_bcount) {
91447636 1297 return (buf_strategy_fragmented(devvp, bp, f_offset, contig_bytes));
6d2010ae 1298 }
91447636 1299 }
6d2010ae
A
1300
1301#if CONFIG_DTRACE
1302 if (dtrace_io_start_flag == 0) {
1303 DTRACE_IO1(start, buf_t, bp);
1304 dtrace_io_start_flag = 1;
1305 }
1306#endif /* CONFIG_DTRACE */
1307
91447636
A
1308 if (bp->b_blkno == -1) {
1309 buf_biodone(bp);
1310 return (0);
1311 }
1312 }
6d2010ae
A
1313
1314#if CONFIG_DTRACE
1315 if (dtrace_io_start_flag == 0)
1316 DTRACE_IO1(start, buf_t, bp);
1317#endif /* CONFIG_DTRACE */
1318
316670eb
A
1319#if CONFIG_PROTECT
1320 /* Capture f_offset in the bufattr*/
3e170ce0
A
1321 cpx_t cpx = bufattr_cpx(buf_attr(bp));
1322 if (cpx) {
316670eb 1323 /* No need to go here for older EAs */
39037602 1324 if(cpx_use_offset_for_iv(cpx) && !cpx_synthetic_offset_for_iv(cpx)) {
316670eb
A
1325 off_t f_offset;
1326 if ((error = VNOP_BLKTOOFF(bp->b_vp, bp->b_lblkno, &f_offset)))
1327 return error;
1328
1329 /*
1330 * Attach the file offset to this buffer. The
1331 * bufattr attributes will be passed down the stack
1332 * until they reach IOFlashStorage. IOFlashStorage
1333 * will retain the offset in a local variable when it
1334 * issues its I/Os to the NAND controller.
1335 *
1336 * Note that LwVM may end up splitting this I/O
1337 * into sub-I/Os if it crosses a chunk boundary. In this
1338 * case, LwVM will update this field when it dispatches
1339 * each I/O to IOFlashStorage. But from our perspective
1340 * we have only issued a single I/O.
1341 */
3e170ce0 1342 buf_setcpoff(bp, f_offset);
fe8ab488 1343 CP_DEBUG((CPDBG_OFFSET_IO | DBG_FUNC_NONE), (uint32_t) f_offset, (uint32_t) bp->b_lblkno, (uint32_t) bp->b_blkno, (uint32_t) bp->b_bcount, 0);
316670eb
A
1344 }
1345 }
1346#endif
1347
91447636
A
1348 /*
1349 * we can issue the I/O because...
1350 * either B_CLUSTER is set which
1351 * means that the I/O is properly set
1352 * up to be a multiple of the page size, or
1353 * we were able to successfully set up the
39236c6e 1354 * physical block mapping
91447636 1355 */
39236c6e
A
1356 error = VOCALL(devvp->v_op, VOFFSET(vnop_strategy), ap);
1357 DTRACE_FSINFO(strategy, vnode_t, vp);
1358 return (error);
91447636
A
1359}
1360
1361
1362
1363buf_t
1364buf_alloc(vnode_t vp)
1365{
39037602 1366 return(alloc_io_buf(vp, is_vm_privileged()));
91447636
A
1367}
1368
1369void
1370buf_free(buf_t bp) {
1371
1372 free_io_buf(bp);
1373}
1374
1375
2d21ac55
A
1376/*
1377 * iterate buffers for the specified vp.
1378 * if BUF_SCAN_DIRTY is set, do the dirty list
1379 * if BUF_SCAN_CLEAN is set, do the clean list
1380 * if neither flag is set, default to BUF_SCAN_DIRTY
1381 * if BUF_NOTIFY_BUSY is set, call the callout function using a NULL bp for busy pages
1382 */
1383
1384struct buf_iterate_info_t {
1385 int flag;
1386 struct buflists *listhead;
1387};
91447636
A
1388
1389void
2d21ac55
A
1390buf_iterate(vnode_t vp, int (*callout)(buf_t, void *), int flags, void *arg)
1391{
91447636
A
1392 buf_t bp;
1393 int retval;
1394 struct buflists local_iterblkhd;
1395 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
2d21ac55
A
1396 int notify_busy = flags & BUF_NOTIFY_BUSY;
1397 struct buf_iterate_info_t list[2];
1398 int num_lists, i;
91447636
A
1399
1400 if (flags & BUF_SKIP_LOCKED)
1401 lock_flags |= BAC_SKIP_LOCKED;
1402 if (flags & BUF_SKIP_NONLOCKED)
1403 lock_flags |= BAC_SKIP_NONLOCKED;
1404
2d21ac55
A
1405 if ( !(flags & (BUF_SCAN_DIRTY | BUF_SCAN_CLEAN)))
1406 flags |= BUF_SCAN_DIRTY;
1407
1408 num_lists = 0;
1409
1410 if (flags & BUF_SCAN_DIRTY) {
1411 list[num_lists].flag = VBI_DIRTY;
1412 list[num_lists].listhead = &vp->v_dirtyblkhd;
1413 num_lists++;
1414 }
1415 if (flags & BUF_SCAN_CLEAN) {
1416 list[num_lists].flag = VBI_CLEAN;
1417 list[num_lists].listhead = &vp->v_cleanblkhd;
1418 num_lists++;
91447636 1419 }
91447636 1420
2d21ac55
A
1421 for (i = 0; i < num_lists; i++) {
1422 lck_mtx_lock(buf_mtxp);
1423
1424 if (buf_iterprepare(vp, &local_iterblkhd, list[i].flag)) {
1425 lck_mtx_unlock(buf_mtxp);
1426 continue;
1427 }
1428 while (!LIST_EMPTY(&local_iterblkhd)) {
1429 bp = LIST_FIRST(&local_iterblkhd);
1430 LIST_REMOVE(bp, b_vnbufs);
1431 LIST_INSERT_HEAD(list[i].listhead, bp, b_vnbufs);
91447636 1432
2d21ac55
A
1433 if (buf_acquire_locked(bp, lock_flags, 0, 0)) {
1434 if (notify_busy) {
1435 bp = NULL;
1436 } else {
1437 continue;
1438 }
1439 }
91447636 1440
2d21ac55 1441 lck_mtx_unlock(buf_mtxp);
91447636 1442
2d21ac55 1443 retval = callout(bp, arg);
91447636 1444
2d21ac55
A
1445 switch (retval) {
1446 case BUF_RETURNED:
1447 if (bp)
1448 buf_brelse(bp);
1449 break;
1450 case BUF_CLAIMED:
1451 break;
1452 case BUF_RETURNED_DONE:
1453 if (bp)
1454 buf_brelse(bp);
1455 lck_mtx_lock(buf_mtxp);
1456 goto out;
1457 case BUF_CLAIMED_DONE:
1458 lck_mtx_lock(buf_mtxp);
1459 goto out;
1460 }
1461 lck_mtx_lock(buf_mtxp);
1462 } /* while list has more nodes */
1463 out:
1464 buf_itercomplete(vp, &local_iterblkhd, list[i].flag);
1465 lck_mtx_unlock(buf_mtxp);
1466 } /* for each list */
1467} /* buf_iterate */
91447636
A
1468
1469
1470/*
1471 * Flush out and invalidate all buffers associated with a vnode.
1472 */
1473int
1474buf_invalidateblks(vnode_t vp, int flags, int slpflag, int slptimeo)
1475{
1476 buf_t bp;
6d2010ae 1477 int aflags;
91447636
A
1478 int error = 0;
1479 int must_rescan = 1;
1480 struct buflists local_iterblkhd;
1481
b0d623f7
A
1482
1483 if (LIST_EMPTY(&vp->v_cleanblkhd) && LIST_EMPTY(&vp->v_dirtyblkhd))
1484 return (0);
1485
91447636
A
1486 lck_mtx_lock(buf_mtxp);
1487
1488 for (;;) {
1489 if (must_rescan == 0)
1490 /*
1491 * the lists may not be empty, but all that's left at this
1492 * point are metadata or B_LOCKED buffers which are being
1493 * skipped... we know this because we made it through both
1494 * the clean and dirty lists without dropping buf_mtxp...
1495 * each time we drop buf_mtxp we bump "must_rescan"
1496 */
1497 break;
1498 if (LIST_EMPTY(&vp->v_cleanblkhd) && LIST_EMPTY(&vp->v_dirtyblkhd))
1499 break;
1500 must_rescan = 0;
1501 /*
1502 * iterate the clean list
1503 */
1504 if (buf_iterprepare(vp, &local_iterblkhd, VBI_CLEAN)) {
1505 goto try_dirty_list;
1506 }
1507 while (!LIST_EMPTY(&local_iterblkhd)) {
6d2010ae 1508
91447636
A
1509 bp = LIST_FIRST(&local_iterblkhd);
1510
1511 LIST_REMOVE(bp, b_vnbufs);
1512 LIST_INSERT_HEAD(&vp->v_cleanblkhd, bp, b_vnbufs);
1513
1514 /*
1515 * some filesystems distinguish meta data blocks with a negative logical block #
1516 */
1517 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
1518 continue;
1519
6d2010ae
A
1520 aflags = BAC_REMOVE;
1521
1522 if ( !(flags & BUF_INVALIDATE_LOCKED) )
1523 aflags |= BAC_SKIP_LOCKED;
1524
1525 if ( (error = (int)buf_acquire_locked(bp, aflags, slpflag, slptimeo)) ) {
91447636
A
1526 if (error == EDEADLK)
1527 /*
1528 * this buffer was marked B_LOCKED...
1529 * we didn't drop buf_mtxp, so we
1530 * we don't need to rescan
1531 */
1532 continue;
1533 if (error == EAGAIN) {
1534 /*
1535 * found a busy buffer... we blocked and
1536 * dropped buf_mtxp, so we're going to
1537 * need to rescan after this pass is completed
1538 */
1539 must_rescan++;
1540 continue;
1541 }
1542 /*
1543 * got some kind of 'real' error out of the msleep
1544 * in buf_acquire_locked, terminate the scan and return the error
1545 */
1546 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1547
1548 lck_mtx_unlock(buf_mtxp);
1549 return (error);
1550 }
1551 lck_mtx_unlock(buf_mtxp);
1552
6d2010ae
A
1553 if (bp->b_flags & B_LOCKED)
1554 KERNEL_DEBUG(0xbbbbc038, bp, 0, 0, 0, 0);
1555
1556 CLR(bp->b_flags, B_LOCKED);
91447636
A
1557 SET(bp->b_flags, B_INVAL);
1558 buf_brelse(bp);
1559
1560 lck_mtx_lock(buf_mtxp);
1561
1562 /*
1563 * by dropping buf_mtxp, we allow new
1564 * buffers to be added to the vnode list(s)
1565 * we'll have to rescan at least once more
1566 * if the queues aren't empty
1567 */
1568 must_rescan++;
1569 }
1570 buf_itercomplete(vp, &local_iterblkhd, VBI_CLEAN);
1571
1572try_dirty_list:
1573 /*
1574 * Now iterate on dirty blks
1575 */
1576 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY)) {
1577 continue;
1578 }
1579 while (!LIST_EMPTY(&local_iterblkhd)) {
1580 bp = LIST_FIRST(&local_iterblkhd);
1581
1582 LIST_REMOVE(bp, b_vnbufs);
1583 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
1584
1585 /*
1586 * some filesystems distinguish meta data blocks with a negative logical block #
1587 */
1588 if ((flags & BUF_SKIP_META) && (bp->b_lblkno < 0 || ISSET(bp->b_flags, B_META)))
1589 continue;
1590
6d2010ae
A
1591 aflags = BAC_REMOVE;
1592
1593 if ( !(flags & BUF_INVALIDATE_LOCKED) )
1594 aflags |= BAC_SKIP_LOCKED;
1595
1596 if ( (error = (int)buf_acquire_locked(bp, aflags, slpflag, slptimeo)) ) {
91447636
A
1597 if (error == EDEADLK)
1598 /*
1599 * this buffer was marked B_LOCKED...
1600 * we didn't drop buf_mtxp, so we
1601 * we don't need to rescan
1602 */
1603 continue;
1604 if (error == EAGAIN) {
1605 /*
1606 * found a busy buffer... we blocked and
1607 * dropped buf_mtxp, so we're going to
1608 * need to rescan after this pass is completed
1609 */
1610 must_rescan++;
1611 continue;
1612 }
1613 /*
1614 * got some kind of 'real' error out of the msleep
1615 * in buf_acquire_locked, terminate the scan and return the error
1616 */
1617 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1618
1619 lck_mtx_unlock(buf_mtxp);
1620 return (error);
1621 }
1622 lck_mtx_unlock(buf_mtxp);
1623
6d2010ae
A
1624 if (bp->b_flags & B_LOCKED)
1625 KERNEL_DEBUG(0xbbbbc038, bp, 0, 0, 1, 0);
1626
1627 CLR(bp->b_flags, B_LOCKED);
91447636
A
1628 SET(bp->b_flags, B_INVAL);
1629
1630 if (ISSET(bp->b_flags, B_DELWRI) && (flags & BUF_WRITE_DATA))
1631 (void) VNOP_BWRITE(bp);
1632 else
1633 buf_brelse(bp);
1634
1635 lck_mtx_lock(buf_mtxp);
1636 /*
1637 * by dropping buf_mtxp, we allow new
1638 * buffers to be added to the vnode list(s)
1639 * we'll have to rescan at least once more
1640 * if the queues aren't empty
1641 */
1642 must_rescan++;
1643 }
1644 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1645 }
1646 lck_mtx_unlock(buf_mtxp);
1647
1648 return (0);
1649}
1650
1651void
2d21ac55 1652buf_flushdirtyblks(vnode_t vp, int wait, int flags, const char *msg) {
316670eb
A
1653
1654 (void) buf_flushdirtyblks_skipinfo(vp, wait, flags, msg);
1655 return;
1656}
1657
1658int
1659buf_flushdirtyblks_skipinfo(vnode_t vp, int wait, int flags, const char *msg) {
91447636
A
1660 buf_t bp;
1661 int writes_issued = 0;
1662 errno_t error;
1663 int busy = 0;
1664 struct buflists local_iterblkhd;
1665 int lock_flags = BAC_NOWAIT | BAC_REMOVE;
316670eb 1666 int any_locked = 0;
91447636
A
1667
1668 if (flags & BUF_SKIP_LOCKED)
1669 lock_flags |= BAC_SKIP_LOCKED;
1670 if (flags & BUF_SKIP_NONLOCKED)
1671 lock_flags |= BAC_SKIP_NONLOCKED;
1672loop:
1673 lck_mtx_lock(buf_mtxp);
1674
1675 if (buf_iterprepare(vp, &local_iterblkhd, VBI_DIRTY) == 0) {
1676 while (!LIST_EMPTY(&local_iterblkhd)) {
1677 bp = LIST_FIRST(&local_iterblkhd);
1678 LIST_REMOVE(bp, b_vnbufs);
1679 LIST_INSERT_HEAD(&vp->v_dirtyblkhd, bp, b_vnbufs);
316670eb
A
1680
1681 if ((error = buf_acquire_locked(bp, lock_flags, 0, 0)) == EBUSY) {
1682 busy++;
1683 }
1684 if (error) {
1685 /*
1686 * If we passed in BUF_SKIP_LOCKED or BUF_SKIP_NONLOCKED,
1687 * we may want to do somethign differently if a locked or unlocked
1688 * buffer was encountered (depending on the arg specified).
1689 * In this case, we know that one of those two was set, and the
1690 * buf acquisition failed above.
1691 *
1692 * If it failed with EDEADLK, then save state which can be emitted
1693 * later on to the caller. Most callers should not care.
1694 */
1695 if (error == EDEADLK) {
1696 any_locked++;
1697 }
1698 continue;
1699 }
91447636
A
1700 lck_mtx_unlock(buf_mtxp);
1701
1702 bp->b_flags &= ~B_LOCKED;
1703
1704 /*
1705 * Wait for I/O associated with indirect blocks to complete,
1706 * since there is no way to quickly wait for them below.
1707 */
1708 if ((bp->b_vp == vp) || (wait == 0))
1709 (void) buf_bawrite(bp);
1710 else
1711 (void) VNOP_BWRITE(bp);
1712 writes_issued++;
1713
1714 lck_mtx_lock(buf_mtxp);
1715 }
1716 buf_itercomplete(vp, &local_iterblkhd, VBI_DIRTY);
1717 }
1718 lck_mtx_unlock(buf_mtxp);
1719
1720 if (wait) {
1721 (void)vnode_waitforwrites(vp, 0, 0, 0, msg);
1722
1723 if (vp->v_dirtyblkhd.lh_first && busy) {
1724 /*
1725 * we had one or more BUSY buffers on
1726 * the dirtyblock list... most likely
1727 * these are due to delayed writes that
1728 * were moved to the bclean queue but
1729 * have not yet been 'written'.
1730 * if we issued some writes on the
1731 * previous pass, we try again immediately
1732 * if we didn't, we'll sleep for some time
1733 * to allow the state to change...
1734 */
1735 if (writes_issued == 0) {
1736 (void)tsleep((caddr_t)&vp->v_numoutput,
1737 PRIBIO + 1, "vnode_flushdirtyblks", hz/20);
1738 }
1739 writes_issued = 0;
1740 busy = 0;
1741
1742 goto loop;
1743 }
1744 }
316670eb
A
1745
1746 return any_locked;
91447636
A
1747}
1748
1749
1750/*
1751 * called with buf_mtxp held...
1752 * this lock protects the queue manipulation
1753 */
1754static int
1755buf_iterprepare(vnode_t vp, struct buflists *iterheadp, int flags)
1756{
1757 struct buflists * listheadp;
1758
1759 if (flags & VBI_DIRTY)
1760 listheadp = &vp->v_dirtyblkhd;
1761 else
1762 listheadp = &vp->v_cleanblkhd;
1763
1764 while (vp->v_iterblkflags & VBI_ITER) {
1765 vp->v_iterblkflags |= VBI_ITERWANT;
2d21ac55 1766 msleep(&vp->v_iterblkflags, buf_mtxp, 0, "buf_iterprepare", NULL);
91447636
A
1767 }
1768 if (LIST_EMPTY(listheadp)) {
1769 LIST_INIT(iterheadp);
1770 return(EINVAL);
1771 }
1772 vp->v_iterblkflags |= VBI_ITER;
1773
1774 iterheadp->lh_first = listheadp->lh_first;
1775 listheadp->lh_first->b_vnbufs.le_prev = &iterheadp->lh_first;
1776 LIST_INIT(listheadp);
1777
1778 return(0);
1779}
1780
1781/*
1782 * called with buf_mtxp held...
1783 * this lock protects the queue manipulation
1784 */
1785static void
1786buf_itercomplete(vnode_t vp, struct buflists *iterheadp, int flags)
1787{
1788 struct buflists * listheadp;
1789 buf_t bp;
1790
1791 if (flags & VBI_DIRTY)
1792 listheadp = &vp->v_dirtyblkhd;
1793 else
1794 listheadp = &vp->v_cleanblkhd;
1795
1796 while (!LIST_EMPTY(iterheadp)) {
1797 bp = LIST_FIRST(iterheadp);
1798 LIST_REMOVE(bp, b_vnbufs);
1799 LIST_INSERT_HEAD(listheadp, bp, b_vnbufs);
1800 }
1801 vp->v_iterblkflags &= ~VBI_ITER;
1802
1803 if (vp->v_iterblkflags & VBI_ITERWANT) {
1804 vp->v_iterblkflags &= ~VBI_ITERWANT;
1805 wakeup(&vp->v_iterblkflags);
1806 }
1807}
1808
1809
1810static void
1811bremfree_locked(buf_t bp)
1812{
1813 struct bqueues *dp = NULL;
2d21ac55 1814 int whichq;
6d2010ae
A
1815
1816 whichq = bp->b_whichq;
1817
1818 if (whichq == -1) {
1819 if (bp->b_shadow_ref == 0)
1820 panic("bremfree_locked: %p not on freelist", bp);
1821 /*
1822 * there are clones pointing to 'bp'...
1823 * therefore, it was not put on a freelist
1824 * when buf_brelse was last called on 'bp'
1825 */
1826 return;
1827 }
91447636
A
1828 /*
1829 * We only calculate the head of the freelist when removing
1830 * the last element of the list as that is the only time that
1831 * it is needed (e.g. to reset the tail pointer).
1832 *
1833 * NB: This makes an assumption about how tailq's are implemented.
1834 */
1835 if (bp->b_freelist.tqe_next == NULL) {
2d21ac55
A
1836 dp = &bufqueues[whichq];
1837
1838 if (dp->tqh_last != &bp->b_freelist.tqe_next)
91447636
A
1839 panic("bremfree: lost tail");
1840 }
1841 TAILQ_REMOVE(dp, bp, b_freelist);
2d21ac55 1842
2d21ac55
A
1843 if (whichq == BQ_LAUNDRY)
1844 blaundrycnt--;
1845
91447636
A
1846 bp->b_whichq = -1;
1847 bp->b_timestamp = 0;
6d2010ae 1848 bp->b_shadow = 0;
91447636
A
1849}
1850
1851/*
1852 * Associate a buffer with a vnode.
2d21ac55 1853 * buf_mtxp must be locked on entry
91447636
A
1854 */
1855static void
2d21ac55 1856bgetvp_locked(vnode_t vp, buf_t bp)
91447636
A
1857{
1858
1859 if (bp->b_vp != vp)
2d21ac55 1860 panic("bgetvp_locked: not free");
91447636
A
1861
1862 if (vp->v_type == VBLK || vp->v_type == VCHR)
1863 bp->b_dev = vp->v_rdev;
1864 else
1865 bp->b_dev = NODEV;
1866 /*
1867 * Insert onto list for new vnode.
1868 */
91447636 1869 bufinsvn(bp, &vp->v_cleanblkhd);
91447636
A
1870}
1871
1872/*
1873 * Disassociate a buffer from a vnode.
2d21ac55 1874 * buf_mtxp must be locked on entry
91447636
A
1875 */
1876static void
2d21ac55 1877brelvp_locked(buf_t bp)
91447636 1878{
91447636
A
1879 /*
1880 * Delete from old vnode list, if on one.
1881 */
91447636
A
1882 if (bp->b_vnbufs.le_next != NOLIST)
1883 bufremvn(bp);
91447636
A
1884
1885 bp->b_vp = (vnode_t)NULL;
1886}
1887
1888/*
1889 * Reassign a buffer from one vnode to another.
1890 * Used to assign file specific control information
1891 * (indirect blocks) to the vnode to which they belong.
1892 */
1893static void
1894buf_reassign(buf_t bp, vnode_t newvp)
1895{
6d2010ae 1896 struct buflists *listheadp;
1c79356b 1897
91447636
A
1898 if (newvp == NULL) {
1899 printf("buf_reassign: NULL");
1900 return;
1901 }
2d21ac55 1902 lck_mtx_lock_spin(buf_mtxp);
91447636
A
1903
1904 /*
1905 * Delete from old vnode list, if on one.
1906 */
1907 if (bp->b_vnbufs.le_next != NOLIST)
1908 bufremvn(bp);
1909 /*
1910 * If dirty, put on list of dirty buffers;
1911 * otherwise insert onto list of clean buffers.
1912 */
1913 if (ISSET(bp->b_flags, B_DELWRI))
1914 listheadp = &newvp->v_dirtyblkhd;
1915 else
1916 listheadp = &newvp->v_cleanblkhd;
1917 bufinsvn(bp, listheadp);
1918
1919 lck_mtx_unlock(buf_mtxp);
1c79356b
A
1920}
1921
91447636
A
1922static __inline__ void
1923bufhdrinit(buf_t bp)
55e303ae 1924{
91447636
A
1925 bzero((char *)bp, sizeof *bp);
1926 bp->b_dev = NODEV;
1927 bp->b_rcred = NOCRED;
1928 bp->b_wcred = NOCRED;
1929 bp->b_vnbufs.le_next = NOLIST;
1930 bp->b_flags = B_INVAL;
1931
1932 return;
55e303ae
A
1933}
1934
1935/*
91447636 1936 * Initialize buffers and hash links for buffers.
55e303ae 1937 */
91447636 1938__private_extern__ void
2d21ac55 1939bufinit(void)
55e303ae 1940{
91447636
A
1941 buf_t bp;
1942 struct bqueues *dp;
1943 int i;
91447636 1944
2d21ac55 1945 nbuf_headers = 0;
91447636
A
1946 /* Initialize the buffer queues ('freelists') and the hash table */
1947 for (dp = bufqueues; dp < &bufqueues[BQUEUES]; dp++)
1948 TAILQ_INIT(dp);
0c530ab8 1949 bufhashtbl = hashinit(nbuf_hashelements, M_CACHE, &bufhash);
91447636 1950
b0d623f7
A
1951 buf_busycount = 0;
1952
91447636 1953 /* Initialize the buffer headers */
0c530ab8 1954 for (i = 0; i < max_nbuf_headers; i++) {
2d21ac55
A
1955 nbuf_headers++;
1956 bp = &buf_headers[i];
91447636
A
1957 bufhdrinit(bp);
1958
91447636 1959 BLISTNONE(bp);
2d21ac55
A
1960 dp = &bufqueues[BQ_EMPTY];
1961 bp->b_whichq = BQ_EMPTY;
1962 bp->b_timestamp = buf_timestamp();
1963 binsheadfree(bp, dp, BQ_EMPTY);
91447636
A
1964 binshash(bp, &invalhash);
1965 }
2d21ac55 1966 boot_nbuf_headers = nbuf_headers;
6d2010ae
A
1967
1968 TAILQ_INIT(&iobufqueue);
1969 TAILQ_INIT(&delaybufqueue);
1970
2d21ac55
A
1971 for (; i < nbuf_headers + niobuf_headers; i++) {
1972 bp = &buf_headers[i];
91447636 1973 bufhdrinit(bp);
2d21ac55 1974 bp->b_whichq = -1;
91447636
A
1975 binsheadfree(bp, &iobufqueue, -1);
1976 }
1977
2d21ac55 1978 /*
91447636
A
1979 * allocate lock group attribute and group
1980 */
2d21ac55 1981 buf_mtx_grp_attr = lck_grp_attr_alloc_init();
91447636
A
1982 buf_mtx_grp = lck_grp_alloc_init("buffer cache", buf_mtx_grp_attr);
1983
1984 /*
1985 * allocate the lock attribute
1986 */
1987 buf_mtx_attr = lck_attr_alloc_init();
91447636
A
1988
1989 /*
1990 * allocate and initialize mutex's for the buffer and iobuffer pools
1991 */
1992 buf_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1993 iobuffer_mtxp = lck_mtx_alloc_init(buf_mtx_grp, buf_mtx_attr);
1994
1995 if (iobuffer_mtxp == NULL)
1996 panic("couldn't create iobuffer mutex");
1997
1998 if (buf_mtxp == NULL)
1999 panic("couldn't create buf mutex");
2000
2001 /*
2002 * allocate and initialize cluster specific global locks...
2003 */
2004 cluster_init();
2005
2006 printf("using %d buffer headers and %d cluster IO buffer headers\n",
2d21ac55 2007 nbuf_headers, niobuf_headers);
91447636
A
2008
2009 /* Set up zones used by the buffer cache */
2010 bufzoneinit();
2011
2012 /* start the bcleanbuf() thread */
2013 bcleanbuf_thread_init();
2014
b0d623f7
A
2015 /* Register a callout for relieving vm pressure */
2016 if (vm_set_buffer_cleanup_callout(buffer_cache_gc) != KERN_SUCCESS) {
2017 panic("Couldn't register buffer cache callout for vm pressure!\n");
2018 }
2019
91447636
A
2020}
2021
2d21ac55
A
2022/*
2023 * Zones for the meta data buffers
2024 */
2025
2026#define MINMETA 512
2027#define MAXMETA 8192
2028
2029struct meta_zone_entry {
2030 zone_t mz_zone;
2031 vm_size_t mz_size;
2032 vm_size_t mz_max;
2033 const char *mz_name;
2034};
2035
2036struct meta_zone_entry meta_zones[] = {
2037 {NULL, (MINMETA * 1), 128 * (MINMETA * 1), "buf.512" },
2038 {NULL, (MINMETA * 2), 64 * (MINMETA * 2), "buf.1024" },
2039 {NULL, (MINMETA * 4), 16 * (MINMETA * 4), "buf.2048" },
2040 {NULL, (MINMETA * 8), 512 * (MINMETA * 8), "buf.4096" },
2041 {NULL, (MINMETA * 16), 512 * (MINMETA * 16), "buf.8192" },
2042 {NULL, 0, 0, "" } /* End */
2043};
2044
2045/*
2046 * Initialize the meta data zones
2047 */
2048static void
2049bufzoneinit(void)
2050{
2051 int i;
2052
2053 for (i = 0; meta_zones[i].mz_size != 0; i++) {
2054 meta_zones[i].mz_zone =
2055 zinit(meta_zones[i].mz_size,
2056 meta_zones[i].mz_max,
2057 PAGE_SIZE,
2058 meta_zones[i].mz_name);
6d2010ae 2059 zone_change(meta_zones[i].mz_zone, Z_CALLERACCT, FALSE);
2d21ac55
A
2060 }
2061 buf_hdr_zone = zinit(sizeof(struct buf), 32, PAGE_SIZE, "buf headers");
6d2010ae 2062 zone_change(buf_hdr_zone, Z_CALLERACCT, FALSE);
2d21ac55
A
2063}
2064
2065static __inline__ zone_t
2066getbufzone(size_t size)
2067{
2068 int i;
2069
2070 if ((size % 512) || (size < MINMETA) || (size > MAXMETA))
2071 panic("getbufzone: incorect size = %lu", size);
2072
2073 for (i = 0; meta_zones[i].mz_size != 0; i++) {
2074 if (meta_zones[i].mz_size >= size)
2075 break;
2076 }
2077
2078 return (meta_zones[i].mz_zone);
2079}
2080
2081
2082
91447636 2083static struct buf *
b0d623f7 2084bio_doread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, int async, int queuetype)
91447636
A
2085{
2086 buf_t bp;
2087
2088 bp = buf_getblk(vp, blkno, size, 0, 0, queuetype);
2089
2090 /*
2091 * If buffer does not have data valid, start a read.
2092 * Note that if buffer is B_INVAL, buf_getblk() won't return it.
2093 * Therefore, it's valid if it's I/O has completed or been delayed.
2094 */
2095 if (!ISSET(bp->b_flags, (B_DONE | B_DELWRI))) {
2096 struct proc *p;
2097
2098 p = current_proc();
2099
2100 /* Start I/O for the buffer (keeping credentials). */
2101 SET(bp->b_flags, B_READ | async);
0c530ab8 2102 if (IS_VALID_CRED(cred) && !IS_VALID_CRED(bp->b_rcred)) {
91447636
A
2103 kauth_cred_ref(cred);
2104 bp->b_rcred = cred;
2105 }
2106
2107 VNOP_STRATEGY(bp);
2108
2109 trace(TR_BREADMISS, pack(vp, size), blkno);
2110
2111 /* Pay for the read. */
39236c6e 2112 if (p && p->p_stats) {
b0d623f7 2113 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_inblock); /* XXX */
39236c6e 2114 }
91447636
A
2115
2116 if (async) {
2117 /*
2118 * since we asked for an ASYNC I/O
2119 * the biodone will do the brelse
2120 * we don't want to pass back a bp
2121 * that we don't 'own'
2122 */
2123 bp = NULL;
2124 }
2125 } else if (async) {
2126 buf_brelse(bp);
2127 bp = NULL;
2128 }
2129
2130 trace(TR_BREADHIT, pack(vp, size), blkno);
2131
2132 return (bp);
55e303ae
A
2133}
2134
2135/*
91447636 2136 * Perform the reads for buf_breadn() and buf_meta_breadn().
55e303ae
A
2137 * Trivial modification to the breada algorithm presented in Bach (p.55).
2138 */
91447636
A
2139static errno_t
2140do_breadn_for_type(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes,
b0d623f7 2141 int nrablks, kauth_cred_t cred, buf_t *bpp, int queuetype)
1c79356b 2142{
91447636
A
2143 buf_t bp;
2144 int i;
1c79356b 2145
55e303ae 2146 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, queuetype);
1c79356b
A
2147
2148 /*
2149 * For each of the read-ahead blocks, start a read, if necessary.
2150 */
2151 for (i = 0; i < nrablks; i++) {
2152 /* If it's in the cache, just go on to next one. */
2153 if (incore(vp, rablks[i]))
2154 continue;
2155
2156 /* Get a buffer for the read-ahead block */
55e303ae 2157 (void) bio_doread(vp, rablks[i], rasizes[i], cred, B_ASYNC, queuetype);
1c79356b
A
2158 }
2159
2160 /* Otherwise, we had to start a read for it; wait until it's valid. */
91447636 2161 return (buf_biowait(bp));
1c79356b
A
2162}
2163
91447636 2164
1c79356b 2165/*
91447636
A
2166 * Read a disk block.
2167 * This algorithm described in Bach (p.54).
1c79356b 2168 */
91447636 2169errno_t
b0d623f7 2170buf_bread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, buf_t *bpp)
91447636
A
2171{
2172 buf_t bp;
2173
2174 /* Get buffer for block. */
2175 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_READ);
2176
2177 /* Wait for the read to complete, and return result. */
2178 return (buf_biowait(bp));
2179}
2180
2181/*
2182 * Read a disk block. [bread() for meta-data]
2183 * This algorithm described in Bach (p.54).
2184 */
2185errno_t
b0d623f7 2186buf_meta_bread(vnode_t vp, daddr64_t blkno, int size, kauth_cred_t cred, buf_t *bpp)
91447636
A
2187{
2188 buf_t bp;
2189
2190 /* Get buffer for block. */
2191 bp = *bpp = bio_doread(vp, blkno, size, cred, 0, BLK_META);
2192
2193 /* Wait for the read to complete, and return result. */
2194 return (buf_biowait(bp));
2195}
2196
2197/*
2198 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2199 */
2200errno_t
b0d623f7 2201buf_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, kauth_cred_t cred, buf_t *bpp)
1c79356b 2202{
91447636
A
2203 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_READ));
2204}
1c79356b 2205
91447636
A
2206/*
2207 * Read-ahead multiple disk blocks. The first is sync, the rest async.
2208 * [buf_breadn() for meta-data]
2209 */
2210errno_t
b0d623f7 2211buf_meta_breadn(vnode_t vp, daddr64_t blkno, int size, daddr64_t *rablks, int *rasizes, int nrablks, kauth_cred_t cred, buf_t *bpp)
91447636
A
2212{
2213 return (do_breadn_for_type(vp, blkno, size, rablks, rasizes, nrablks, cred, bpp, BLK_META));
1c79356b
A
2214}
2215
2216/*
2217 * Block write. Described in Bach (p.56)
2218 */
91447636
A
2219errno_t
2220buf_bwrite(buf_t bp)
1c79356b 2221{
91447636
A
2222 int sync, wasdelayed;
2223 errno_t rv;
2224 proc_t p = current_proc();
2225 vnode_t vp = bp->b_vp;
1c79356b 2226
91447636 2227 if (bp->b_datap == 0) {
55e303ae
A
2228 if (brecover_data(bp) == 0)
2229 return (0);
2230 }
1c79356b
A
2231 /* Remember buffer type, to switch on it later. */
2232 sync = !ISSET(bp->b_flags, B_ASYNC);
2233 wasdelayed = ISSET(bp->b_flags, B_DELWRI);
2234 CLR(bp->b_flags, (B_READ | B_DONE | B_ERROR | B_DELWRI));
91447636
A
2235
2236 if (wasdelayed)
b0d623f7 2237 OSAddAtomicLong(-1, &nbdwrite);
1c79356b
A
2238
2239 if (!sync) {
2240 /*
2241 * If not synchronous, pay for the I/O operation and make
2242 * sure the buf is on the correct vnode queue. We have
2243 * to do this now, because if we don't, the vnode may not
2244 * be properly notified that its I/O has completed.
2245 */
2246 if (wasdelayed)
91447636 2247 buf_reassign(bp, vp);
39236c6e
A
2248 else
2249 if (p && p->p_stats) {
2250 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
39236c6e 2251 }
1c79356b 2252 }
d52fe63f 2253 trace(TR_BUFWRITE, pack(vp, bp->b_bcount), bp->b_lblkno);
1c79356b
A
2254
2255 /* Initiate disk write. Make sure the appropriate party is charged. */
91447636
A
2256
2257 OSAddAtomic(1, &vp->v_numoutput);
1c79356b 2258
91447636 2259 VNOP_STRATEGY(bp);
1c79356b
A
2260
2261 if (sync) {
2262 /*
2263 * If I/O was synchronous, wait for it to complete.
2264 */
91447636 2265 rv = buf_biowait(bp);
1c79356b
A
2266
2267 /*
2268 * Pay for the I/O operation, if it's not been paid for, and
2269 * make sure it's on the correct vnode queue. (async operatings
2270 * were payed for above.)
2271 */
2272 if (wasdelayed)
91447636 2273 buf_reassign(bp, vp);
1c79356b 2274 else
39236c6e
A
2275 if (p && p->p_stats) {
2276 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
39236c6e 2277 }
1c79356b
A
2278
2279 /* Release the buffer. */
39037602 2280 buf_brelse(bp);
1c79356b
A
2281
2282 return (rv);
2283 } else {
2284 return (0);
2285 }
2286}
2287
2288int
2d21ac55 2289vn_bwrite(struct vnop_bwrite_args *ap)
1c79356b 2290{
91447636 2291 return (buf_bwrite(ap->a_bp));
1c79356b
A
2292}
2293
2294/*
2295 * Delayed write.
2296 *
2297 * The buffer is marked dirty, but is not queued for I/O.
2298 * This routine should be used when the buffer is expected
2299 * to be modified again soon, typically a small write that
2300 * partially fills a buffer.
2301 *
2302 * NB: magnetic tapes cannot be delayed; they must be
2303 * written in the order that the writes are requested.
2304 *
2305 * Described in Leffler, et al. (pp. 208-213).
d52fe63f 2306 *
b0d623f7 2307 * Note: With the ability to allocate additional buffer
d52fe63f 2308 * headers, we can get in to the situation where "too" many
91447636
A
2309 * buf_bdwrite()s can create situation where the kernel can create
2310 * buffers faster than the disks can service. Doing a buf_bawrite() in
6d2010ae 2311 * cases where we have "too many" outstanding buf_bdwrite()s avoids that.
1c79356b 2312 */
39037602 2313int
91447636 2314bdwrite_internal(buf_t bp, int return_error)
1c79356b 2315{
91447636
A
2316 proc_t p = current_proc();
2317 vnode_t vp = bp->b_vp;
1c79356b
A
2318
2319 /*
2320 * If the block hasn't been seen before:
2321 * (1) Mark it as having been seen,
2322 * (2) Charge for the write.
2323 * (3) Make sure it's on its vnode's correct block list,
2324 */
2325 if (!ISSET(bp->b_flags, B_DELWRI)) {
2326 SET(bp->b_flags, B_DELWRI);
39236c6e 2327 if (p && p->p_stats) {
b0d623f7 2328 OSIncrementAtomicLong(&p->p_stats->p_ru.ru_oublock); /* XXX */
39236c6e 2329 }
b0d623f7 2330 OSAddAtomicLong(1, &nbdwrite);
91447636 2331 buf_reassign(bp, vp);
1c79356b
A
2332 }
2333
d52fe63f 2334 /*
91447636
A
2335 * if we're not LOCKED, but the total number of delayed writes
2336 * has climbed above 75% of the total buffers in the system
2337 * return an error if the caller has indicated that it can
2338 * handle one in this case, otherwise schedule the I/O now
2339 * this is done to prevent us from allocating tons of extra
2340 * buffers when dealing with virtual disks (i.e. DiskImages),
2341 * because additional buffers are dynamically allocated to prevent
2342 * deadlocks from occurring
2343 *
2344 * however, can't do a buf_bawrite() if the LOCKED bit is set because the
2345 * buffer is part of a transaction and can't go to disk until
2346 * the LOCKED bit is cleared.
d52fe63f 2347 */
2d21ac55 2348 if (!ISSET(bp->b_flags, B_LOCKED) && nbdwrite > ((nbuf_headers/4)*3)) {
9bccf70c
A
2349 if (return_error)
2350 return (EAGAIN);
91447636
A
2351 /*
2352 * If the vnode has "too many" write operations in progress
2353 * wait for them to finish the IO
2354 */
2d21ac55 2355 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, "buf_bdwrite");
91447636
A
2356
2357 return (buf_bawrite(bp));
d52fe63f
A
2358 }
2359
1c79356b
A
2360 /* Otherwise, the "write" is done, so mark and release the buffer. */
2361 SET(bp->b_flags, B_DONE);
91447636 2362 buf_brelse(bp);
9bccf70c 2363 return (0);
1c79356b
A
2364}
2365
91447636
A
2366errno_t
2367buf_bdwrite(buf_t bp)
9bccf70c 2368{
91447636 2369 return (bdwrite_internal(bp, 0));
9bccf70c
A
2370}
2371
2372
1c79356b 2373/*
91447636 2374 * Asynchronous block write; just an asynchronous buf_bwrite().
d52fe63f
A
2375 *
2376 * Note: With the abilitty to allocate additional buffer
2377 * headers, we can get in to the situation where "too" many
91447636 2378 * buf_bawrite()s can create situation where the kernel can create
d52fe63f
A
2379 * buffers faster than the disks can service.
2380 * We limit the number of "in flight" writes a vnode can have to
2381 * avoid this.
1c79356b 2382 */
9bccf70c 2383static int
91447636 2384bawrite_internal(buf_t bp, int throttle)
1c79356b 2385{
91447636 2386 vnode_t vp = bp->b_vp;
d52fe63f
A
2387
2388 if (vp) {
91447636
A
2389 if (throttle)
2390 /*
2391 * If the vnode has "too many" write operations in progress
2392 * wait for them to finish the IO
2393 */
2394 (void)vnode_waitforwrites(vp, VNODE_ASYNC_THROTTLE, 0, 0, (const char *)"buf_bawrite");
2395 else if (vp->v_numoutput >= VNODE_ASYNC_THROTTLE)
2396 /*
2397 * return to the caller and
2398 * let him decide what to do
2399 */
2400 return (EWOULDBLOCK);
d52fe63f 2401 }
1c79356b 2402 SET(bp->b_flags, B_ASYNC);
9bccf70c 2403
91447636 2404 return (VNOP_BWRITE(bp));
9bccf70c
A
2405}
2406
91447636
A
2407errno_t
2408buf_bawrite(buf_t bp)
9bccf70c 2409{
91447636 2410 return (bawrite_internal(bp, 1));
1c79356b
A
2411}
2412
91447636 2413
6d2010ae
A
2414
2415static void
2416buf_free_meta_store(buf_t bp)
2417{
2418 if (bp->b_bufsize) {
2419 if (ISSET(bp->b_flags, B_ZALLOC)) {
2420 zone_t z;
2421
2422 z = getbufzone(bp->b_bufsize);
2423 zfree(z, (void *)bp->b_datap);
2424 } else
2425 kmem_free(kernel_map, bp->b_datap, bp->b_bufsize);
2426
2427 bp->b_datap = (uintptr_t)NULL;
2428 bp->b_bufsize = 0;
2429 }
2430}
2431
2432
2433static buf_t
2434buf_brelse_shadow(buf_t bp)
2435{
2436 buf_t bp_head;
2437 buf_t bp_temp;
2438 buf_t bp_return = NULL;
2439#ifdef BUF_MAKE_PRIVATE
2440 buf_t bp_data;
2441 int data_ref = 0;
2442#endif
316670eb
A
2443 int need_wakeup = 0;
2444
6d2010ae
A
2445 lck_mtx_lock_spin(buf_mtxp);
2446
3e170ce0 2447 __IGNORE_WCASTALIGN(bp_head = (buf_t)bp->b_orig);
6d2010ae
A
2448
2449 if (bp_head->b_whichq != -1)
2450 panic("buf_brelse_shadow: bp_head on freelist %d\n", bp_head->b_whichq);
2451
2452#ifdef BUF_MAKE_PRIVATE
2453 if (bp_data = bp->b_data_store) {
2454 bp_data->b_data_ref--;
2455 /*
2456 * snapshot the ref count so that we can check it
2457 * outside of the lock... we only want the guy going
2458 * from 1 -> 0 to try and release the storage
2459 */
2460 data_ref = bp_data->b_data_ref;
2461 }
2462#endif
2463 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_START, bp, bp_head, bp_head->b_shadow_ref, 0, 0);
2464
2465 bp_head->b_shadow_ref--;
2466
2467 for (bp_temp = bp_head; bp_temp && bp != bp_temp->b_shadow; bp_temp = bp_temp->b_shadow);
2468
2469 if (bp_temp == NULL)
2470 panic("buf_brelse_shadow: bp not on list %p", bp_head);
2471
2472 bp_temp->b_shadow = bp_temp->b_shadow->b_shadow;
2473
2474#ifdef BUF_MAKE_PRIVATE
2475 /*
2476 * we're about to free the current 'owner' of the data buffer and
2477 * there is at least one other shadow buf_t still pointing at it
2478 * so transfer it to the first shadow buf left in the chain
2479 */
2480 if (bp == bp_data && data_ref) {
2481 if ((bp_data = bp_head->b_shadow) == NULL)
2482 panic("buf_brelse_shadow: data_ref mismatch bp(%p)", bp);
2483
2484 for (bp_temp = bp_data; bp_temp; bp_temp = bp_temp->b_shadow)
2485 bp_temp->b_data_store = bp_data;
2486 bp_data->b_data_ref = data_ref;
2487 }
2488#endif
2489 if (bp_head->b_shadow_ref == 0 && bp_head->b_shadow)
2490 panic("buf_relse_shadow: b_shadow != NULL && b_shadow_ref == 0 bp(%p)", bp);
2491 if (bp_head->b_shadow_ref && bp_head->b_shadow == 0)
2492 panic("buf_relse_shadow: b_shadow == NULL && b_shadow_ref != 0 bp(%p)", bp);
2493
2494 if (bp_head->b_shadow_ref == 0) {
2495 if (!ISSET(bp_head->b_lflags, BL_BUSY)) {
2496
2497 CLR(bp_head->b_flags, B_AGE);
2498 bp_head->b_timestamp = buf_timestamp();
2499
2500 if (ISSET(bp_head->b_flags, B_LOCKED)) {
2501 bp_head->b_whichq = BQ_LOCKED;
2502 binstailfree(bp_head, &bufqueues[BQ_LOCKED], BQ_LOCKED);
2503 } else {
2504 bp_head->b_whichq = BQ_META;
2505 binstailfree(bp_head, &bufqueues[BQ_META], BQ_META);
2506 }
2507 } else if (ISSET(bp_head->b_lflags, BL_WAITSHADOW)) {
2508 CLR(bp_head->b_lflags, BL_WAITSHADOW);
2509
2510 bp_return = bp_head;
2511 }
316670eb
A
2512 if (ISSET(bp_head->b_lflags, BL_WANTED_REF)) {
2513 CLR(bp_head->b_lflags, BL_WANTED_REF);
2514 need_wakeup = 1;
2515 }
6d2010ae
A
2516 }
2517 lck_mtx_unlock(buf_mtxp);
39236c6e
A
2518
2519 if (need_wakeup)
316670eb 2520 wakeup(bp_head);
316670eb 2521
6d2010ae
A
2522#ifdef BUF_MAKE_PRIVATE
2523 if (bp == bp_data && data_ref == 0)
2524 buf_free_meta_store(bp);
2525
2526 bp->b_data_store = NULL;
2527#endif
2528 KERNEL_DEBUG(0xbbbbc008 | DBG_FUNC_END, bp, 0, 0, 0, 0);
2529
2530 return (bp_return);
2531}
2532
2533
1c79356b
A
2534/*
2535 * Release a buffer on to the free lists.
2536 * Described in Bach (p. 46).
2537 */
2538void
91447636 2539buf_brelse(buf_t bp)
1c79356b
A
2540{
2541 struct bqueues *bufq;
91447636
A
2542 long whichq;
2543 upl_t upl;
2544 int need_wakeup = 0;
2545 int need_bp_wakeup = 0;
2546
2547
2548 if (bp->b_whichq != -1 || !(bp->b_lflags & BL_BUSY))
2d21ac55 2549 panic("buf_brelse: bad buffer = %p\n", bp);
91447636
A
2550
2551#ifdef JOE_DEBUG
b0d623f7 2552 (void) OSBacktrace(&bp->b_stackbrelse[0], 6);
91447636
A
2553
2554 bp->b_lastbrelse = current_thread();
2555 bp->b_tag = 0;
2556#endif
2557 if (bp->b_lflags & BL_IOBUF) {
6d2010ae
A
2558 buf_t shadow_master_bp = NULL;
2559
2560 if (ISSET(bp->b_lflags, BL_SHADOW))
2561 shadow_master_bp = buf_brelse_shadow(bp);
2562 else if (ISSET(bp->b_lflags, BL_IOBUF_ALLOC))
2563 buf_free_meta_store(bp);
91447636 2564 free_io_buf(bp);
6d2010ae
A
2565
2566 if (shadow_master_bp) {
2567 bp = shadow_master_bp;
2568 goto finish_shadow_master;
2569 }
91447636
A
2570 return;
2571 }
1c79356b
A
2572
2573 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_START,
b0d623f7 2574 bp->b_lblkno * PAGE_SIZE, bp, bp->b_datap,
fa4905b1 2575 bp->b_flags, 0);
1c79356b
A
2576
2577 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
2578
91447636
A
2579 /*
2580 * if we're invalidating a buffer that has the B_FILTER bit
2581 * set then call the b_iodone function so it gets cleaned
2582 * up properly.
2583 *
2584 * the HFS journal code depends on this
2585 */
b4c24cb9 2586 if (ISSET(bp->b_flags, B_META) && ISSET(bp->b_flags, B_INVAL)) {
91447636
A
2587 if (ISSET(bp->b_flags, B_FILTER)) { /* if necessary, call out */
2588 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
6d2010ae 2589 void *arg = bp->b_transaction;
b4c24cb9 2590
91447636 2591 CLR(bp->b_flags, B_FILTER); /* but note callout done */
b4c24cb9 2592 bp->b_iodone = NULL;
91447636 2593 bp->b_transaction = NULL;
b4c24cb9
A
2594
2595 if (iodone_func == NULL) {
2d21ac55 2596 panic("brelse: bp @ %p has NULL b_iodone!\n", bp);
b4c24cb9 2597 }
91447636 2598 (*iodone_func)(bp, arg);
b4c24cb9
A
2599 }
2600 }
91447636
A
2601 /*
2602 * I/O is done. Cleanup the UPL state
2603 */
2604 upl = bp->b_upl;
2605
2606 if ( !ISSET(bp->b_flags, B_META) && UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
1c79356b 2607 kern_return_t kret;
1c79356b
A
2608 int upl_flags;
2609
6d2010ae 2610 if (upl == NULL) {
1c79356b 2611 if ( !ISSET(bp->b_flags, B_INVAL)) {
0b4e3aa0 2612 kret = ubc_create_upl(bp->b_vp,
91447636
A
2613 ubc_blktooff(bp->b_vp, bp->b_lblkno),
2614 bp->b_bufsize,
2615 &upl,
2616 NULL,
2617 UPL_PRECIOUS);
2618
1c79356b 2619 if (kret != KERN_SUCCESS)
91447636 2620 panic("brelse: Failed to create UPL");
b0d623f7
A
2621#if UPL_DEBUG
2622 upl_ubc_alias_set(upl, (uintptr_t) bp, (uintptr_t) 5);
91447636
A
2623#endif /* UPL_DEBUG */
2624 }
1c79356b 2625 } else {
91447636 2626 if (bp->b_datap) {
55e303ae
A
2627 kret = ubc_upl_unmap(upl);
2628
2629 if (kret != KERN_SUCCESS)
91447636
A
2630 panic("ubc_upl_unmap failed");
2631 bp->b_datap = (uintptr_t)NULL;
55e303ae 2632 }
1c79356b
A
2633 }
2634 if (upl) {
1c79356b 2635 if (bp->b_flags & (B_ERROR | B_INVAL)) {
91447636 2636 if (bp->b_flags & (B_READ | B_INVAL))
1c79356b
A
2637 upl_flags = UPL_ABORT_DUMP_PAGES;
2638 else
2639 upl_flags = 0;
91447636 2640
0b4e3aa0 2641 ubc_upl_abort(upl, upl_flags);
1c79356b 2642 } else {
91447636
A
2643 if (ISSET(bp->b_flags, B_DELWRI | B_WASDIRTY))
2644 upl_flags = UPL_COMMIT_SET_DIRTY ;
2645 else
2646 upl_flags = UPL_COMMIT_CLEAR_DIRTY ;
2647
0b4e3aa0 2648 ubc_upl_commit_range(upl, 0, bp->b_bufsize, upl_flags |
91447636 2649 UPL_COMMIT_INACTIVATE | UPL_COMMIT_FREE_ON_EMPTY);
1c79356b 2650 }
91447636 2651 bp->b_upl = NULL;
1c79356b
A
2652 }
2653 } else {
91447636 2654 if ( (upl) )
2d21ac55 2655 panic("brelse: UPL set for non VREG; vp=%p", bp->b_vp);
1c79356b
A
2656 }
2657
1c79356b 2658 /*
91447636 2659 * If it's locked, don't report an error; try again later.
1c79356b 2660 */
1c79356b
A
2661 if (ISSET(bp->b_flags, (B_LOCKED|B_ERROR)) == (B_LOCKED|B_ERROR))
2662 CLR(bp->b_flags, B_ERROR);
91447636
A
2663 /*
2664 * If it's not cacheable, or an error, mark it invalid.
2665 */
1c79356b
A
2666 if (ISSET(bp->b_flags, (B_NOCACHE|B_ERROR)))
2667 SET(bp->b_flags, B_INVAL);
91447636 2668
b0d623f7
A
2669 if ((bp->b_bufsize <= 0) ||
2670 ISSET(bp->b_flags, B_INVAL) ||
2671 (ISSET(bp->b_lflags, BL_WANTDEALLOC) && !ISSET(bp->b_flags, B_DELWRI))) {
6d2010ae
A
2672
2673 boolean_t delayed_buf_free_meta_store = FALSE;
2674
1c79356b 2675 /*
2d21ac55
A
2676 * If it's invalid or empty, dissociate it from its vnode,
2677 * release its storage if B_META, and
2678 * clean it up a bit and put it on the EMPTY queue
1c79356b 2679 */
91447636 2680 if (ISSET(bp->b_flags, B_DELWRI))
b0d623f7 2681 OSAddAtomicLong(-1, &nbdwrite);
91447636 2682
2d21ac55 2683 if (ISSET(bp->b_flags, B_META)) {
6d2010ae
A
2684 if (bp->b_shadow_ref)
2685 delayed_buf_free_meta_store = TRUE;
2686 else
2687 buf_free_meta_store(bp);
2d21ac55 2688 }
91447636 2689 /*
2d21ac55 2690 * nuke any credentials we were holding
91447636 2691 */
6d2010ae
A
2692 buf_release_credentials(bp);
2693
2694 lck_mtx_lock_spin(buf_mtxp);
2695
2696 if (bp->b_shadow_ref) {
2697 SET(bp->b_lflags, BL_WAITSHADOW);
2698
2699 lck_mtx_unlock(buf_mtxp);
2700
2701 return;
2d21ac55 2702 }
6d2010ae 2703 if (delayed_buf_free_meta_store == TRUE) {
91447636 2704
6d2010ae
A
2705 lck_mtx_unlock(buf_mtxp);
2706finish_shadow_master:
2707 buf_free_meta_store(bp);
91447636 2708
6d2010ae
A
2709 lck_mtx_lock_spin(buf_mtxp);
2710 }
2711 CLR(bp->b_flags, (B_META | B_ZALLOC | B_DELWRI | B_LOCKED | B_AGE | B_ASYNC | B_NOCACHE | B_FUA));
2d21ac55
A
2712
2713 if (bp->b_vp)
2714 brelvp_locked(bp);
2715
2716 bremhash(bp);
2717 BLISTNONE(bp);
2718 binshash(bp, &invalhash);
2719
6d2010ae
A
2720 bp->b_whichq = BQ_EMPTY;
2721 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
1c79356b 2722 } else {
6d2010ae 2723
1c79356b
A
2724 /*
2725 * It has valid data. Put it on the end of the appropriate
2726 * queue, so that it'll stick around for as long as possible.
2727 */
2728 if (ISSET(bp->b_flags, B_LOCKED))
2729 whichq = BQ_LOCKED; /* locked in core */
2730 else if (ISSET(bp->b_flags, B_META))
2731 whichq = BQ_META; /* meta-data */
2732 else if (ISSET(bp->b_flags, B_AGE))
2733 whichq = BQ_AGE; /* stale but valid data */
2734 else
2735 whichq = BQ_LRU; /* valid data */
1c79356b 2736 bufq = &bufqueues[whichq];
91447636 2737
2d21ac55 2738 bp->b_timestamp = buf_timestamp();
91447636 2739
6d2010ae
A
2740 lck_mtx_lock_spin(buf_mtxp);
2741
2742 /*
2743 * the buf_brelse_shadow routine doesn't take 'ownership'
2744 * of the parent buf_t... it updates state that is protected by
2745 * the buf_mtxp, and checks for BL_BUSY to determine whether to
2746 * put the buf_t back on a free list. b_shadow_ref is protected
2747 * by the lock, and since we have not yet cleared B_BUSY, we need
2748 * to check it while holding the lock to insure that one of us
2749 * puts this buf_t back on a free list when it is safe to do so
2750 */
2751 if (bp->b_shadow_ref == 0) {
2752 CLR(bp->b_flags, (B_AGE | B_ASYNC | B_NOCACHE));
2753 bp->b_whichq = whichq;
2754 binstailfree(bp, bufq, whichq);
2755 } else {
2756 /*
2757 * there are still cloned buf_t's pointing
2758 * at this guy... need to keep it off the
2759 * freelists until a buf_brelse is done on
2760 * the last clone
2761 */
2762 CLR(bp->b_flags, (B_ASYNC | B_NOCACHE));
2763 }
1c79356b 2764 }
91447636
A
2765 if (needbuffer) {
2766 /*
2767 * needbuffer is a global
2768 * we're currently using buf_mtxp to protect it
2769 * delay doing the actual wakeup until after
2770 * we drop buf_mtxp
2771 */
2772 needbuffer = 0;
2773 need_wakeup = 1;
2774 }
2775 if (ISSET(bp->b_lflags, BL_WANTED)) {
2776 /*
2777 * delay the actual wakeup until after we
2778 * clear BL_BUSY and we've dropped buf_mtxp
2779 */
2780 need_bp_wakeup = 1;
2781 }
2782 /*
2783 * Unlock the buffer.
2784 */
2785 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
b0d623f7 2786 buf_busycount--;
1c79356b 2787
91447636 2788 lck_mtx_unlock(buf_mtxp);
1c79356b 2789
91447636
A
2790 if (need_wakeup) {
2791 /*
2792 * Wake up any processes waiting for any buffer to become free.
2793 */
2794 wakeup(&needbuffer);
2795 }
2796 if (need_bp_wakeup) {
2797 /*
2798 * Wake up any proceeses waiting for _this_ buffer to become free.
2799 */
2800 wakeup(bp);
2801 }
1c79356b 2802 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 388)) | DBG_FUNC_END,
b0d623f7 2803 bp, bp->b_datap, bp->b_flags, 0, 0);
1c79356b
A
2804}
2805
2806/*
2807 * Determine if a block is in the cache.
2808 * Just look on what would be its hash chain. If it's there, return
2809 * a pointer to it, unless it's marked invalid. If it's marked invalid,
2810 * we normally don't return the buffer, unless the caller explicitly
2811 * wants us to.
2812 */
91447636
A
2813static boolean_t
2814incore(vnode_t vp, daddr64_t blkno)
2815{
2816 boolean_t retval;
2d21ac55 2817 struct bufhashhdr *dp;
91447636 2818
2d21ac55 2819 dp = BUFHASH(vp, blkno);
91447636 2820
2d21ac55
A
2821 lck_mtx_lock_spin(buf_mtxp);
2822
2823 if (incore_locked(vp, blkno, dp))
91447636
A
2824 retval = TRUE;
2825 else
2826 retval = FALSE;
2827 lck_mtx_unlock(buf_mtxp);
2828
2829 return (retval);
2830}
2831
2832
2833static buf_t
2d21ac55 2834incore_locked(vnode_t vp, daddr64_t blkno, struct bufhashhdr *dp)
1c79356b
A
2835{
2836 struct buf *bp;
1c79356b 2837
1c79356b 2838 /* Search hash chain */
2d21ac55 2839 for (bp = dp->lh_first; bp != NULL; bp = bp->b_hash.le_next) {
1c79356b 2840 if (bp->b_lblkno == blkno && bp->b_vp == vp &&
91447636 2841 !ISSET(bp->b_flags, B_INVAL)) {
1c79356b 2842 return (bp);
91447636 2843 }
1c79356b 2844 }
2d21ac55 2845 return (NULL);
1c79356b
A
2846}
2847
39236c6e 2848
316670eb
A
2849void
2850buf_wait_for_shadow_io(vnode_t vp, daddr64_t blkno)
2851{
2852 buf_t bp;
2853 struct bufhashhdr *dp;
2854
2855 dp = BUFHASH(vp, blkno);
2856
2857 lck_mtx_lock_spin(buf_mtxp);
2858
2859 for (;;) {
2860 if ((bp = incore_locked(vp, blkno, dp)) == NULL)
2861 break;
2862
2863 if (bp->b_shadow_ref == 0)
2864 break;
2865
2866 SET(bp->b_lflags, BL_WANTED_REF);
fa4905b1 2867
316670eb
A
2868 (void) msleep(bp, buf_mtxp, PSPIN | (PRIBIO+1), "buf_wait_for_shadow", NULL);
2869 }
2870 lck_mtx_unlock(buf_mtxp);
2871}
2872
fa4905b1 2873/* XXX FIXME -- Update the comment to reflect the UBC changes (please) -- */
1c79356b
A
2874/*
2875 * Get a block of requested size that is associated with
2876 * a given vnode and block offset. If it is found in the
2877 * block cache, mark it as having been found, make it busy
2878 * and return it. Otherwise, return an empty block of the
2879 * correct size. It is up to the caller to insure that the
2880 * cached blocks be of the correct size.
2881 */
91447636
A
2882buf_t
2883buf_getblk(vnode_t vp, daddr64_t blkno, int size, int slpflag, int slptimeo, int operation)
1c79356b 2884{
91447636
A
2885 buf_t bp;
2886 int err;
1c79356b
A
2887 upl_t upl;
2888 upl_page_info_t *pl;
1c79356b 2889 kern_return_t kret;
91447636
A
2890 int ret_only_valid;
2891 struct timespec ts;
2892 int upl_flags;
2d21ac55 2893 struct bufhashhdr *dp;
1c79356b 2894
1c79356b 2895 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_START,
b0d623f7 2896 (uintptr_t)(blkno * PAGE_SIZE), size, operation, 0, 0);
1c79356b 2897
91447636
A
2898 ret_only_valid = operation & BLK_ONLYVALID;
2899 operation &= ~BLK_ONLYVALID;
2d21ac55 2900 dp = BUFHASH(vp, blkno);
91447636 2901start:
2d21ac55 2902 lck_mtx_lock_spin(buf_mtxp);
b0d623f7 2903
2d21ac55 2904 if ((bp = incore_locked(vp, blkno, dp))) {
91447636
A
2905 /*
2906 * Found in the Buffer Cache
2907 */
2908 if (ISSET(bp->b_lflags, BL_BUSY)) {
2909 /*
2910 * but is busy
2911 */
1c79356b
A
2912 switch (operation) {
2913 case BLK_READ:
2914 case BLK_WRITE:
2915 case BLK_META:
91447636 2916 SET(bp->b_lflags, BL_WANTED);
1c79356b 2917 bufstats.bufs_busyincore++;
91447636
A
2918
2919 /*
2920 * don't retake the mutex after being awakened...
2921 * the time out is in msecs
2922 */
2923 ts.tv_sec = (slptimeo/1000);
2924 ts.tv_nsec = (slptimeo % 1000) * 10 * NSEC_PER_USEC * 1000;
2925
b0d623f7
A
2926 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 396)) | DBG_FUNC_NONE,
2927 (uintptr_t)blkno, size, operation, 0, 0);
2928
91447636
A
2929 err = msleep(bp, buf_mtxp, slpflag | PDROP | (PRIBIO + 1), "buf_getblk", &ts);
2930
1c79356b
A
2931 /*
2932 * Callers who call with PCATCH or timeout are
2933 * willing to deal with the NULL pointer
2934 */
91447636 2935 if (err && ((slpflag & PCATCH) || ((err == EWOULDBLOCK) && slptimeo)))
1c79356b
A
2936 return (NULL);
2937 goto start;
2938 /*NOTREACHED*/
1c79356b 2939
1c79356b 2940 default:
91447636
A
2941 /*
2942 * unknown operation requested
2943 */
2944 panic("getblk: paging or unknown operation for incore busy buffer - %x\n", operation);
1c79356b
A
2945 /*NOTREACHED*/
2946 break;
2947 }
2948 } else {
d190cdc3
A
2949 int clear_bdone;
2950
91447636
A
2951 /*
2952 * buffer in core and not busy
2953 */
91447636
A
2954 SET(bp->b_lflags, BL_BUSY);
2955 SET(bp->b_flags, B_CACHE);
b0d623f7 2956 buf_busycount++;
2d21ac55 2957
91447636 2958 bremfree_locked(bp);
1c79356b 2959 bufstats.bufs_incore++;
91447636
A
2960
2961 lck_mtx_unlock(buf_mtxp);
2d21ac55
A
2962#ifdef JOE_DEBUG
2963 bp->b_owner = current_thread();
2964 bp->b_tag = 1;
2965#endif
2966 if ( (bp->b_upl) )
2967 panic("buffer has UPL, but not marked BUSY: %p", bp);
1c79356b 2968
d190cdc3
A
2969 clear_bdone = FALSE;
2970 if (!ret_only_valid) {
2971 /*
2972 * If the number bytes that are valid is going
2973 * to increase (even if we end up not doing a
2974 * reallocation through allocbuf) we have to read
2975 * the new size first.
2976 *
2977 * This is required in cases where we doing a read
2978 * modify write of a already valid data on disk but
2979 * in cases where the data on disk beyond (blkno + b_bcount)
2980 * is invalid, we may end up doing extra I/O.
2981 */
2982 if (operation == BLK_META && bp->b_bcount < size) {
2983 /*
2984 * Since we are going to read in the whole size first
2985 * we first have to ensure that any pending delayed write
2986 * is flushed to disk first.
2987 */
2988 if (ISSET(bp->b_flags, B_DELWRI)) {
2989 CLR(bp->b_flags, B_CACHE);
2990 buf_bwrite(bp);
2991 goto start;
2992 }
2993 /*
2994 * clear B_DONE before returning from
2995 * this function so that the caller can
2996 * can issue a read for the new size.
2997 */
2998 clear_bdone = TRUE;
2999 }
3000
3001 if (bp->b_bufsize != size)
3002 allocbuf(bp, size);
3003 }
1c79356b 3004
91447636 3005 upl_flags = 0;
1c79356b 3006 switch (operation) {
1c79356b 3007 case BLK_WRITE:
91447636
A
3008 /*
3009 * "write" operation: let the UPL subsystem
3010 * know that we intend to modify the buffer
3011 * cache pages we're gathering.
3012 */
3013 upl_flags |= UPL_WILL_MODIFY;
3014 case BLK_READ:
3015 upl_flags |= UPL_PRECIOUS;
3016 if (UBCINFOEXISTS(bp->b_vp) && bp->b_bufsize) {
0b4e3aa0 3017 kret = ubc_create_upl(vp,
91447636
A
3018 ubc_blktooff(vp, bp->b_lblkno),
3019 bp->b_bufsize,
3020 &upl,
3021 &pl,
3022 upl_flags);
1c79356b 3023 if (kret != KERN_SUCCESS)
91447636 3024 panic("Failed to create UPL");
1c79356b 3025
91447636 3026 bp->b_upl = upl;
1c79356b 3027
91447636
A
3028 if (upl_valid_page(pl, 0)) {
3029 if (upl_dirty_page(pl, 0))
3030 SET(bp->b_flags, B_WASDIRTY);
3031 else
3032 CLR(bp->b_flags, B_WASDIRTY);
3033 } else
3034 CLR(bp->b_flags, (B_DONE | B_CACHE | B_WASDIRTY | B_DELWRI));
1c79356b 3035
b0d623f7 3036 kret = ubc_upl_map(upl, (vm_offset_t*)&(bp->b_datap));
1c79356b 3037
9bccf70c 3038 if (kret != KERN_SUCCESS)
91447636 3039 panic("getblk: ubc_upl_map() failed with (%d)", kret);
1c79356b
A
3040 }
3041 break;
3042
3043 case BLK_META:
3044 /*
3045 * VM is not involved in IO for the meta data
3046 * buffer already has valid data
3047 */
1c79356b
A
3048 break;
3049
3050 default:
91447636 3051 panic("getblk: paging or unknown operation for incore buffer- %d\n", operation);
1c79356b
A
3052 /*NOTREACHED*/
3053 break;
3054 }
d190cdc3
A
3055
3056 if (clear_bdone)
3057 CLR(bp->b_flags, B_DONE);
1c79356b
A
3058 }
3059 } else { /* not incore() */
3060 int queue = BQ_EMPTY; /* Start with no preference */
1c79356b 3061
91447636
A
3062 if (ret_only_valid) {
3063 lck_mtx_unlock(buf_mtxp);
3064 return (NULL);
1c79356b 3065 }
2d21ac55 3066 if ((vnode_isreg(vp) == 0) || (UBCINFOEXISTS(vp) == 0) /*|| (vnode_issystem(vp) == 1)*/)
91447636
A
3067 operation = BLK_META;
3068
1c79356b 3069 if ((bp = getnewbuf(slpflag, slptimeo, &queue)) == NULL)
b0d623f7 3070 goto start;
91447636
A
3071
3072 /*
3073 * getnewbuf may block for a number of different reasons...
3074 * if it does, it's then possible for someone else to
3075 * create a buffer for the same block and insert it into
3076 * the hash... if we see it incore at this point we dump
3077 * the buffer we were working on and start over
3078 */
2d21ac55 3079 if (incore_locked(vp, blkno, dp)) {
0b4e3aa0
A
3080 SET(bp->b_flags, B_INVAL);
3081 binshash(bp, &invalhash);
91447636
A
3082
3083 lck_mtx_unlock(buf_mtxp);
3084
3085 buf_brelse(bp);
0b4e3aa0
A
3086 goto start;
3087 }
b4c24cb9
A
3088 /*
3089 * NOTE: YOU CAN NOT BLOCK UNTIL binshash() HAS BEEN
3090 * CALLED! BE CAREFUL.
3091 */
0b4e3aa0 3092
1c79356b 3093 /*
91447636 3094 * mark the buffer as B_META if indicated
1c79356b 3095 * so that when buffer is released it will goto META queue
1c79356b 3096 */
91447636
A
3097 if (operation == BLK_META)
3098 SET(bp->b_flags, B_META);
9bccf70c
A
3099
3100 bp->b_blkno = bp->b_lblkno = blkno;
3101 bp->b_vp = vp;
3102
0b4e3aa0
A
3103 /*
3104 * Insert in the hash so that incore() can find it
3105 */
3106 binshash(bp, BUFHASH(vp, blkno));
3107
2d21ac55 3108 bgetvp_locked(vp, bp);
91447636 3109
2d21ac55 3110 lck_mtx_unlock(buf_mtxp);
9bccf70c 3111
1c79356b
A
3112 allocbuf(bp, size);
3113
91447636 3114 upl_flags = 0;
1c79356b
A
3115 switch (operation) {
3116 case BLK_META:
91447636
A
3117 /*
3118 * buffer data is invalid...
3119 *
3120 * I don't want to have to retake buf_mtxp,
3121 * so the miss and vmhits counters are done
3122 * with Atomic updates... all other counters
3123 * in bufstats are protected with either
3124 * buf_mtxp or iobuffer_mtxp
3125 */
b0d623f7 3126 OSAddAtomicLong(1, &bufstats.bufs_miss);
1c79356b
A
3127 break;
3128
1c79356b 3129 case BLK_WRITE:
91447636
A
3130 /*
3131 * "write" operation: let the UPL subsystem know
3132 * that we intend to modify the buffer cache pages
3133 * we're gathering.
3134 */
3135 upl_flags |= UPL_WILL_MODIFY;
3136 case BLK_READ:
3137 { off_t f_offset;
3138 size_t contig_bytes;
3139 int bmap_flags;
1c79356b 3140
3e170ce0
A
3141#if DEVELOPMENT || DEBUG
3142 /*
3143 * Apple implemented file systems use UBC excludively; they should
3144 * not call in here."
3145 */
3146 const char* excldfs[] = {"hfs", "afpfs", "smbfs", "acfs",
3147 "exfat", "msdos", "webdav", NULL};
3148
3149 for (int i = 0; excldfs[i] != NULL; i++) {
3150 if (vp->v_mount &&
3151 !strcmp(vp->v_mount->mnt_vfsstat.f_fstypename,
3152 excldfs[i])) {
3153 panic("%s %s calls buf_getblk",
3154 excldfs[i],
3155 operation == BLK_READ ? "BLK_READ" : "BLK_WRITE");
3156 }
3157 }
3158#endif
3159
91447636 3160 if ( (bp->b_upl) )
2d21ac55 3161 panic("bp already has UPL: %p",bp);
1c79356b 3162
91447636
A
3163 f_offset = ubc_blktooff(vp, blkno);
3164
3165 upl_flags |= UPL_PRECIOUS;
0b4e3aa0 3166 kret = ubc_create_upl(vp,
91447636
A
3167 f_offset,
3168 bp->b_bufsize,
3169 &upl,
3170 &pl,
3171 upl_flags);
1c79356b 3172
91447636
A
3173 if (kret != KERN_SUCCESS)
3174 panic("Failed to create UPL");
b0d623f7
A
3175#if UPL_DEBUG
3176 upl_ubc_alias_set(upl, (uintptr_t) bp, (uintptr_t) 4);
91447636
A
3177#endif /* UPL_DEBUG */
3178 bp->b_upl = upl;
1c79356b
A
3179
3180 if (upl_valid_page(pl, 0)) {
1c79356b 3181
91447636
A
3182 if (operation == BLK_READ)
3183 bmap_flags = VNODE_READ;
3184 else
3185 bmap_flags = VNODE_WRITE;
1c79356b 3186
91447636 3187 SET(bp->b_flags, B_CACHE | B_DONE);
1c79356b 3188
b0d623f7 3189 OSAddAtomicLong(1, &bufstats.bufs_vmhits);
1c79356b 3190
91447636
A
3191 bp->b_validoff = 0;
3192 bp->b_dirtyoff = 0;
1c79356b 3193
91447636
A
3194 if (upl_dirty_page(pl, 0)) {
3195 /* page is dirty */
3196 SET(bp->b_flags, B_WASDIRTY);
1c79356b 3197
91447636
A
3198 bp->b_validend = bp->b_bcount;
3199 bp->b_dirtyend = bp->b_bcount;
1c79356b 3200 } else {
91447636
A
3201 /* page is clean */
3202 bp->b_validend = bp->b_bcount;
3203 bp->b_dirtyend = 0;
1c79356b 3204 }
91447636
A
3205 /*
3206 * try to recreate the physical block number associated with
3207 * this buffer...
3208 */
3209 if (VNOP_BLOCKMAP(vp, f_offset, bp->b_bcount, &bp->b_blkno, &contig_bytes, NULL, bmap_flags, NULL))
3210 panic("getblk: VNOP_BLOCKMAP failed");
3211 /*
3212 * if the extent represented by this buffer
3213 * is not completely physically contiguous on
3214 * disk, than we can't cache the physical mapping
3215 * in the buffer header
3216 */
3217 if ((long)contig_bytes < bp->b_bcount)
3218 bp->b_blkno = bp->b_lblkno;
1c79356b 3219 } else {
b0d623f7 3220 OSAddAtomicLong(1, &bufstats.bufs_miss);
1c79356b 3221 }
b0d623f7 3222 kret = ubc_upl_map(upl, (vm_offset_t *)&(bp->b_datap));
1c79356b 3223
91447636
A
3224 if (kret != KERN_SUCCESS)
3225 panic("getblk: ubc_upl_map() failed with (%d)", kret);
1c79356b 3226 break;
91447636 3227 }
1c79356b 3228 default:
91447636 3229 panic("getblk: paging or unknown operation - %x", operation);
1c79356b
A
3230 /*NOTREACHED*/
3231 break;
3232 }
3233 }
1c79356b 3234 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 386)) | DBG_FUNC_END,
b0d623f7 3235 bp, bp->b_datap, bp->b_flags, 3, 0);
91447636
A
3236
3237#ifdef JOE_DEBUG
b0d623f7 3238 (void) OSBacktrace(&bp->b_stackgetblk[0], 6);
91447636 3239#endif
1c79356b
A
3240 return (bp);
3241}
3242
3243/*
3244 * Get an empty, disassociated buffer of given size.
3245 */
91447636 3246buf_t
2d21ac55 3247buf_geteblk(int size)
1c79356b 3248{
b0d623f7 3249 buf_t bp = NULL;
91447636
A
3250 int queue = BQ_EMPTY;
3251
b0d623f7
A
3252 do {
3253 lck_mtx_lock_spin(buf_mtxp);
3254
3255 bp = getnewbuf(0, 0, &queue);
3256 } while (bp == NULL);
1c79356b 3257
1c79356b 3258 SET(bp->b_flags, (B_META|B_INVAL));
1c79356b
A
3259
3260#if DIAGNOSTIC
3261 assert(queue == BQ_EMPTY);
3262#endif /* DIAGNOSTIC */
3263 /* XXX need to implement logic to deal with other queues */
3264
1c79356b 3265 binshash(bp, &invalhash);
1c79356b
A
3266 bufstats.bufs_eblk++;
3267
91447636
A
3268 lck_mtx_unlock(buf_mtxp);
3269
3270 allocbuf(bp, size);
3271
1c79356b
A
3272 return (bp);
3273}
3274
6d2010ae
A
3275uint32_t
3276buf_redundancy_flags(buf_t bp)
3277{
3278 return bp->b_redundancy_flags;
3279}
3280
3281void
3282buf_set_redundancy_flags(buf_t bp, uint32_t flags)
3283{
3284 SET(bp->b_redundancy_flags, flags);
3285}
3286
3287void
3288buf_clear_redundancy_flags(buf_t bp, uint32_t flags)
3289{
3290 CLR(bp->b_redundancy_flags, flags);
3291}
1c79356b 3292
fe8ab488
A
3293
3294
3295static void *
3296recycle_buf_from_pool(int nsize)
3297{
3298 buf_t bp;
3299 void *ptr = NULL;
3300
3301 lck_mtx_lock_spin(buf_mtxp);
3302
3303 TAILQ_FOREACH(bp, &bufqueues[BQ_META], b_freelist) {
3304 if (ISSET(bp->b_flags, B_DELWRI) || bp->b_bufsize != nsize)
3305 continue;
3306 ptr = (void *)bp->b_datap;
3307 bp->b_bufsize = 0;
3308
3309 bcleanbuf(bp, TRUE);
3310 break;
3311 }
3312 lck_mtx_unlock(buf_mtxp);
3313
3314 return (ptr);
3315}
3316
3317
3318
3319int zalloc_nopagewait_failed = 0;
3320int recycle_buf_failed = 0;
3321
3322static void *
3323grab_memory_for_meta_buf(int nsize)
3324{
3325 zone_t z;
3326 void *ptr;
3327 boolean_t was_vmpriv;
3328
3329 z = getbufzone(nsize);
3330
3331 /*
3332 * make sure we're NOT priviliged so that
3333 * if a vm_page_grab is needed, it won't
3334 * block if we're out of free pages... if
3335 * it blocks, then we can't honor the
3336 * nopagewait request
3337 */
3338 was_vmpriv = set_vm_privilege(FALSE);
3339
3340 ptr = zalloc_nopagewait(z);
3341
3342 if (was_vmpriv == TRUE)
3343 set_vm_privilege(TRUE);
3344
3345 if (ptr == NULL) {
3346
3347 zalloc_nopagewait_failed++;
3348
3349 ptr = recycle_buf_from_pool(nsize);
3350
3351 if (ptr == NULL) {
3352
3353 recycle_buf_failed++;
3354
3355 if (was_vmpriv == FALSE)
3356 set_vm_privilege(TRUE);
3357
3358 ptr = zalloc(z);
3359
3360 if (was_vmpriv == FALSE)
3361 set_vm_privilege(FALSE);
3362 }
3363 }
3364 return (ptr);
3365}
3366
1c79356b
A
3367/*
3368 * With UBC, there is no need to expand / shrink the file data
3369 * buffer. The VM uses the same pages, hence no waste.
3370 * All the file data buffers can have one size.
3371 * In fact expand / shrink would be an expensive operation.
3372 *
3373 * Only exception to this is meta-data buffers. Most of the
3374 * meta data operations are smaller than PAGE_SIZE. Having the
3375 * meta-data buffers grow and shrink as needed, optimizes use
3376 * of the kernel wired memory.
3377 */
3378
3379int
91447636 3380allocbuf(buf_t bp, int size)
1c79356b
A
3381{
3382 vm_size_t desired_size;
3383
3384 desired_size = roundup(size, CLBYTES);
3385
91447636 3386 if (desired_size < PAGE_SIZE)
1c79356b
A
3387 desired_size = PAGE_SIZE;
3388 if (desired_size > MAXBSIZE)
3389 panic("allocbuf: buffer larger than MAXBSIZE requested");
3390
1c79356b 3391 if (ISSET(bp->b_flags, B_META)) {
91447636
A
3392 int nsize = roundup(size, MINMETA);
3393
3394 if (bp->b_datap) {
3395 vm_offset_t elem = (vm_offset_t)bp->b_datap;
3396
3397 if (ISSET(bp->b_flags, B_ZALLOC)) {
3398 if (bp->b_bufsize < nsize) {
fe8ab488
A
3399 zone_t zprev;
3400
91447636
A
3401 /* reallocate to a bigger size */
3402
3403 zprev = getbufzone(bp->b_bufsize);
3404 if (nsize <= MAXMETA) {
3405 desired_size = nsize;
fe8ab488 3406
2d21ac55 3407 /* b_datap not really a ptr */
fe8ab488 3408 *(void **)(&bp->b_datap) = grab_memory_for_meta_buf(nsize);
1c79356b 3409 } else {
91447636 3410 bp->b_datap = (uintptr_t)NULL;
3e170ce0 3411 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size, VM_KERN_MEMORY_FILE);
91447636 3412 CLR(bp->b_flags, B_ZALLOC);
1c79356b 3413 }
91447636
A
3414 bcopy((void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
3415 zfree(zprev, (void *)elem);
3416 } else {
3417 desired_size = bp->b_bufsize;
3418 }
3419
3420 } else {
3421 if ((vm_size_t)bp->b_bufsize < desired_size) {
1c79356b 3422 /* reallocate to a bigger size */
91447636 3423 bp->b_datap = (uintptr_t)NULL;
3e170ce0 3424 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size, VM_KERN_MEMORY_FILE);
91447636 3425 bcopy((const void *)elem, (caddr_t)bp->b_datap, bp->b_bufsize);
1c79356b
A
3426 kmem_free(kernel_map, elem, bp->b_bufsize);
3427 } else {
3428 desired_size = bp->b_bufsize;
3429 }
91447636 3430 }
1c79356b
A
3431 } else {
3432 /* new allocation */
3433 if (nsize <= MAXMETA) {
3434 desired_size = nsize;
fe8ab488 3435
2d21ac55 3436 /* b_datap not really a ptr */
fe8ab488 3437 *(void **)(&bp->b_datap) = grab_memory_for_meta_buf(nsize);
1c79356b 3438 SET(bp->b_flags, B_ZALLOC);
91447636 3439 } else
3e170ce0 3440 kmem_alloc_kobject(kernel_map, (vm_offset_t *)&bp->b_datap, desired_size, VM_KERN_MEMORY_FILE);
1c79356b 3441 }
2d21ac55
A
3442
3443 if (bp->b_datap == 0)
3444 panic("allocbuf: NULL b_datap");
1c79356b 3445 }
9bccf70c
A
3446 bp->b_bufsize = desired_size;
3447 bp->b_bcount = size;
91447636 3448
9bccf70c 3449 return (0);
1c79356b
A
3450}
3451
3452/*
3453 * Get a new buffer from one of the free lists.
3454 *
3455 * Request for a queue is passes in. The queue from which the buffer was taken
3456 * from is returned. Out of range queue requests get BQ_EMPTY. Request for
3457 * BQUEUE means no preference. Use heuristics in that case.
3458 * Heuristics is as follows:
3459 * Try BQ_AGE, BQ_LRU, BQ_EMPTY, BQ_META in that order.
3460 * If none available block till one is made available.
3461 * If buffers available on both BQ_AGE and BQ_LRU, check the timestamps.
3462 * Pick the most stale buffer.
3463 * If found buffer was marked delayed write, start the async. write
3464 * and restart the search.
3465 * Initialize the fields and disassociate the buffer from the vnode.
3466 * Remove the buffer from the hash. Return the buffer and the queue
3467 * on which it was found.
91447636
A
3468 *
3469 * buf_mtxp is held upon entry
b0d623f7
A
3470 * returns with buf_mtxp locked if new buf available
3471 * returns with buf_mtxp UNlocked if new buf NOT available
1c79356b
A
3472 */
3473
91447636
A
3474static buf_t
3475getnewbuf(int slpflag, int slptimeo, int * queue)
1c79356b 3476{
91447636
A
3477 buf_t bp;
3478 buf_t lru_bp;
3479 buf_t age_bp;
3480 buf_t meta_bp;
3481 int age_time, lru_time, bp_time, meta_time;
3482 int req = *queue; /* save it for restarts */
3483 struct timespec ts;
1c79356b
A
3484
3485start:
91447636
A
3486 /*
3487 * invalid request gets empty queue
3488 */
2d21ac55 3489 if ((*queue >= BQUEUES) || (*queue < 0)
765c9de3 3490 || (*queue == BQ_LAUNDRY) || (*queue == BQ_LOCKED))
1c79356b 3491 *queue = BQ_EMPTY;
2d21ac55
A
3492
3493
3494 if (*queue == BQ_EMPTY && (bp = bufqueues[*queue].tqh_first))
3495 goto found;
3496
3497 /*
3498 * need to grow number of bufs, add another one rather than recycling
3499 */
3500 if (nbuf_headers < max_nbuf_headers) {
0c530ab8
A
3501 /*
3502 * Increment count now as lock
3503 * is dropped for allocation.
3504 * That avoids over commits
3505 */
2d21ac55 3506 nbuf_headers++;
0c530ab8
A
3507 goto add_newbufs;
3508 }
2d21ac55
A
3509 /* Try for the requested queue first */
3510 bp = bufqueues[*queue].tqh_first;
3511 if (bp)
3512 goto found;
1c79356b
A
3513
3514 /* Unable to use requested queue */
3515 age_bp = bufqueues[BQ_AGE].tqh_first;
3516 lru_bp = bufqueues[BQ_LRU].tqh_first;
3517 meta_bp = bufqueues[BQ_META].tqh_first;
3518
9bccf70c
A
3519 if (!age_bp && !lru_bp && !meta_bp) {
3520 /*
3521 * Unavailble on AGE or LRU or META queues
3522 * Try the empty list first
3523 */
1c79356b
A
3524 bp = bufqueues[BQ_EMPTY].tqh_first;
3525 if (bp) {
3526 *queue = BQ_EMPTY;
3527 goto found;
3528 }
0c530ab8
A
3529 /*
3530 * We have seen is this is hard to trigger.
3531 * This is an overcommit of nbufs but needed
3532 * in some scenarios with diskiamges
3533 */
3534
3535add_newbufs:
91447636 3536 lck_mtx_unlock(buf_mtxp);
765c9de3 3537
91447636 3538 /* Create a new temporary buffer header */
765c9de3 3539 bp = (struct buf *)zalloc(buf_hdr_zone);
2d21ac55 3540
765c9de3
A
3541 if (bp) {
3542 bufhdrinit(bp);
2d21ac55
A
3543 bp->b_whichq = BQ_EMPTY;
3544 bp->b_timestamp = buf_timestamp();
765c9de3 3545 BLISTNONE(bp);
765c9de3
A
3546 SET(bp->b_flags, B_HDRALLOC);
3547 *queue = BQ_EMPTY;
2d21ac55 3548 }
b0d623f7 3549 lck_mtx_lock_spin(buf_mtxp);
2d21ac55
A
3550
3551 if (bp) {
3552 binshash(bp, &invalhash);
765c9de3
A
3553 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
3554 buf_hdr_count++;
3555 goto found;
3556 }
0c530ab8 3557 /* subtract already accounted bufcount */
2d21ac55 3558 nbuf_headers--;
0c530ab8 3559
91447636 3560 bufstats.bufs_sleeps++;
765c9de3 3561
1c79356b
A
3562 /* wait for a free buffer of any kind */
3563 needbuffer = 1;
91447636
A
3564 /* hz value is 100 */
3565 ts.tv_sec = (slptimeo/1000);
3566 /* the hz value is 100; which leads to 10ms */
3567 ts.tv_nsec = (slptimeo % 1000) * NSEC_PER_USEC * 1000 * 10;
b0d623f7
A
3568
3569 msleep(&needbuffer, buf_mtxp, slpflag | PDROP | (PRIBIO+1), "getnewbuf", &ts);
2d21ac55 3570 return (NULL);
1c79356b
A
3571 }
3572
3573 /* Buffer available either on AGE or LRU or META */
3574 bp = NULL;
3575 *queue = -1;
3576
3577 /* Buffer available either on AGE or LRU */
3578 if (!age_bp) {
3579 bp = lru_bp;
3580 *queue = BQ_LRU;
3581 } else if (!lru_bp) {
3582 bp = age_bp;
3583 *queue = BQ_AGE;
3584 } else { /* buffer available on both AGE and LRU */
91447636
A
3585 int t = buf_timestamp();
3586
3587 age_time = t - age_bp->b_timestamp;
3588 lru_time = t - lru_bp->b_timestamp;
1c79356b
A
3589 if ((age_time < 0) || (lru_time < 0)) { /* time set backwards */
3590 bp = age_bp;
3591 *queue = BQ_AGE;
3592 /*
3593 * we should probably re-timestamp eveything in the
3594 * queues at this point with the current time
3595 */
3596 } else {
3597 if ((lru_time >= lru_is_stale) && (age_time < age_is_stale)) {
3598 bp = lru_bp;
3599 *queue = BQ_LRU;
3600 } else {
3601 bp = age_bp;
3602 *queue = BQ_AGE;
3603 }
3604 }
3605 }
3606
3607 if (!bp) { /* Neither on AGE nor on LRU */
3608 bp = meta_bp;
3609 *queue = BQ_META;
3610 } else if (meta_bp) {
91447636
A
3611 int t = buf_timestamp();
3612
3613 bp_time = t - bp->b_timestamp;
3614 meta_time = t - meta_bp->b_timestamp;
1c79356b
A
3615
3616 if (!(bp_time < 0) && !(meta_time < 0)) {
3617 /* time not set backwards */
3618 int bp_is_stale;
3619 bp_is_stale = (*queue == BQ_LRU) ?
3620 lru_is_stale : age_is_stale;
3621
3622 if ((meta_time >= meta_is_stale) &&
3623 (bp_time < bp_is_stale)) {
3624 bp = meta_bp;
3625 *queue = BQ_META;
3626 }
3627 }
3628 }
1c79356b 3629found:
91447636 3630 if (ISSET(bp->b_flags, B_LOCKED) || ISSET(bp->b_lflags, BL_BUSY))
b0d623f7 3631 panic("getnewbuf: bp @ %p is LOCKED or BUSY! (flags 0x%x)\n", bp, bp->b_flags);
1c79356b
A
3632
3633 /* Clean it */
b0d623f7 3634 if (bcleanbuf(bp, FALSE)) {
91447636
A
3635 /*
3636 * moved to the laundry thread, buffer not ready
3637 */
1c79356b
A
3638 *queue = req;
3639 goto start;
3640 }
1c79356b
A
3641 return (bp);
3642}
9bccf70c 3643
1c79356b
A
3644
3645/*
3646 * Clean a buffer.
6d2010ae 3647 * Returns 0 if buffer is ready to use,
91447636 3648 * Returns 1 if issued a buf_bawrite() to indicate
1c79356b 3649 * that the buffer is not ready.
91447636
A
3650 *
3651 * buf_mtxp is held upon entry
3652 * returns with buf_mtxp locked
1c79356b 3653 */
6d2010ae 3654int
b0d623f7 3655bcleanbuf(buf_t bp, boolean_t discard)
1c79356b 3656{
1c79356b 3657 /* Remove from the queue */
91447636 3658 bremfree_locked(bp);
1c79356b 3659
91447636
A
3660#ifdef JOE_DEBUG
3661 bp->b_owner = current_thread();
3662 bp->b_tag = 2;
3663#endif
765c9de3
A
3664 /*
3665 * If buffer was a delayed write, start the IO by queuing
3666 * it on the LAUNDRY queue, and return 1
3667 */
1c79356b 3668 if (ISSET(bp->b_flags, B_DELWRI)) {
b0d623f7
A
3669 if (discard) {
3670 SET(bp->b_lflags, BL_WANTDEALLOC);
3671 }
3672
6d2010ae 3673 bmovelaundry(bp);
91447636
A
3674
3675 lck_mtx_unlock(buf_mtxp);
3676
2d21ac55
A
3677 wakeup(&bufqueues[BQ_LAUNDRY]);
3678 /*
3679 * and give it a chance to run
3680 */
9bccf70c 3681 (void)thread_block(THREAD_CONTINUE_NULL);
91447636 3682
b0d623f7 3683 lck_mtx_lock_spin(buf_mtxp);
2d21ac55 3684
1c79356b
A
3685 return (1);
3686 }
2d21ac55
A
3687#ifdef JOE_DEBUG
3688 bp->b_owner = current_thread();
3689 bp->b_tag = 8;
3690#endif
3691 /*
3692 * Buffer is no longer on any free list... we own it
3693 */
3694 SET(bp->b_lflags, BL_BUSY);
b0d623f7
A
3695 buf_busycount++;
3696
2d21ac55 3697 bremhash(bp);
91447636 3698
91447636
A
3699 /*
3700 * disassociate us from our vnode, if we had one...
3701 */
3702 if (bp->b_vp)
2d21ac55
A
3703 brelvp_locked(bp);
3704
3705 lck_mtx_unlock(buf_mtxp);
3706
3707 BLISTNONE(bp);
91447636 3708
6d2010ae
A
3709 if (ISSET(bp->b_flags, B_META))
3710 buf_free_meta_store(bp);
91447636
A
3711
3712 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
3713
6d2010ae 3714 buf_release_credentials(bp);
fe8ab488 3715
b0d623f7
A
3716 /* If discarding, just move to the empty queue */
3717 if (discard) {
3718 lck_mtx_lock_spin(buf_mtxp);
3719 CLR(bp->b_flags, (B_META | B_ZALLOC | B_DELWRI | B_LOCKED | B_AGE | B_ASYNC | B_NOCACHE | B_FUA));
3720 bp->b_whichq = BQ_EMPTY;
3721 binshash(bp, &invalhash);
3722 binsheadfree(bp, &bufqueues[BQ_EMPTY], BQ_EMPTY);
3723 CLR(bp->b_lflags, BL_BUSY);
3724 buf_busycount--;
3725 } else {
3726 /* Not discarding: clean up and prepare for reuse */
3727 bp->b_bufsize = 0;
3728 bp->b_datap = (uintptr_t)NULL;
3729 bp->b_upl = (void *)NULL;
3e170ce0 3730 bp->b_fsprivate = (void *)NULL;
b0d623f7
A
3731 /*
3732 * preserve the state of whether this buffer
3733 * was allocated on the fly or not...
3734 * the only other flag that should be set at
3735 * this point is BL_BUSY...
3736 */
3737#ifdef JOE_DEBUG
3738 bp->b_owner = current_thread();
3739 bp->b_tag = 3;
3740#endif
3741 bp->b_lflags = BL_BUSY;
3742 bp->b_flags = (bp->b_flags & B_HDRALLOC);
3e170ce0 3743 bp->b_redundancy_flags = 0;
b0d623f7
A
3744 bp->b_dev = NODEV;
3745 bp->b_blkno = bp->b_lblkno = 0;
3746 bp->b_iodone = NULL;
3747 bp->b_error = 0;
3748 bp->b_resid = 0;
3749 bp->b_bcount = 0;
3750 bp->b_dirtyoff = bp->b_dirtyend = 0;
3751 bp->b_validoff = bp->b_validend = 0;
7ddcb079 3752 bzero(&bp->b_attr, sizeof(struct bufattr));
b0d623f7
A
3753
3754 lck_mtx_lock_spin(buf_mtxp);
3755 }
91447636
A
3756 return (0);
3757}
3758
3759
3760
3761errno_t
3762buf_invalblkno(vnode_t vp, daddr64_t lblkno, int flags)
3763{
3764 buf_t bp;
3765 errno_t error;
2d21ac55
A
3766 struct bufhashhdr *dp;
3767
3768 dp = BUFHASH(vp, lblkno);
91447636 3769
91447636 3770relook:
b0d623f7
A
3771 lck_mtx_lock_spin(buf_mtxp);
3772
2d21ac55 3773 if ((bp = incore_locked(vp, lblkno, dp)) == (struct buf *)0) {
91447636
A
3774 lck_mtx_unlock(buf_mtxp);
3775 return (0);
3776 }
3777 if (ISSET(bp->b_lflags, BL_BUSY)) {
3778 if ( !ISSET(flags, BUF_WAIT)) {
3779 lck_mtx_unlock(buf_mtxp);
3780 return (EBUSY);
3781 }
3782 SET(bp->b_lflags, BL_WANTED);
3783
b0d623f7 3784 error = msleep((caddr_t)bp, buf_mtxp, PDROP | (PRIBIO + 1), "buf_invalblkno", NULL);
91447636 3785
2d21ac55 3786 if (error) {
91447636 3787 return (error);
2d21ac55 3788 }
91447636
A
3789 goto relook;
3790 }
3791 bremfree_locked(bp);
3792 SET(bp->b_lflags, BL_BUSY);
3793 SET(bp->b_flags, B_INVAL);
b0d623f7 3794 buf_busycount++;
91447636
A
3795#ifdef JOE_DEBUG
3796 bp->b_owner = current_thread();
3797 bp->b_tag = 4;
3798#endif
3799 lck_mtx_unlock(buf_mtxp);
3800 buf_brelse(bp);
3801
3802 return (0);
3803}
3804
3805
3806void
3807buf_drop(buf_t bp)
3808{
3809 int need_wakeup = 0;
3810
2d21ac55 3811 lck_mtx_lock_spin(buf_mtxp);
91447636
A
3812
3813 if (ISSET(bp->b_lflags, BL_WANTED)) {
3814 /*
3815 * delay the actual wakeup until after we
3816 * clear BL_BUSY and we've dropped buf_mtxp
3817 */
3818 need_wakeup = 1;
3819 }
2d21ac55
A
3820#ifdef JOE_DEBUG
3821 bp->b_owner = current_thread();
3822 bp->b_tag = 9;
3823#endif
91447636
A
3824 /*
3825 * Unlock the buffer.
3826 */
3827 CLR(bp->b_lflags, (BL_BUSY | BL_WANTED));
b0d623f7 3828 buf_busycount--;
1c79356b 3829
91447636 3830 lck_mtx_unlock(buf_mtxp);
1c79356b 3831
91447636
A
3832 if (need_wakeup) {
3833 /*
3834 * Wake up any proceeses waiting for _this_ buffer to become free.
3835 */
3836 wakeup(bp);
3837 }
3838}
1c79356b 3839
1c79356b 3840
91447636
A
3841errno_t
3842buf_acquire(buf_t bp, int flags, int slpflag, int slptimeo) {
3843 errno_t error;
1c79356b 3844
b0d623f7 3845 lck_mtx_lock_spin(buf_mtxp);
1c79356b 3846
91447636 3847 error = buf_acquire_locked(bp, flags, slpflag, slptimeo);
1c79356b 3848
91447636 3849 lck_mtx_unlock(buf_mtxp);
1c79356b 3850
91447636
A
3851 return (error);
3852}
1c79356b 3853
91447636
A
3854
3855static errno_t
3856buf_acquire_locked(buf_t bp, int flags, int slpflag, int slptimeo)
3857{
3858 errno_t error;
3859 struct timespec ts;
3860
3861 if (ISSET(bp->b_flags, B_LOCKED)) {
3862 if ((flags & BAC_SKIP_LOCKED))
3863 return (EDEADLK);
3864 } else {
3865 if ((flags & BAC_SKIP_NONLOCKED))
3866 return (EDEADLK);
1c79356b 3867 }
91447636
A
3868 if (ISSET(bp->b_lflags, BL_BUSY)) {
3869 /*
b0d623f7 3870 * since the lck_mtx_lock may block, the buffer
91447636
A
3871 * may become BUSY, so we need to
3872 * recheck for a NOWAIT request
3873 */
3874 if (flags & BAC_NOWAIT)
3875 return (EBUSY);
3876 SET(bp->b_lflags, BL_WANTED);
3877
3878 /* the hz value is 100; which leads to 10ms */
3879 ts.tv_sec = (slptimeo/100);
3880 ts.tv_nsec = (slptimeo % 100) * 10 * NSEC_PER_USEC * 1000;
2d21ac55 3881 error = msleep((caddr_t)bp, buf_mtxp, slpflag | (PRIBIO + 1), "buf_acquire", &ts);
91447636
A
3882
3883 if (error)
3884 return (error);
3885 return (EAGAIN);
1c79356b 3886 }
91447636
A
3887 if (flags & BAC_REMOVE)
3888 bremfree_locked(bp);
3889 SET(bp->b_lflags, BL_BUSY);
b0d623f7
A
3890 buf_busycount++;
3891
91447636
A
3892#ifdef JOE_DEBUG
3893 bp->b_owner = current_thread();
3894 bp->b_tag = 5;
3895#endif
1c79356b
A
3896 return (0);
3897}
3898
3899
3900/*
3901 * Wait for operations on the buffer to complete.
3902 * When they do, extract and return the I/O's error value.
3903 */
91447636
A
3904errno_t
3905buf_biowait(buf_t bp)
1c79356b 3906{
b0d623f7 3907 while (!ISSET(bp->b_flags, B_DONE)) {
1c79356b 3908
b0d623f7 3909 lck_mtx_lock_spin(buf_mtxp);
91447636 3910
b0d623f7
A
3911 if (!ISSET(bp->b_flags, B_DONE)) {
3912 DTRACE_IO1(wait__start, buf_t, bp);
3913 (void) msleep(bp, buf_mtxp, PDROP | (PRIBIO+1), "buf_biowait", NULL);
3914 DTRACE_IO1(wait__done, buf_t, bp);
3915 } else
3916 lck_mtx_unlock(buf_mtxp);
3917 }
1c79356b
A
3918 /* check for interruption of I/O (e.g. via NFS), then errors. */
3919 if (ISSET(bp->b_flags, B_EINTR)) {
3920 CLR(bp->b_flags, B_EINTR);
3921 return (EINTR);
3922 } else if (ISSET(bp->b_flags, B_ERROR))
3923 return (bp->b_error ? bp->b_error : EIO);
3924 else
3925 return (0);
3926}
3927
2d21ac55 3928
1c79356b
A
3929/*
3930 * Mark I/O complete on a buffer.
3931 *
3932 * If a callback has been requested, e.g. the pageout
3933 * daemon, do so. Otherwise, awaken waiting processes.
3934 *
3935 * [ Leffler, et al., says on p.247:
3936 * "This routine wakes up the blocked process, frees the buffer
3937 * for an asynchronous write, or, for a request by the pagedaemon
3938 * process, invokes a procedure specified in the buffer structure" ]
3939 *
3940 * In real life, the pagedaemon (or other system processes) wants
91447636 3941 * to do async stuff to, and doesn't want the buffer buf_brelse()'d.
1c79356b
A
3942 * (for swap pager, that puts swap buffers on the free lists (!!!),
3943 * for the vn device, that puts malloc'd buffers on the free lists!)
3944 */
91447636 3945
1c79356b 3946void
91447636 3947buf_biodone(buf_t bp)
1c79356b 3948{
b0d623f7 3949 mount_t mp;
39236c6e 3950 struct bufattr *bap;
b0d623f7 3951
1c79356b 3952 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_START,
b0d623f7 3953 bp, bp->b_datap, bp->b_flags, 0, 0);
1c79356b
A
3954
3955 if (ISSET(bp->b_flags, B_DONE))
3956 panic("biodone already");
1c79356b 3957
39236c6e
A
3958 bap = &bp->b_attr;
3959
b0d623f7
A
3960 if (bp->b_vp && bp->b_vp->v_mount) {
3961 mp = bp->b_vp->v_mount;
3962 } else {
3963 mp = NULL;
3964 }
3965
d190cdc3
A
3966 if (ISSET(bp->b_flags, B_ERROR)) {
3967 if (mp && (MNT_ROOTFS & mp->mnt_flag)) {
3968 dk_error_description_t desc;
3969 bzero(&desc, sizeof(desc));
3970 desc.description = panic_disk_error_description;
3971 desc.description_size = panic_disk_error_description_size;
3972 VNOP_IOCTL(mp->mnt_devvp, DKIOCGETERRORDESCRIPTION, (caddr_t)&desc, 0, vfs_context_kernel());
3973 }
3974 }
3975
b0d623f7
A
3976 if (mp && (bp->b_flags & B_READ) == 0) {
3977 update_last_io_time(mp);
3978 INCR_PENDING_IO(-(pending_io_t)buf_count(bp), mp->mnt_pending_write_size);
3979 } else if (mp) {
3980 INCR_PENDING_IO(-(pending_io_t)buf_count(bp), mp->mnt_pending_read_size);
e2fac8b1
A
3981 }
3982
39037602
A
3983 throttle_info_end_io(bp);
3984
39236c6e
A
3985 if (kdebug_enable) {
3986 int code = DKIO_DONE;
3987 int io_tier = GET_BUFATTR_IO_TIER(bap);
9bccf70c 3988
91447636
A
3989 if (bp->b_flags & B_READ)
3990 code |= DKIO_READ;
3991 if (bp->b_flags & B_ASYNC)
3992 code |= DKIO_ASYNC;
9bccf70c 3993
91447636
A
3994 if (bp->b_flags & B_META)
3995 code |= DKIO_META;
3996 else if (bp->b_flags & B_PAGEIO)
3997 code |= DKIO_PAGING;
9bccf70c 3998
39236c6e 3999 if (io_tier != 0)
6d2010ae 4000 code |= DKIO_THROTTLE;
39236c6e
A
4001
4002 code |= ((io_tier << DKIO_TIER_SHIFT) & DKIO_TIER_MASK);
4003
4004 if (bp->b_flags & B_PASSIVE)
6d2010ae
A
4005 code |= DKIO_PASSIVE;
4006
39236c6e 4007 if (bap->ba_flags & BA_NOCACHE)
316670eb
A
4008 code |= DKIO_NOCACHE;
4009
d190cdc3
A
4010 if (bap->ba_flags & BA_IO_TIER_UPGRADE) {
4011 code |= DKIO_TIER_UPGRADE;
4012 }
4013
316670eb 4014 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_COMMON, FSDBG_CODE(DBG_DKRW, code) | DBG_FUNC_NONE,
39236c6e 4015 buf_kernel_addrperm_addr(bp), (uintptr_t)VM_KERNEL_ADDRPERM(bp->b_vp), bp->b_resid, bp->b_error, 0);
9bccf70c 4016 }
6d2010ae 4017
91447636
A
4018 /*
4019 * I/O was done, so don't believe
6d2010ae
A
4020 * the DIRTY state from VM anymore...
4021 * and we need to reset the THROTTLED/PASSIVE
4022 * indicators
91447636 4023 */
39236c6e 4024 CLR(bp->b_flags, (B_WASDIRTY | B_PASSIVE));
d190cdc3 4025 CLR(bap->ba_flags, (BA_META | BA_NOCACHE | BA_DELAYIDLESLEEP | BA_IO_TIER_UPGRADE));
39236c6e
A
4026
4027 SET_BUFATTR_IO_TIER(bap, 0);
4028
2d21ac55 4029 DTRACE_IO1(done, buf_t, bp);
b4c24cb9 4030
91447636
A
4031 if (!ISSET(bp->b_flags, B_READ) && !ISSET(bp->b_flags, B_RAW))
4032 /*
4033 * wake up any writer's blocked
4034 * on throttle or waiting for I/O
4035 * to drain
4036 */
4037 vnode_writedone(bp->b_vp);
4038
4039 if (ISSET(bp->b_flags, (B_CALL | B_FILTER))) { /* if necessary, call out */
4040 void (*iodone_func)(struct buf *, void *) = bp->b_iodone;
6d2010ae 4041 void *arg = bp->b_transaction;
91447636
A
4042 int callout = ISSET(bp->b_flags, B_CALL);
4043
6d2010ae
A
4044 if (iodone_func == NULL)
4045 panic("biodone: bp @ %p has NULL b_iodone!\n", bp);
4046
91447636 4047 CLR(bp->b_flags, (B_CALL | B_FILTER)); /* filters and callouts are one-shot */
b4c24cb9 4048 bp->b_iodone = NULL;
91447636 4049 bp->b_transaction = NULL;
b4c24cb9 4050
6d2010ae
A
4051 if (callout)
4052 SET(bp->b_flags, B_DONE); /* note that it's done */
2d21ac55 4053
6d2010ae
A
4054 (*iodone_func)(bp, arg);
4055
4056 if (callout) {
4057 /*
2d21ac55 4058 * assumes that the callback function takes
91447636
A
4059 * ownership of the bp and deals with releasing it if necessary
4060 */
2d21ac55
A
4061 goto biodone_done;
4062 }
91447636
A
4063 /*
4064 * in this case the call back function is acting
4065 * strictly as a filter... it does not take
4066 * ownership of the bp and is expecting us
4067 * to finish cleaning up... this is currently used
4068 * by the HFS journaling code
4069 */
1c79356b 4070 }
91447636
A
4071 if (ISSET(bp->b_flags, B_ASYNC)) { /* if async, release it */
4072 SET(bp->b_flags, B_DONE); /* note that it's done */
1c79356b 4073
91447636
A
4074 buf_brelse(bp);
4075 } else { /* or just wakeup the buffer */
4076 /*
4077 * by taking the mutex, we serialize
4078 * the buf owner calling buf_biowait so that we'll
4079 * only see him in one of 2 states...
4080 * state 1: B_DONE wasn't set and he's
4081 * blocked in msleep
4082 * state 2: he's blocked trying to take the
4083 * mutex before looking at B_DONE
4084 * BL_WANTED is cleared in case anyone else
4085 * is blocked waiting for the buffer... note
4086 * that we haven't cleared B_BUSY yet, so if
4087 * they do get to run, their going to re-set
4088 * BL_WANTED and go back to sleep
4089 */
2d21ac55 4090 lck_mtx_lock_spin(buf_mtxp);
1c79356b 4091
91447636
A
4092 CLR(bp->b_lflags, BL_WANTED);
4093 SET(bp->b_flags, B_DONE); /* note that it's done */
4094
4095 lck_mtx_unlock(buf_mtxp);
4096
4097 wakeup(bp);
4098 }
4099biodone_done:
4100 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 387)) | DBG_FUNC_END,
b0d623f7 4101 (uintptr_t)bp, (uintptr_t)bp->b_datap, bp->b_flags, 0, 0);
1c79356b
A
4102}
4103
39236c6e
A
4104/*
4105 * Obfuscate buf pointers.
4106 */
4107vm_offset_t
4108buf_kernel_addrperm_addr(void * addr)
4109{
4110 if ((vm_offset_t)addr == 0)
4111 return 0;
4112 else
4113 return ((vm_offset_t)addr + buf_kernel_addrperm);
4114}
4115
1c79356b
A
4116/*
4117 * Return a count of buffers on the "locked" queue.
4118 */
4119int
91447636 4120count_lock_queue(void)
1c79356b 4121{
91447636
A
4122 buf_t bp;
4123 int n = 0;
4124
b0d623f7 4125 lck_mtx_lock_spin(buf_mtxp);
1c79356b
A
4126
4127 for (bp = bufqueues[BQ_LOCKED].tqh_first; bp;
4128 bp = bp->b_freelist.tqe_next)
4129 n++;
91447636
A
4130 lck_mtx_unlock(buf_mtxp);
4131
1c79356b
A
4132 return (n);
4133}
4134
4135/*
4136 * Return a count of 'busy' buffers. Used at the time of shutdown.
316670eb 4137 * note: This is also called from the mach side in debug context in kdp.c
1c79356b
A
4138 */
4139int
91447636 4140count_busy_buffers(void)
1c79356b 4141{
b0d623f7 4142 return buf_busycount + bufstats.bufs_iobufinuse;
1c79356b
A
4143}
4144
9bccf70c 4145#if DIAGNOSTIC
1c79356b
A
4146/*
4147 * Print out statistics on the current allocation of the buffer pool.
4148 * Can be enabled to print out on every ``sync'' by setting "syncprt"
4149 * in vfs_syscalls.c using sysctl.
4150 */
4151void
4152vfs_bufstats()
4153{
91447636 4154 int i, j, count;
6d2010ae
A
4155 struct buf *bp;
4156 struct bqueues *dp;
91447636
A
4157 int counts[MAXBSIZE/CLBYTES+1];
4158 static char *bname[BQUEUES] =
4159 { "LOCKED", "LRU", "AGE", "EMPTY", "META", "LAUNDRY" };
4160
4161 for (dp = bufqueues, i = 0; dp < &bufqueues[BQUEUES]; dp++, i++) {
4162 count = 0;
4163 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
4164 counts[j] = 0;
4165
4166 lck_mtx_lock(buf_mtxp);
4167
4168 for (bp = dp->tqh_first; bp; bp = bp->b_freelist.tqe_next) {
4169 counts[bp->b_bufsize/CLBYTES]++;
4170 count++;
4171 }
4172 lck_mtx_unlock(buf_mtxp);
4173
4174 printf("%s: total-%d", bname[i], count);
4175 for (j = 0; j <= MAXBSIZE/CLBYTES; j++)
4176 if (counts[j] != 0)
4177 printf(", %d-%d", j * CLBYTES, counts[j]);
4178 printf("\n");
4179 }
4180}
4181#endif /* DIAGNOSTIC */
4182
6d2010ae 4183#define NRESERVEDIOBUFS 128
91447636 4184
39037602
A
4185#define MNT_VIRTUALDEV_MAX_IOBUFS 16
4186#define VIRTUALDEV_MAX_IOBUFS ((40*niobuf_headers)/100)
91447636
A
4187
4188buf_t
4189alloc_io_buf(vnode_t vp, int priv)
4190{
4191 buf_t bp;
39037602
A
4192 mount_t mp = NULL;
4193 int alloc_for_virtualdev = FALSE;
91447636 4194
b0d623f7 4195 lck_mtx_lock_spin(iobuffer_mtxp);
91447636 4196
39037602
A
4197 /*
4198 * We subject iobuf requests for diskimages to additional restrictions.
4199 *
4200 * a) A single diskimage mount cannot use up more than
4201 * MNT_VIRTUALDEV_MAX_IOBUFS. However,vm privileged (pageout) requests
4202 * are not subject to this restriction.
4203 * b) iobuf headers used by all diskimage headers by all mount
4204 * points cannot exceed VIRTUALDEV_MAX_IOBUFS.
4205 */
4206 if (vp && ((mp = vp->v_mount)) && mp != dead_mountp &&
4207 mp->mnt_kern_flag & MNTK_VIRTUALDEV) {
4208 alloc_for_virtualdev = TRUE;
4209 while ((!priv && mp->mnt_iobufinuse > MNT_VIRTUALDEV_MAX_IOBUFS) ||
4210 bufstats.bufs_iobufinuse_vdev > VIRTUALDEV_MAX_IOBUFS) {
4211 bufstats.bufs_iobufsleeps++;
4212
4213 need_iobuffer = 1;
4214 (void)msleep(&need_iobuffer, iobuffer_mtxp,
4215 PSPIN | (PRIBIO+1), (const char *)"alloc_io_buf (1)",
4216 NULL);
4217 }
4218 }
4219
2d21ac55 4220 while (((niobuf_headers - NRESERVEDIOBUFS < bufstats.bufs_iobufinuse) && !priv) ||
91447636
A
4221 (bp = iobufqueue.tqh_first) == NULL) {
4222 bufstats.bufs_iobufsleeps++;
4223
4224 need_iobuffer = 1;
39037602
A
4225 (void)msleep(&need_iobuffer, iobuffer_mtxp, PSPIN | (PRIBIO+1),
4226 (const char *)"alloc_io_buf (2)", NULL);
91447636
A
4227 }
4228 TAILQ_REMOVE(&iobufqueue, bp, b_freelist);
4229
4230 bufstats.bufs_iobufinuse++;
4231 if (bufstats.bufs_iobufinuse > bufstats.bufs_iobufmax)
4232 bufstats.bufs_iobufmax = bufstats.bufs_iobufinuse;
4233
39037602
A
4234 if (alloc_for_virtualdev) {
4235 mp->mnt_iobufinuse++;
4236 bufstats.bufs_iobufinuse_vdev++;
4237 }
4238
91447636
A
4239 lck_mtx_unlock(iobuffer_mtxp);
4240
4241 /*
4242 * initialize various fields
4243 * we don't need to hold the mutex since the buffer
4244 * is now private... the vp should have a reference
4245 * on it and is not protected by this mutex in any event
4246 */
4247 bp->b_timestamp = 0;
4248 bp->b_proc = NULL;
4249
4250 bp->b_datap = 0;
4251 bp->b_flags = 0;
4252 bp->b_lflags = BL_BUSY | BL_IOBUF;
39037602
A
4253 if (alloc_for_virtualdev)
4254 bp->b_lflags |= BL_IOBUF_VDEV;
6d2010ae 4255 bp->b_redundancy_flags = 0;
91447636
A
4256 bp->b_blkno = bp->b_lblkno = 0;
4257#ifdef JOE_DEBUG
4258 bp->b_owner = current_thread();
4259 bp->b_tag = 6;
4260#endif
4261 bp->b_iodone = NULL;
4262 bp->b_error = 0;
4263 bp->b_resid = 0;
4264 bp->b_bcount = 0;
4265 bp->b_bufsize = 0;
4266 bp->b_upl = NULL;
3e170ce0 4267 bp->b_fsprivate = (void *)NULL;
91447636 4268 bp->b_vp = vp;
7ddcb079 4269 bzero(&bp->b_attr, sizeof(struct bufattr));
91447636
A
4270
4271 if (vp && (vp->v_type == VBLK || vp->v_type == VCHR))
4272 bp->b_dev = vp->v_rdev;
4273 else
4274 bp->b_dev = NODEV;
4275
4276 return (bp);
4277}
4278
4279
4280void
4281free_io_buf(buf_t bp)
4282{
39037602
A
4283 int need_wakeup = 0;
4284 int free_for_virtualdev = FALSE;
4285 mount_t mp = NULL;
4286
4287 /* Was this iobuf for a diskimage ? */
4288 if (bp->b_lflags & BL_IOBUF_VDEV) {
4289 free_for_virtualdev = TRUE;
4290 if (bp->b_vp)
4291 mp = bp->b_vp->v_mount;
4292 }
91447636
A
4293
4294 /*
4295 * put buffer back on the head of the iobufqueue
4296 */
4297 bp->b_vp = NULL;
4298 bp->b_flags = B_INVAL;
4299
fe8ab488
A
4300 /* Zero out the bufattr and its flags before relinquishing this iobuf */
4301 bzero (&bp->b_attr, sizeof(struct bufattr));
4302
2d21ac55 4303 lck_mtx_lock_spin(iobuffer_mtxp);
91447636
A
4304
4305 binsheadfree(bp, &iobufqueue, -1);
4306
4307 if (need_iobuffer) {
4308 /*
4309 * Wake up any processes waiting because they need an io buffer
4310 *
4311 * do the wakeup after we drop the mutex... it's possible that the
4312 * wakeup will be superfluous if need_iobuffer gets set again and
4313 * another thread runs this path, but it's highly unlikely, doesn't
4314 * hurt, and it means we don't hold up I/O progress if the wakeup blocks
4315 * trying to grab a task related lock...
4316 */
4317 need_iobuffer = 0;
4318 need_wakeup = 1;
4319 }
b0d623f7
A
4320 if (bufstats.bufs_iobufinuse <= 0)
4321 panic("free_io_buf: bp(%p) - bufstats.bufs_iobufinuse < 0", bp);
4322
91447636
A
4323 bufstats.bufs_iobufinuse--;
4324
39037602
A
4325 if (free_for_virtualdev) {
4326 bufstats.bufs_iobufinuse_vdev--;
4327 if (mp && mp != dead_mountp)
4328 mp->mnt_iobufinuse--;
4329 }
4330
91447636
A
4331 lck_mtx_unlock(iobuffer_mtxp);
4332
4333 if (need_wakeup)
4334 wakeup(&need_iobuffer);
4335}
4336
4337
2d21ac55
A
4338void
4339buf_list_lock(void)
4340{
b0d623f7 4341 lck_mtx_lock_spin(buf_mtxp);
2d21ac55
A
4342}
4343
4344void
4345buf_list_unlock(void)
4346{
4347 lck_mtx_unlock(buf_mtxp);
4348}
91447636
A
4349
4350/*
4351 * If getnewbuf() calls bcleanbuf() on the same thread
4352 * there is a potential for stack overrun and deadlocks.
4353 * So we always handoff the work to a worker thread for completion
4354 */
91447636
A
4355
4356
4357static void
4358bcleanbuf_thread_init(void)
4359{
b0d623f7
A
4360 thread_t thread = THREAD_NULL;
4361
91447636 4362 /* create worker thread */
b0d623f7
A
4363 kernel_thread_start((thread_continue_t)bcleanbuf_thread, NULL, &thread);
4364 thread_deallocate(thread);
91447636
A
4365}
4366
6d2010ae
A
4367typedef int (*bcleanbufcontinuation)(int);
4368
39037602 4369__attribute__((noreturn))
91447636
A
4370static void
4371bcleanbuf_thread(void)
4372{
4373 struct buf *bp;
4374 int error = 0;
4375 int loopcnt = 0;
4376
4377 for (;;) {
b0d623f7 4378 lck_mtx_lock_spin(buf_mtxp);
91447636 4379
b0d623f7 4380 while ( (bp = TAILQ_FIRST(&bufqueues[BQ_LAUNDRY])) == NULL) {
6d2010ae 4381 (void)msleep0(&bufqueues[BQ_LAUNDRY], buf_mtxp, PRIBIO|PDROP, "blaundry", 0, (bcleanbufcontinuation)bcleanbuf_thread);
b0d623f7 4382 }
6d2010ae 4383
91447636
A
4384 /*
4385 * Remove from the queue
4386 */
4387 bremfree_locked(bp);
2d21ac55
A
4388
4389 /*
4390 * Buffer is no longer on any free list
4391 */
4392 SET(bp->b_lflags, BL_BUSY);
b0d623f7 4393 buf_busycount++;
2d21ac55
A
4394
4395#ifdef JOE_DEBUG
4396 bp->b_owner = current_thread();
4397 bp->b_tag = 10;
4398#endif
91447636
A
4399
4400 lck_mtx_unlock(buf_mtxp);
4401 /*
4402 * do the IO
4403 */
4404 error = bawrite_internal(bp, 0);
4405
4406 if (error) {
2d21ac55
A
4407 bp->b_whichq = BQ_LAUNDRY;
4408 bp->b_timestamp = buf_timestamp();
4409
4410 lck_mtx_lock_spin(buf_mtxp);
91447636
A
4411
4412 binstailfree(bp, &bufqueues[BQ_LAUNDRY], BQ_LAUNDRY);
4413 blaundrycnt++;
4414
6d2010ae 4415 /* we never leave a busy page on the laundry queue */
2d21ac55 4416 CLR(bp->b_lflags, BL_BUSY);
b0d623f7 4417 buf_busycount--;
2d21ac55
A
4418#ifdef JOE_DEBUG
4419 bp->b_owner = current_thread();
4420 bp->b_tag = 11;
4421#endif
4422
91447636 4423 lck_mtx_unlock(buf_mtxp);
6d2010ae
A
4424
4425 if (loopcnt > MAXLAUNDRY) {
4426 /*
4427 * bawrite_internal() can return errors if we're throttled. If we've
4428 * done several I/Os and failed, give the system some time to unthrottle
4429 * the vnode
4430 */
4431 (void)tsleep((void *)&bufqueues[BQ_LAUNDRY], PRIBIO, "blaundry", 1);
91447636
A
4432 loopcnt = 0;
4433 } else {
6d2010ae
A
4434 /* give other threads a chance to run */
4435 (void)thread_block(THREAD_CONTINUE_NULL);
91447636
A
4436 loopcnt++;
4437 }
4438 }
4439 }
4440}
4441
4442
4443static int
4444brecover_data(buf_t bp)
4445{
4446 int upl_offset;
4447 upl_t upl;
4448 upl_page_info_t *pl;
4449 kern_return_t kret;
4450 vnode_t vp = bp->b_vp;
4451 int upl_flags;
4452
4453
4454 if ( !UBCINFOEXISTS(vp) || bp->b_bufsize == 0)
4455 goto dump_buffer;
4456
4457 upl_flags = UPL_PRECIOUS;
4458 if (! (buf_flags(bp) & B_READ)) {
4459 /*
4460 * "write" operation: let the UPL subsystem know
4461 * that we intend to modify the buffer cache pages we're
4462 * gathering.
4463 */
4464 upl_flags |= UPL_WILL_MODIFY;
4465 }
4466
4467 kret = ubc_create_upl(vp,
4468 ubc_blktooff(vp, bp->b_lblkno),
4469 bp->b_bufsize,
4470 &upl,
4471 &pl,
4472 upl_flags);
4473 if (kret != KERN_SUCCESS)
4474 panic("Failed to create UPL");
4475
4476 for (upl_offset = 0; upl_offset < bp->b_bufsize; upl_offset += PAGE_SIZE) {
4477
4478 if (!upl_valid_page(pl, upl_offset / PAGE_SIZE) || !upl_dirty_page(pl, upl_offset / PAGE_SIZE)) {
4479 ubc_upl_abort(upl, 0);
4480 goto dump_buffer;
4481 }
4482 }
4483 bp->b_upl = upl;
4484
b0d623f7 4485 kret = ubc_upl_map(upl, (vm_offset_t *)&(bp->b_datap));
91447636
A
4486
4487 if (kret != KERN_SUCCESS)
4488 panic("getblk: ubc_upl_map() failed with (%d)", kret);
4489 return (1);
4490
4491dump_buffer:
4492 bp->b_bufsize = 0;
4493 SET(bp->b_flags, B_INVAL);
4494 buf_brelse(bp);
4495
4496 return(0);
4497}
4498
b7266188 4499boolean_t
0b4c1975 4500buffer_cache_gc(int all)
b0d623f7
A
4501{
4502 buf_t bp;
4503 boolean_t did_large_zfree = FALSE;
6d2010ae 4504 boolean_t need_wakeup = FALSE;
b0d623f7 4505 int now = buf_timestamp();
316670eb 4506 uint32_t found = 0;
6d2010ae 4507 struct bqueues privq;
0b4c1975
A
4508 int thresh_hold = BUF_STALE_THRESHHOLD;
4509
4510 if (all)
4511 thresh_hold = 0;
6d2010ae
A
4512 /*
4513 * We only care about metadata (incore storage comes from zalloc()).
316670eb
A
4514 * Unless "all" is set (used to evict meta data buffers in preparation
4515 * for deep sleep), we only evict up to BUF_MAX_GC_BATCH_SIZE buffers
fe8ab488
A
4516 * that have not been accessed in the last BUF_STALE_THRESHOLD seconds.
4517 * BUF_MAX_GC_BATCH_SIZE controls both the hold time of the global lock
4518 * "buf_mtxp" and the length of time we spend compute bound in the GC
4519 * thread which calls this function
6d2010ae
A
4520 */
4521 lck_mtx_lock(buf_mtxp);
316670eb 4522
6d2010ae
A
4523 do {
4524 found = 0;
4525 TAILQ_INIT(&privq);
4526 need_wakeup = FALSE;
b0d623f7 4527
6d2010ae
A
4528 while (((bp = TAILQ_FIRST(&bufqueues[BQ_META]))) &&
4529 (now > bp->b_timestamp) &&
4530 (now - bp->b_timestamp > thresh_hold) &&
4531 (found < BUF_MAX_GC_BATCH_SIZE)) {
4532
4533 /* Remove from free list */
4534 bremfree_locked(bp);
4535 found++;
4536
4537#ifdef JOE_DEBUG
4538 bp->b_owner = current_thread();
4539 bp->b_tag = 12;
4540#endif
4541
4542 /* If dirty, move to laundry queue and remember to do wakeup */
4543 if (ISSET(bp->b_flags, B_DELWRI)) {
4544 SET(bp->b_lflags, BL_WANTDEALLOC);
4545
4546 bmovelaundry(bp);
4547 need_wakeup = TRUE;
4548
4549 continue;
4550 }
4551
4552 /*
4553 * Mark busy and put on private list. We could technically get
4554 * away without setting BL_BUSY here.
4555 */
4556 SET(bp->b_lflags, BL_BUSY);
4557 buf_busycount++;
b0d623f7 4558
6d2010ae
A
4559 /*
4560 * Remove from hash and dissociate from vp.
4561 */
4562 bremhash(bp);
4563 if (bp->b_vp) {
4564 brelvp_locked(bp);
4565 }
b0d623f7 4566
6d2010ae
A
4567 TAILQ_INSERT_TAIL(&privq, bp, b_freelist);
4568 }
b0d623f7 4569
6d2010ae
A
4570 if (found == 0) {
4571 break;
4572 }
b0d623f7 4573
6d2010ae
A
4574 /* Drop lock for batch processing */
4575 lck_mtx_unlock(buf_mtxp);
4576
4577 /* Wakeup and yield for laundry if need be */
4578 if (need_wakeup) {
4579 wakeup(&bufqueues[BQ_LAUNDRY]);
4580 (void)thread_block(THREAD_CONTINUE_NULL);
b0d623f7 4581 }
6d2010ae
A
4582
4583 /* Clean up every buffer on private list */
4584 TAILQ_FOREACH(bp, &privq, b_freelist) {
4585 /* Take note if we've definitely freed at least a page to a zone */
4586 if ((ISSET(bp->b_flags, B_ZALLOC)) && (buf_size(bp) >= PAGE_SIZE)) {
4587 did_large_zfree = TRUE;
4588 }
4589
4590 trace(TR_BRELSE, pack(bp->b_vp, bp->b_bufsize), bp->b_lblkno);
4591
4592 /* Free Storage */
4593 buf_free_meta_store(bp);
4594
4595 /* Release credentials */
4596 buf_release_credentials(bp);
4597
4598 /* Prepare for moving to empty queue */
4599 CLR(bp->b_flags, (B_META | B_ZALLOC | B_DELWRI | B_LOCKED
4600 | B_AGE | B_ASYNC | B_NOCACHE | B_FUA));
4601 bp->b_whichq = BQ_EMPTY;
4602 BLISTNONE(bp);
4603 }
6d2010ae
A
4604 lck_mtx_lock(buf_mtxp);
4605
4606 /* Back under lock, move them all to invalid hash and clear busy */
4607 TAILQ_FOREACH(bp, &privq, b_freelist) {
4608 binshash(bp, &invalhash);
4609 CLR(bp->b_lflags, BL_BUSY);
4610 buf_busycount--;
4611
4612#ifdef JOE_DEBUG
4613 if (bp->b_owner != current_thread()) {
4614 panic("Buffer stolen from buffer_cache_gc()");
4615 }
4616 bp->b_owner = current_thread();
4617 bp->b_tag = 13;
4618#endif
4619 }
4620
4621 /* And do a big bulk move to the empty queue */
4622 TAILQ_CONCAT(&bufqueues[BQ_EMPTY], &privq, b_freelist);
6d2010ae 4623
316670eb 4624 } while (all && (found == BUF_MAX_GC_BATCH_SIZE));
b0d623f7
A
4625
4626 lck_mtx_unlock(buf_mtxp);
4627
4628 return did_large_zfree;
4629}
91447636
A
4630
4631
4632/*
4633 * disabled for now
4634 */
4635
4636#if FLUSH_QUEUES
4637
4638#define NFLUSH 32
4639
4640static int
4641bp_cmp(void *a, void *b)
4642{
4643 buf_t *bp_a = *(buf_t **)a,
4644 *bp_b = *(buf_t **)b;
4645 daddr64_t res;
1c79356b 4646
91447636
A
4647 // don't have to worry about negative block
4648 // numbers so this is ok to do.
4649 //
4650 res = (bp_a->b_blkno - bp_b->b_blkno);
4651
4652 return (int)res;
1c79356b 4653}
1c79356b
A
4654
4655
91447636
A
4656int
4657bflushq(int whichq, mount_t mp)
1c79356b 4658{
91447636
A
4659 buf_t bp, next;
4660 int i, buf_count;
4661 int total_writes = 0;
4662 static buf_t flush_table[NFLUSH];
1c79356b 4663
91447636
A
4664 if (whichq < 0 || whichq >= BQUEUES) {
4665 return (0);
0b4e3aa0
A
4666 }
4667
91447636
A
4668 restart:
4669 lck_mtx_lock(buf_mtxp);
0b4e3aa0 4670
91447636 4671 bp = TAILQ_FIRST(&bufqueues[whichq]);
1c79356b 4672
91447636
A
4673 for (buf_count = 0; bp; bp = next) {
4674 next = bp->b_freelist.tqe_next;
4675
4676 if (bp->b_vp == NULL || bp->b_vp->v_mount != mp) {
4677 continue;
4678 }
b4c24cb9 4679
91447636 4680 if (ISSET(bp->b_flags, B_DELWRI) && !ISSET(bp->b_lflags, BL_BUSY)) {
1c79356b 4681
91447636
A
4682 bremfree_locked(bp);
4683#ifdef JOE_DEBUG
4684 bp->b_owner = current_thread();
4685 bp->b_tag = 7;
4686#endif
4687 SET(bp->b_lflags, BL_BUSY);
b0d623f7
A
4688 buf_busycount++;
4689
91447636
A
4690 flush_table[buf_count] = bp;
4691 buf_count++;
4692 total_writes++;
1c79356b 4693
91447636
A
4694 if (buf_count >= NFLUSH) {
4695 lck_mtx_unlock(buf_mtxp);
1c79356b 4696
91447636 4697 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
1c79356b 4698
91447636
A
4699 for (i = 0; i < buf_count; i++) {
4700 buf_bawrite(flush_table[i]);
4701 }
4702 goto restart;
4703 }
4704 }
4705 }
4706 lck_mtx_unlock(buf_mtxp);
1c79356b 4707
91447636
A
4708 if (buf_count > 0) {
4709 qsort(flush_table, buf_count, sizeof(struct buf *), bp_cmp);
1c79356b 4710
91447636
A
4711 for (i = 0; i < buf_count; i++) {
4712 buf_bawrite(flush_table[i]);
4713 }
1c79356b 4714 }
91447636
A
4715
4716 return (total_writes);
1c79356b 4717}
91447636 4718#endif