xref: /illumos-gate/usr/src/uts/common/fs/zfs/arc.c (revision 051d39bbeea3e1b0fd8395dc97be34acb3241891)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * DVA-based Adjustable Relpacement Cache
30  *
31  * While much of the theory of operation used here is
32  * based on the self-tuning, low overhead replacement cache
33  * presented by Megiddo and Modha at FAST 2003, there are some
34  * significant differences:
35  *
36  * 1. The Megiddo and Modha model assumes any page is evictable.
37  * Pages in its cache cannot be "locked" into memory.  This makes
38  * the eviction algorithm simple: evict the last page in the list.
39  * This also make the performance characteristics easy to reason
40  * about.  Our cache is not so simple.  At any given moment, some
41  * subset of the blocks in the cache are un-evictable because we
42  * have handed out a reference to them.  Blocks are only evictable
43  * when there are no external references active.  This makes
44  * eviction far more problematic:  we choose to evict the evictable
45  * blocks that are the "lowest" in the list.
46  *
47  * There are times when it is not possible to evict the requested
48  * space.  In these circumstances we are unable to adjust the cache
49  * size.  To prevent the cache growing unbounded at these times we
50  * implement a "cache throttle" that slowes the flow of new data
51  * into the cache until we can make space avaiable.
52  *
53  * 2. The Megiddo and Modha model assumes a fixed cache size.
54  * Pages are evicted when the cache is full and there is a cache
55  * miss.  Our model has a variable sized cache.  It grows with
56  * high use, but also tries to react to memory preasure from the
57  * operating system: decreasing its size when system memory is
58  * tight.
59  *
60  * 3. The Megiddo and Modha model assumes a fixed page size. All
61  * elements of the cache are therefor exactly the same size.  So
62  * when adjusting the cache size following a cache miss, its simply
63  * a matter of choosing a single page to evict.  In our model, we
64  * have variable sized cache blocks (rangeing from 512 bytes to
65  * 128K bytes).  We therefor choose a set of blocks to evict to make
66  * space for a cache miss that approximates as closely as possible
67  * the space used by the new block.
68  *
69  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70  * by N. Megiddo & D. Modha, FAST 2003
71  */
72 
73 /*
74  * The locking model:
75  *
76  * A new reference to a cache buffer can be obtained in two
77  * ways: 1) via a hash table lookup using the DVA as a key,
78  * or 2) via one of the ARC lists.  The arc_read() inerface
79  * uses method 1, while the internal arc algorithms for
80  * adjusting the cache use method 2.  We therefor provide two
81  * types of locks: 1) the hash table lock array, and 2) the
82  * arc list locks.
83  *
84  * Buffers do not have their own mutexs, rather they rely on the
85  * hash table mutexs for the bulk of their protection (i.e. most
86  * fields in the arc_buf_hdr_t are protected by these mutexs).
87  *
88  * buf_hash_find() returns the appropriate mutex (held) when it
89  * locates the requested buffer in the hash table.  It returns
90  * NULL for the mutex if the buffer was not in the table.
91  *
92  * buf_hash_remove() expects the appropriate hash mutex to be
93  * already held before it is invoked.
94  *
95  * Each arc state also has a mutex which is used to protect the
96  * buffer list associated with the state.  When attempting to
97  * obtain a hash table lock while holding an arc list lock you
98  * must use: mutex_tryenter() to avoid deadlock.  Also note that
99  * the active state mutex must be held before the ghost state mutex.
100  *
101  * Arc buffers may have an associated eviction callback function.
102  * This function will be invoked prior to removing the buffer (e.g.
103  * in arc_do_user_evicts()).  Note however that the data associated
104  * with the buffer may be evicted prior to the callback.  The callback
105  * must be made with *no locks held* (to prevent deadlock).  Additionally,
106  * the users of callbacks must ensure that their private data is
107  * protected from simultaneous callbacks from arc_buf_evict()
108  * and arc_do_user_evicts().
109  *
110  * Note that the majority of the performance stats are manipulated
111  * with atomic operations.
112  */
113 
114 #include <sys/spa.h>
115 #include <sys/zio.h>
116 #include <sys/zio_checksum.h>
117 #include <sys/zfs_context.h>
118 #include <sys/arc.h>
119 #include <sys/refcount.h>
120 #ifdef _KERNEL
121 #include <sys/vmsystm.h>
122 #include <vm/anon.h>
123 #include <sys/fs/swapnode.h>
124 #include <sys/dnlc.h>
125 #endif
126 #include <sys/callb.h>
127 
128 static kmutex_t		arc_reclaim_thr_lock;
129 static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
130 static uint8_t		arc_thread_exit;
131 
132 #define	ARC_REDUCE_DNLC_PERCENT	3
133 uint_t arc_reduce_dnlc_percent = ARC_REDUCE_DNLC_PERCENT;
134 
135 typedef enum arc_reclaim_strategy {
136 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
137 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
138 } arc_reclaim_strategy_t;
139 
140 /* number of seconds before growing cache again */
141 static int		arc_grow_retry = 60;
142 
143 /*
144  * minimum lifespan of a prefetch block in clock ticks
145  * (initialized in arc_init())
146  */
147 static int		arc_min_prefetch_lifespan;
148 
149 static int arc_dead;
150 
151 /*
152  * These tunables are for performance analysis.
153  */
154 uint64_t zfs_arc_max;
155 uint64_t zfs_arc_min;
156 
157 /*
158  * Note that buffers can be on one of 5 states:
159  *	ARC_anon	- anonymous (discussed below)
160  *	ARC_mru		- recently used, currently cached
161  *	ARC_mru_ghost	- recentely used, no longer in cache
162  *	ARC_mfu		- frequently used, currently cached
163  *	ARC_mfu_ghost	- frequently used, no longer in cache
164  * When there are no active references to the buffer, they
165  * are linked onto one of the lists in arc.  These are the
166  * only buffers that can be evicted or deleted.
167  *
168  * Anonymous buffers are buffers that are not associated with
169  * a DVA.  These are buffers that hold dirty block copies
170  * before they are written to stable storage.  By definition,
171  * they are "ref'd" and are considered part of arc_mru
172  * that cannot be freed.  Generally, they will aquire a DVA
173  * as they are written and migrate onto the arc_mru list.
174  */
175 
176 typedef struct arc_state {
177 	list_t	list;	/* linked list of evictable buffer in state */
178 	uint64_t lsize;	/* total size of buffers in the linked list */
179 	uint64_t size;	/* total size of all buffers in this state */
180 	uint64_t hits;
181 	kmutex_t mtx;
182 } arc_state_t;
183 
184 /* The 5 states: */
185 static arc_state_t ARC_anon;
186 static arc_state_t ARC_mru;
187 static arc_state_t ARC_mru_ghost;
188 static arc_state_t ARC_mfu;
189 static arc_state_t ARC_mfu_ghost;
190 
191 static struct arc {
192 	arc_state_t 	*anon;
193 	arc_state_t	*mru;
194 	arc_state_t	*mru_ghost;
195 	arc_state_t	*mfu;
196 	arc_state_t	*mfu_ghost;
197 	uint64_t	size;		/* Actual total arc size */
198 	uint64_t	p;		/* Target size (in bytes) of mru */
199 	uint64_t	c;		/* Target size of cache (in bytes) */
200 	uint64_t	c_min;		/* Minimum target cache size */
201 	uint64_t	c_max;		/* Maximum target cache size */
202 
203 	/* performance stats */
204 	uint64_t	hits;
205 	uint64_t	misses;
206 	uint64_t	deleted;
207 	uint64_t	recycle_miss;
208 	uint64_t	mutex_miss;
209 	uint64_t	evict_skip;
210 	uint64_t	hash_elements;
211 	uint64_t	hash_elements_max;
212 	uint64_t	hash_collisions;
213 	uint64_t	hash_chains;
214 	uint32_t	hash_chain_max;
215 
216 	int		no_grow;	/* Don't try to grow cache size */
217 } arc;
218 
219 static uint64_t arc_tempreserve;
220 
221 typedef struct arc_callback arc_callback_t;
222 
223 struct arc_callback {
224 	arc_done_func_t		*acb_done;
225 	void			*acb_private;
226 	arc_byteswap_func_t	*acb_byteswap;
227 	arc_buf_t		*acb_buf;
228 	zio_t			*acb_zio_dummy;
229 	arc_callback_t		*acb_next;
230 };
231 
232 struct arc_buf_hdr {
233 	/* protected by hash lock */
234 	dva_t			b_dva;
235 	uint64_t		b_birth;
236 	uint64_t		b_cksum0;
237 
238 	kmutex_t		b_freeze_lock;
239 	zio_cksum_t		*b_freeze_cksum;
240 
241 	arc_buf_hdr_t		*b_hash_next;
242 	arc_buf_t		*b_buf;
243 	uint32_t		b_flags;
244 	uint32_t		b_datacnt;
245 
246 	arc_callback_t		*b_acb;
247 	kcondvar_t		b_cv;
248 
249 	/* immutable */
250 	arc_buf_contents_t	b_type;
251 	uint64_t		b_size;
252 	spa_t			*b_spa;
253 
254 	/* protected by arc state mutex */
255 	arc_state_t		*b_state;
256 	list_node_t		b_arc_node;
257 
258 	/* updated atomically */
259 	clock_t			b_arc_access;
260 
261 	/* self protecting */
262 	refcount_t		b_refcnt;
263 };
264 
265 static arc_buf_t *arc_eviction_list;
266 static kmutex_t arc_eviction_mtx;
267 static arc_buf_hdr_t arc_eviction_hdr;
268 static void arc_get_data_buf(arc_buf_t *buf);
269 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
270 
271 #define	GHOST_STATE(state)	\
272 	((state) == arc.mru_ghost || (state) == arc.mfu_ghost)
273 
274 /*
275  * Private ARC flags.  These flags are private ARC only flags that will show up
276  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
277  * be passed in as arc_flags in things like arc_read.  However, these flags
278  * should never be passed and should only be set by ARC code.  When adding new
279  * public flags, make sure not to smash the private ones.
280  */
281 
282 #define	ARC_IN_HASH_TABLE	(1 << 9)	/* this buffer is hashed */
283 #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
284 #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
285 #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
286 #define	ARC_BUF_AVAILABLE	(1 << 13)	/* block not in active use */
287 #define	ARC_INDIRECT		(1 << 14)	/* this is an indirect block */
288 
289 #define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_IN_HASH_TABLE)
290 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
291 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
292 #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
293 #define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_BUF_AVAILABLE)
294 
295 /*
296  * Hash table routines
297  */
298 
299 #define	HT_LOCK_PAD	64
300 
301 struct ht_lock {
302 	kmutex_t	ht_lock;
303 #ifdef _KERNEL
304 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
305 #endif
306 };
307 
308 #define	BUF_LOCKS 256
309 typedef struct buf_hash_table {
310 	uint64_t ht_mask;
311 	arc_buf_hdr_t **ht_table;
312 	struct ht_lock ht_locks[BUF_LOCKS];
313 } buf_hash_table_t;
314 
315 static buf_hash_table_t buf_hash_table;
316 
317 #define	BUF_HASH_INDEX(spa, dva, birth) \
318 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
319 #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
320 #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
321 #define	HDR_LOCK(buf) \
322 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
323 
324 uint64_t zfs_crc64_table[256];
325 
326 static uint64_t
327 buf_hash(spa_t *spa, dva_t *dva, uint64_t birth)
328 {
329 	uintptr_t spav = (uintptr_t)spa;
330 	uint8_t *vdva = (uint8_t *)dva;
331 	uint64_t crc = -1ULL;
332 	int i;
333 
334 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
335 
336 	for (i = 0; i < sizeof (dva_t); i++)
337 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
338 
339 	crc ^= (spav>>8) ^ birth;
340 
341 	return (crc);
342 }
343 
344 #define	BUF_EMPTY(buf)						\
345 	((buf)->b_dva.dva_word[0] == 0 &&			\
346 	(buf)->b_dva.dva_word[1] == 0 &&			\
347 	(buf)->b_birth == 0)
348 
349 #define	BUF_EQUAL(spa, dva, birth, buf)				\
350 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
351 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
352 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
353 
354 static arc_buf_hdr_t *
355 buf_hash_find(spa_t *spa, dva_t *dva, uint64_t birth, kmutex_t **lockp)
356 {
357 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
358 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
359 	arc_buf_hdr_t *buf;
360 
361 	mutex_enter(hash_lock);
362 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
363 	    buf = buf->b_hash_next) {
364 		if (BUF_EQUAL(spa, dva, birth, buf)) {
365 			*lockp = hash_lock;
366 			return (buf);
367 		}
368 	}
369 	mutex_exit(hash_lock);
370 	*lockp = NULL;
371 	return (NULL);
372 }
373 
374 /*
375  * Insert an entry into the hash table.  If there is already an element
376  * equal to elem in the hash table, then the already existing element
377  * will be returned and the new element will not be inserted.
378  * Otherwise returns NULL.
379  */
380 static arc_buf_hdr_t *
381 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
382 {
383 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
384 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
385 	arc_buf_hdr_t *fbuf;
386 	uint32_t max, i;
387 
388 	ASSERT(!HDR_IN_HASH_TABLE(buf));
389 	*lockp = hash_lock;
390 	mutex_enter(hash_lock);
391 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
392 	    fbuf = fbuf->b_hash_next, i++) {
393 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
394 			return (fbuf);
395 	}
396 
397 	buf->b_hash_next = buf_hash_table.ht_table[idx];
398 	buf_hash_table.ht_table[idx] = buf;
399 	buf->b_flags |= ARC_IN_HASH_TABLE;
400 
401 	/* collect some hash table performance data */
402 	if (i > 0) {
403 		atomic_add_64(&arc.hash_collisions, 1);
404 		if (i == 1)
405 			atomic_add_64(&arc.hash_chains, 1);
406 	}
407 	while (i > (max = arc.hash_chain_max) &&
408 	    max != atomic_cas_32(&arc.hash_chain_max, max, i)) {
409 		continue;
410 	}
411 	atomic_add_64(&arc.hash_elements, 1);
412 	if (arc.hash_elements > arc.hash_elements_max)
413 		atomic_add_64(&arc.hash_elements_max, 1);
414 
415 	return (NULL);
416 }
417 
418 static void
419 buf_hash_remove(arc_buf_hdr_t *buf)
420 {
421 	arc_buf_hdr_t *fbuf, **bufp;
422 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
423 
424 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
425 	ASSERT(HDR_IN_HASH_TABLE(buf));
426 
427 	bufp = &buf_hash_table.ht_table[idx];
428 	while ((fbuf = *bufp) != buf) {
429 		ASSERT(fbuf != NULL);
430 		bufp = &fbuf->b_hash_next;
431 	}
432 	*bufp = buf->b_hash_next;
433 	buf->b_hash_next = NULL;
434 	buf->b_flags &= ~ARC_IN_HASH_TABLE;
435 
436 	/* collect some hash table performance data */
437 	atomic_add_64(&arc.hash_elements, -1);
438 	if (buf_hash_table.ht_table[idx] &&
439 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
440 		atomic_add_64(&arc.hash_chains, -1);
441 }
442 
443 /*
444  * Global data structures and functions for the buf kmem cache.
445  */
446 static kmem_cache_t *hdr_cache;
447 static kmem_cache_t *buf_cache;
448 
449 static void
450 buf_fini(void)
451 {
452 	int i;
453 
454 	kmem_free(buf_hash_table.ht_table,
455 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
456 	for (i = 0; i < BUF_LOCKS; i++)
457 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
458 	kmem_cache_destroy(hdr_cache);
459 	kmem_cache_destroy(buf_cache);
460 }
461 
462 /*
463  * Constructor callback - called when the cache is empty
464  * and a new buf is requested.
465  */
466 /* ARGSUSED */
467 static int
468 hdr_cons(void *vbuf, void *unused, int kmflag)
469 {
470 	arc_buf_hdr_t *buf = vbuf;
471 
472 	bzero(buf, sizeof (arc_buf_hdr_t));
473 	refcount_create(&buf->b_refcnt);
474 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
475 	return (0);
476 }
477 
478 /*
479  * Destructor callback - called when a cached buf is
480  * no longer required.
481  */
482 /* ARGSUSED */
483 static void
484 hdr_dest(void *vbuf, void *unused)
485 {
486 	arc_buf_hdr_t *buf = vbuf;
487 
488 	refcount_destroy(&buf->b_refcnt);
489 	cv_destroy(&buf->b_cv);
490 }
491 
492 /*
493  * Reclaim callback -- invoked when memory is low.
494  */
495 /* ARGSUSED */
496 static void
497 hdr_recl(void *unused)
498 {
499 	dprintf("hdr_recl called\n");
500 	/*
501 	 * umem calls the reclaim func when we destroy the buf cache,
502 	 * which is after we do arc_fini().
503 	 */
504 	if (!arc_dead)
505 		cv_signal(&arc_reclaim_thr_cv);
506 }
507 
508 static void
509 buf_init(void)
510 {
511 	uint64_t *ct;
512 	uint64_t hsize = 1ULL << 12;
513 	int i, j;
514 
515 	/*
516 	 * The hash table is big enough to fill all of physical memory
517 	 * with an average 64K block size.  The table will take up
518 	 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
519 	 */
520 	while (hsize * 65536 < physmem * PAGESIZE)
521 		hsize <<= 1;
522 retry:
523 	buf_hash_table.ht_mask = hsize - 1;
524 	buf_hash_table.ht_table =
525 	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
526 	if (buf_hash_table.ht_table == NULL) {
527 		ASSERT(hsize > (1ULL << 8));
528 		hsize >>= 1;
529 		goto retry;
530 	}
531 
532 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
533 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
534 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
535 	    0, NULL, NULL, NULL, NULL, NULL, 0);
536 
537 	for (i = 0; i < 256; i++)
538 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
539 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
540 
541 	for (i = 0; i < BUF_LOCKS; i++) {
542 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
543 		    NULL, MUTEX_DEFAULT, NULL);
544 	}
545 }
546 
547 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
548 
549 static void
550 arc_cksum_verify(arc_buf_t *buf)
551 {
552 	zio_cksum_t zc;
553 
554 	if (!zfs_flags & ZFS_DEBUG_MODIFY)
555 		return;
556 
557 	mutex_enter(&buf->b_hdr->b_freeze_lock);
558 	if (buf->b_hdr->b_freeze_cksum == NULL ||
559 	    (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
560 		mutex_exit(&buf->b_hdr->b_freeze_lock);
561 		return;
562 	}
563 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
564 	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
565 		panic("buffer modified while frozen!");
566 	mutex_exit(&buf->b_hdr->b_freeze_lock);
567 }
568 
569 static void
570 arc_cksum_compute(arc_buf_t *buf)
571 {
572 	if (!zfs_flags & ZFS_DEBUG_MODIFY)
573 		return;
574 
575 	mutex_enter(&buf->b_hdr->b_freeze_lock);
576 	if (buf->b_hdr->b_freeze_cksum != NULL) {
577 		mutex_exit(&buf->b_hdr->b_freeze_lock);
578 		return;
579 	}
580 	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
581 	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
582 	    buf->b_hdr->b_freeze_cksum);
583 	mutex_exit(&buf->b_hdr->b_freeze_lock);
584 }
585 
586 void
587 arc_buf_thaw(arc_buf_t *buf)
588 {
589 	if (!zfs_flags & ZFS_DEBUG_MODIFY)
590 		return;
591 
592 	if (buf->b_hdr->b_state != arc.anon)
593 		panic("modifying non-anon buffer!");
594 	if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
595 		panic("modifying buffer while i/o in progress!");
596 	arc_cksum_verify(buf);
597 	mutex_enter(&buf->b_hdr->b_freeze_lock);
598 	if (buf->b_hdr->b_freeze_cksum != NULL) {
599 		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
600 		buf->b_hdr->b_freeze_cksum = NULL;
601 	}
602 	mutex_exit(&buf->b_hdr->b_freeze_lock);
603 }
604 
605 void
606 arc_buf_freeze(arc_buf_t *buf)
607 {
608 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
609 	    buf->b_hdr->b_state == arc.anon);
610 	arc_cksum_compute(buf);
611 }
612 
613 static void
614 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
615 {
616 	ASSERT(MUTEX_HELD(hash_lock));
617 
618 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
619 	    (ab->b_state != arc.anon)) {
620 		int delta = ab->b_size * ab->b_datacnt;
621 
622 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
623 		mutex_enter(&ab->b_state->mtx);
624 		ASSERT(list_link_active(&ab->b_arc_node));
625 		list_remove(&ab->b_state->list, ab);
626 		if (GHOST_STATE(ab->b_state)) {
627 			ASSERT3U(ab->b_datacnt, ==, 0);
628 			ASSERT3P(ab->b_buf, ==, NULL);
629 			delta = ab->b_size;
630 		}
631 		ASSERT(delta > 0);
632 		ASSERT3U(ab->b_state->lsize, >=, delta);
633 		atomic_add_64(&ab->b_state->lsize, -delta);
634 		mutex_exit(&ab->b_state->mtx);
635 		/* remove the prefetch flag is we get a reference */
636 		if (ab->b_flags & ARC_PREFETCH)
637 			ab->b_flags &= ~ARC_PREFETCH;
638 	}
639 }
640 
641 static int
642 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
643 {
644 	int cnt;
645 
646 	ASSERT(ab->b_state == arc.anon || MUTEX_HELD(hash_lock));
647 	ASSERT(!GHOST_STATE(ab->b_state));
648 
649 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
650 	    (ab->b_state != arc.anon)) {
651 
652 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
653 		mutex_enter(&ab->b_state->mtx);
654 		ASSERT(!list_link_active(&ab->b_arc_node));
655 		list_insert_head(&ab->b_state->list, ab);
656 		ASSERT(ab->b_datacnt > 0);
657 		atomic_add_64(&ab->b_state->lsize, ab->b_size * ab->b_datacnt);
658 		ASSERT3U(ab->b_state->size, >=, ab->b_state->lsize);
659 		mutex_exit(&ab->b_state->mtx);
660 	}
661 	return (cnt);
662 }
663 
664 /*
665  * Move the supplied buffer to the indicated state.  The mutex
666  * for the buffer must be held by the caller.
667  */
668 static void
669 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
670 {
671 	arc_state_t *old_state = ab->b_state;
672 	int refcnt = refcount_count(&ab->b_refcnt);
673 	int from_delta, to_delta;
674 
675 	ASSERT(MUTEX_HELD(hash_lock));
676 	ASSERT(new_state != old_state);
677 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
678 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
679 
680 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
681 
682 	/*
683 	 * If this buffer is evictable, transfer it from the
684 	 * old state list to the new state list.
685 	 */
686 	if (refcnt == 0) {
687 		if (old_state != arc.anon) {
688 			int use_mutex = !MUTEX_HELD(&old_state->mtx);
689 
690 			if (use_mutex)
691 				mutex_enter(&old_state->mtx);
692 
693 			ASSERT(list_link_active(&ab->b_arc_node));
694 			list_remove(&old_state->list, ab);
695 
696 			/*
697 			 * If prefetching out of the ghost cache,
698 			 * we will have a non-null datacnt.
699 			 */
700 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
701 				/* ghost elements have a ghost size */
702 				ASSERT(ab->b_buf == NULL);
703 				from_delta = ab->b_size;
704 			}
705 			ASSERT3U(old_state->lsize, >=, from_delta);
706 			atomic_add_64(&old_state->lsize, -from_delta);
707 
708 			if (use_mutex)
709 				mutex_exit(&old_state->mtx);
710 		}
711 		if (new_state != arc.anon) {
712 			int use_mutex = !MUTEX_HELD(&new_state->mtx);
713 
714 			if (use_mutex)
715 				mutex_enter(&new_state->mtx);
716 
717 			list_insert_head(&new_state->list, ab);
718 
719 			/* ghost elements have a ghost size */
720 			if (GHOST_STATE(new_state)) {
721 				ASSERT(ab->b_datacnt == 0);
722 				ASSERT(ab->b_buf == NULL);
723 				to_delta = ab->b_size;
724 			}
725 			atomic_add_64(&new_state->lsize, to_delta);
726 			ASSERT3U(new_state->size + to_delta, >=,
727 			    new_state->lsize);
728 
729 			if (use_mutex)
730 				mutex_exit(&new_state->mtx);
731 		}
732 	}
733 
734 	ASSERT(!BUF_EMPTY(ab));
735 	if (new_state == arc.anon && old_state != arc.anon) {
736 		buf_hash_remove(ab);
737 	}
738 
739 	/* adjust state sizes */
740 	if (to_delta)
741 		atomic_add_64(&new_state->size, to_delta);
742 	if (from_delta) {
743 		ASSERT3U(old_state->size, >=, from_delta);
744 		atomic_add_64(&old_state->size, -from_delta);
745 	}
746 	ab->b_state = new_state;
747 }
748 
749 arc_buf_t *
750 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
751 {
752 	arc_buf_hdr_t *hdr;
753 	arc_buf_t *buf;
754 
755 	ASSERT3U(size, >, 0);
756 	hdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
757 	ASSERT(BUF_EMPTY(hdr));
758 	hdr->b_size = size;
759 	hdr->b_type = type;
760 	hdr->b_spa = spa;
761 	hdr->b_state = arc.anon;
762 	hdr->b_arc_access = 0;
763 	buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
764 	buf->b_hdr = hdr;
765 	buf->b_data = NULL;
766 	buf->b_efunc = NULL;
767 	buf->b_private = NULL;
768 	buf->b_next = NULL;
769 	hdr->b_buf = buf;
770 	arc_get_data_buf(buf);
771 	hdr->b_datacnt = 1;
772 	hdr->b_flags = 0;
773 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
774 	(void) refcount_add(&hdr->b_refcnt, tag);
775 
776 	return (buf);
777 }
778 
779 static arc_buf_t *
780 arc_buf_clone(arc_buf_t *from)
781 {
782 	arc_buf_t *buf;
783 	arc_buf_hdr_t *hdr = from->b_hdr;
784 	uint64_t size = hdr->b_size;
785 
786 	buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
787 	buf->b_hdr = hdr;
788 	buf->b_data = NULL;
789 	buf->b_efunc = NULL;
790 	buf->b_private = NULL;
791 	buf->b_next = hdr->b_buf;
792 	hdr->b_buf = buf;
793 	arc_get_data_buf(buf);
794 	bcopy(from->b_data, buf->b_data, size);
795 	hdr->b_datacnt += 1;
796 	return (buf);
797 }
798 
799 void
800 arc_buf_add_ref(arc_buf_t *buf, void* tag)
801 {
802 	arc_buf_hdr_t *hdr;
803 	kmutex_t *hash_lock;
804 
805 	/*
806 	 * Check to see if this buffer is currently being evicted via
807 	 * arc_do_user_evicts().
808 	 */
809 	mutex_enter(&arc_eviction_mtx);
810 	hdr = buf->b_hdr;
811 	if (hdr == NULL) {
812 		mutex_exit(&arc_eviction_mtx);
813 		return;
814 	}
815 	hash_lock = HDR_LOCK(hdr);
816 	mutex_exit(&arc_eviction_mtx);
817 
818 	mutex_enter(hash_lock);
819 	if (buf->b_data == NULL) {
820 		/*
821 		 * This buffer is evicted.
822 		 */
823 		mutex_exit(hash_lock);
824 		return;
825 	}
826 
827 	ASSERT(buf->b_hdr == hdr);
828 	ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
829 	add_reference(hdr, hash_lock, tag);
830 	arc_access(hdr, hash_lock);
831 	mutex_exit(hash_lock);
832 	atomic_add_64(&arc.hits, 1);
833 }
834 
835 static void
836 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
837 {
838 	arc_buf_t **bufp;
839 
840 	/* free up data associated with the buf */
841 	if (buf->b_data) {
842 		arc_state_t *state = buf->b_hdr->b_state;
843 		uint64_t size = buf->b_hdr->b_size;
844 		arc_buf_contents_t type = buf->b_hdr->b_type;
845 
846 		arc_cksum_verify(buf);
847 		if (!recycle) {
848 			if (type == ARC_BUFC_METADATA) {
849 				zio_buf_free(buf->b_data, size);
850 			} else {
851 				ASSERT(type == ARC_BUFC_DATA);
852 				zio_data_buf_free(buf->b_data, size);
853 			}
854 			atomic_add_64(&arc.size, -size);
855 		}
856 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
857 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
858 			ASSERT(state != arc.anon);
859 			ASSERT3U(state->lsize, >=, size);
860 			atomic_add_64(&state->lsize, -size);
861 		}
862 		ASSERT3U(state->size, >=, size);
863 		atomic_add_64(&state->size, -size);
864 		buf->b_data = NULL;
865 		ASSERT(buf->b_hdr->b_datacnt > 0);
866 		buf->b_hdr->b_datacnt -= 1;
867 	}
868 
869 	/* only remove the buf if requested */
870 	if (!all)
871 		return;
872 
873 	/* remove the buf from the hdr list */
874 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
875 		continue;
876 	*bufp = buf->b_next;
877 
878 	ASSERT(buf->b_efunc == NULL);
879 
880 	/* clean up the buf */
881 	buf->b_hdr = NULL;
882 	kmem_cache_free(buf_cache, buf);
883 }
884 
885 static void
886 arc_hdr_destroy(arc_buf_hdr_t *hdr)
887 {
888 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
889 	ASSERT3P(hdr->b_state, ==, arc.anon);
890 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
891 
892 	if (!BUF_EMPTY(hdr)) {
893 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
894 		bzero(&hdr->b_dva, sizeof (dva_t));
895 		hdr->b_birth = 0;
896 		hdr->b_cksum0 = 0;
897 	}
898 	while (hdr->b_buf) {
899 		arc_buf_t *buf = hdr->b_buf;
900 
901 		if (buf->b_efunc) {
902 			mutex_enter(&arc_eviction_mtx);
903 			ASSERT(buf->b_hdr != NULL);
904 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
905 			hdr->b_buf = buf->b_next;
906 			buf->b_hdr = &arc_eviction_hdr;
907 			buf->b_next = arc_eviction_list;
908 			arc_eviction_list = buf;
909 			mutex_exit(&arc_eviction_mtx);
910 		} else {
911 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
912 		}
913 	}
914 	if (hdr->b_freeze_cksum != NULL) {
915 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
916 		hdr->b_freeze_cksum = NULL;
917 	}
918 
919 	ASSERT(!list_link_active(&hdr->b_arc_node));
920 	ASSERT3P(hdr->b_hash_next, ==, NULL);
921 	ASSERT3P(hdr->b_acb, ==, NULL);
922 	kmem_cache_free(hdr_cache, hdr);
923 }
924 
925 void
926 arc_buf_free(arc_buf_t *buf, void *tag)
927 {
928 	arc_buf_hdr_t *hdr = buf->b_hdr;
929 	int hashed = hdr->b_state != arc.anon;
930 
931 	ASSERT(buf->b_efunc == NULL);
932 	ASSERT(buf->b_data != NULL);
933 
934 	if (hashed) {
935 		kmutex_t *hash_lock = HDR_LOCK(hdr);
936 
937 		mutex_enter(hash_lock);
938 		(void) remove_reference(hdr, hash_lock, tag);
939 		if (hdr->b_datacnt > 1)
940 			arc_buf_destroy(buf, FALSE, TRUE);
941 		else
942 			hdr->b_flags |= ARC_BUF_AVAILABLE;
943 		mutex_exit(hash_lock);
944 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
945 		int destroy_hdr;
946 		/*
947 		 * We are in the middle of an async write.  Don't destroy
948 		 * this buffer unless the write completes before we finish
949 		 * decrementing the reference count.
950 		 */
951 		mutex_enter(&arc_eviction_mtx);
952 		(void) remove_reference(hdr, NULL, tag);
953 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
954 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
955 		mutex_exit(&arc_eviction_mtx);
956 		if (destroy_hdr)
957 			arc_hdr_destroy(hdr);
958 	} else {
959 		if (remove_reference(hdr, NULL, tag) > 0) {
960 			ASSERT(HDR_IO_ERROR(hdr));
961 			arc_buf_destroy(buf, FALSE, TRUE);
962 		} else {
963 			arc_hdr_destroy(hdr);
964 		}
965 	}
966 }
967 
968 int
969 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
970 {
971 	arc_buf_hdr_t *hdr = buf->b_hdr;
972 	kmutex_t *hash_lock = HDR_LOCK(hdr);
973 	int no_callback = (buf->b_efunc == NULL);
974 
975 	if (hdr->b_state == arc.anon) {
976 		arc_buf_free(buf, tag);
977 		return (no_callback);
978 	}
979 
980 	mutex_enter(hash_lock);
981 	ASSERT(hdr->b_state != arc.anon);
982 	ASSERT(buf->b_data != NULL);
983 
984 	(void) remove_reference(hdr, hash_lock, tag);
985 	if (hdr->b_datacnt > 1) {
986 		if (no_callback)
987 			arc_buf_destroy(buf, FALSE, TRUE);
988 	} else if (no_callback) {
989 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
990 		hdr->b_flags |= ARC_BUF_AVAILABLE;
991 	}
992 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
993 	    refcount_is_zero(&hdr->b_refcnt));
994 	mutex_exit(hash_lock);
995 	return (no_callback);
996 }
997 
998 int
999 arc_buf_size(arc_buf_t *buf)
1000 {
1001 	return (buf->b_hdr->b_size);
1002 }
1003 
1004 /*
1005  * Evict buffers from list until we've removed the specified number of
1006  * bytes.  Move the removed buffers to the appropriate evict state.
1007  * If the recycle flag is set, then attempt to "recycle" a buffer:
1008  * - look for a buffer to evict that is `bytes' long.
1009  * - return the data block from this buffer rather than freeing it.
1010  * This flag is used by callers that are trying to make space for a
1011  * new buffer in a full arc cache.
1012  */
1013 static void *
1014 arc_evict(arc_state_t *state, int64_t bytes, boolean_t recycle,
1015     arc_buf_contents_t type)
1016 {
1017 	arc_state_t *evicted_state;
1018 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1019 	arc_buf_hdr_t *ab, *ab_prev = NULL;
1020 	kmutex_t *hash_lock;
1021 	boolean_t have_lock;
1022 	void *stolen = NULL;
1023 
1024 	ASSERT(state == arc.mru || state == arc.mfu);
1025 
1026 	evicted_state = (state == arc.mru) ? arc.mru_ghost : arc.mfu_ghost;
1027 
1028 	mutex_enter(&state->mtx);
1029 	mutex_enter(&evicted_state->mtx);
1030 
1031 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
1032 		ab_prev = list_prev(&state->list, ab);
1033 		/* prefetch buffers have a minimum lifespan */
1034 		if (HDR_IO_IN_PROGRESS(ab) ||
1035 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1036 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
1037 			skipped++;
1038 			continue;
1039 		}
1040 		/* "lookahead" for better eviction candidate */
1041 		if (recycle && ab->b_size != bytes &&
1042 		    ab_prev && ab_prev->b_size == bytes)
1043 			continue;
1044 		hash_lock = HDR_LOCK(ab);
1045 		have_lock = MUTEX_HELD(hash_lock);
1046 		if (have_lock || mutex_tryenter(hash_lock)) {
1047 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
1048 			ASSERT(ab->b_datacnt > 0);
1049 			while (ab->b_buf) {
1050 				arc_buf_t *buf = ab->b_buf;
1051 				if (buf->b_data) {
1052 					bytes_evicted += ab->b_size;
1053 					if (recycle && ab->b_type == type &&
1054 					    ab->b_size == bytes) {
1055 						stolen = buf->b_data;
1056 						recycle = FALSE;
1057 					}
1058 				}
1059 				if (buf->b_efunc) {
1060 					mutex_enter(&arc_eviction_mtx);
1061 					arc_buf_destroy(buf,
1062 					    buf->b_data == stolen, FALSE);
1063 					ab->b_buf = buf->b_next;
1064 					buf->b_hdr = &arc_eviction_hdr;
1065 					buf->b_next = arc_eviction_list;
1066 					arc_eviction_list = buf;
1067 					mutex_exit(&arc_eviction_mtx);
1068 				} else {
1069 					arc_buf_destroy(buf,
1070 					    buf->b_data == stolen, TRUE);
1071 				}
1072 			}
1073 			ASSERT(ab->b_datacnt == 0);
1074 			arc_change_state(evicted_state, ab, hash_lock);
1075 			ASSERT(HDR_IN_HASH_TABLE(ab));
1076 			ab->b_flags = ARC_IN_HASH_TABLE;
1077 			DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1078 			if (!have_lock)
1079 				mutex_exit(hash_lock);
1080 			if (bytes >= 0 && bytes_evicted >= bytes)
1081 				break;
1082 		} else {
1083 			missed += 1;
1084 		}
1085 	}
1086 	mutex_exit(&evicted_state->mtx);
1087 	mutex_exit(&state->mtx);
1088 
1089 	if (bytes_evicted < bytes)
1090 		dprintf("only evicted %lld bytes from %x",
1091 		    (longlong_t)bytes_evicted, state);
1092 
1093 	if (skipped)
1094 		atomic_add_64(&arc.evict_skip, skipped);
1095 	if (missed)
1096 		atomic_add_64(&arc.mutex_miss, missed);
1097 	return (stolen);
1098 }
1099 
1100 /*
1101  * Remove buffers from list until we've removed the specified number of
1102  * bytes.  Destroy the buffers that are removed.
1103  */
1104 static void
1105 arc_evict_ghost(arc_state_t *state, int64_t bytes)
1106 {
1107 	arc_buf_hdr_t *ab, *ab_prev;
1108 	kmutex_t *hash_lock;
1109 	uint64_t bytes_deleted = 0;
1110 	uint_t bufs_skipped = 0;
1111 
1112 	ASSERT(GHOST_STATE(state));
1113 top:
1114 	mutex_enter(&state->mtx);
1115 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
1116 		ab_prev = list_prev(&state->list, ab);
1117 		hash_lock = HDR_LOCK(ab);
1118 		if (mutex_tryenter(hash_lock)) {
1119 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
1120 			ASSERT(ab->b_buf == NULL);
1121 			arc_change_state(arc.anon, ab, hash_lock);
1122 			mutex_exit(hash_lock);
1123 			atomic_add_64(&arc.deleted, 1);
1124 			bytes_deleted += ab->b_size;
1125 			arc_hdr_destroy(ab);
1126 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1127 			if (bytes >= 0 && bytes_deleted >= bytes)
1128 				break;
1129 		} else {
1130 			if (bytes < 0) {
1131 				mutex_exit(&state->mtx);
1132 				mutex_enter(hash_lock);
1133 				mutex_exit(hash_lock);
1134 				goto top;
1135 			}
1136 			bufs_skipped += 1;
1137 		}
1138 	}
1139 	mutex_exit(&state->mtx);
1140 
1141 	if (bufs_skipped) {
1142 		atomic_add_64(&arc.mutex_miss, bufs_skipped);
1143 		ASSERT(bytes >= 0);
1144 	}
1145 
1146 	if (bytes_deleted < bytes)
1147 		dprintf("only deleted %lld bytes from %p",
1148 		    (longlong_t)bytes_deleted, state);
1149 }
1150 
1151 static void
1152 arc_adjust(void)
1153 {
1154 	int64_t top_sz, mru_over, arc_over;
1155 
1156 	top_sz = arc.anon->size + arc.mru->size;
1157 
1158 	if (top_sz > arc.p && arc.mru->lsize > 0) {
1159 		int64_t toevict = MIN(arc.mru->lsize, top_sz-arc.p);
1160 		(void) arc_evict(arc.mru, toevict, FALSE, ARC_BUFC_UNDEF);
1161 		top_sz = arc.anon->size + arc.mru->size;
1162 	}
1163 
1164 	mru_over = top_sz + arc.mru_ghost->size - arc.c;
1165 
1166 	if (mru_over > 0) {
1167 		if (arc.mru_ghost->lsize > 0) {
1168 			int64_t todelete = MIN(arc.mru_ghost->lsize, mru_over);
1169 			arc_evict_ghost(arc.mru_ghost, todelete);
1170 		}
1171 	}
1172 
1173 	if ((arc_over = arc.size - arc.c) > 0) {
1174 		int64_t tbl_over;
1175 
1176 		if (arc.mfu->lsize > 0) {
1177 			int64_t toevict = MIN(arc.mfu->lsize, arc_over);
1178 			(void) arc_evict(arc.mfu, toevict, FALSE,
1179 			    ARC_BUFC_UNDEF);
1180 		}
1181 
1182 		tbl_over = arc.size + arc.mru_ghost->lsize +
1183 		    arc.mfu_ghost->lsize - arc.c*2;
1184 
1185 		if (tbl_over > 0 && arc.mfu_ghost->lsize > 0) {
1186 			int64_t todelete = MIN(arc.mfu_ghost->lsize, tbl_over);
1187 			arc_evict_ghost(arc.mfu_ghost, todelete);
1188 		}
1189 	}
1190 }
1191 
1192 static void
1193 arc_do_user_evicts(void)
1194 {
1195 	mutex_enter(&arc_eviction_mtx);
1196 	while (arc_eviction_list != NULL) {
1197 		arc_buf_t *buf = arc_eviction_list;
1198 		arc_eviction_list = buf->b_next;
1199 		buf->b_hdr = NULL;
1200 		mutex_exit(&arc_eviction_mtx);
1201 
1202 		if (buf->b_efunc != NULL)
1203 			VERIFY(buf->b_efunc(buf) == 0);
1204 
1205 		buf->b_efunc = NULL;
1206 		buf->b_private = NULL;
1207 		kmem_cache_free(buf_cache, buf);
1208 		mutex_enter(&arc_eviction_mtx);
1209 	}
1210 	mutex_exit(&arc_eviction_mtx);
1211 }
1212 
1213 /*
1214  * Flush all *evictable* data from the cache.
1215  * NOTE: this will not touch "active" (i.e. referenced) data.
1216  */
1217 void
1218 arc_flush(void)
1219 {
1220 	while (list_head(&arc.mru->list))
1221 		(void) arc_evict(arc.mru, -1, FALSE, ARC_BUFC_UNDEF);
1222 	while (list_head(&arc.mfu->list))
1223 		(void) arc_evict(arc.mfu, -1, FALSE, ARC_BUFC_UNDEF);
1224 
1225 	arc_evict_ghost(arc.mru_ghost, -1);
1226 	arc_evict_ghost(arc.mfu_ghost, -1);
1227 
1228 	mutex_enter(&arc_reclaim_thr_lock);
1229 	arc_do_user_evicts();
1230 	mutex_exit(&arc_reclaim_thr_lock);
1231 	ASSERT(arc_eviction_list == NULL);
1232 }
1233 
1234 int arc_shrink_shift = 5;		/* log2(fraction of arc to reclaim) */
1235 
1236 void
1237 arc_shrink(void)
1238 {
1239 	if (arc.c > arc.c_min) {
1240 		uint64_t to_free;
1241 
1242 #ifdef _KERNEL
1243 		to_free = MAX(arc.c >> arc_shrink_shift, ptob(needfree));
1244 #else
1245 		to_free = arc.c >> arc_shrink_shift;
1246 #endif
1247 		if (arc.c > arc.c_min + to_free)
1248 			atomic_add_64(&arc.c, -to_free);
1249 		else
1250 			arc.c = arc.c_min;
1251 
1252 		atomic_add_64(&arc.p, -(arc.p >> arc_shrink_shift));
1253 		if (arc.c > arc.size)
1254 			arc.c = MAX(arc.size, arc.c_min);
1255 		if (arc.p > arc.c)
1256 			arc.p = (arc.c >> 1);
1257 		ASSERT(arc.c >= arc.c_min);
1258 		ASSERT((int64_t)arc.p >= 0);
1259 	}
1260 
1261 	if (arc.size > arc.c)
1262 		arc_adjust();
1263 }
1264 
1265 static int
1266 arc_reclaim_needed(void)
1267 {
1268 	uint64_t extra;
1269 
1270 #ifdef _KERNEL
1271 
1272 	if (needfree)
1273 		return (1);
1274 
1275 	/*
1276 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1277 	 */
1278 	extra = desfree;
1279 
1280 	/*
1281 	 * check that we're out of range of the pageout scanner.  It starts to
1282 	 * schedule paging if freemem is less than lotsfree and needfree.
1283 	 * lotsfree is the high-water mark for pageout, and needfree is the
1284 	 * number of needed free pages.  We add extra pages here to make sure
1285 	 * the scanner doesn't start up while we're freeing memory.
1286 	 */
1287 	if (freemem < lotsfree + needfree + extra)
1288 		return (1);
1289 
1290 	/*
1291 	 * check to make sure that swapfs has enough space so that anon
1292 	 * reservations can still succeeed. anon_resvmem() checks that the
1293 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1294 	 * swap pages.  We also add a bit of extra here just to prevent
1295 	 * circumstances from getting really dire.
1296 	 */
1297 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1298 		return (1);
1299 
1300 #if defined(__i386)
1301 	/*
1302 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1303 	 * kernel heap space before we ever run out of available physical
1304 	 * memory.  Most checks of the size of the heap_area compare against
1305 	 * tune.t_minarmem, which is the minimum available real memory that we
1306 	 * can have in the system.  However, this is generally fixed at 25 pages
1307 	 * which is so low that it's useless.  In this comparison, we seek to
1308 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
1309 	 * heap is allocated.  (Or, in the caclulation, if less than 1/4th is
1310 	 * free)
1311 	 */
1312 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1313 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1314 		return (1);
1315 #endif
1316 
1317 #else
1318 	if (spa_get_random(100) == 0)
1319 		return (1);
1320 #endif
1321 	return (0);
1322 }
1323 
1324 static void
1325 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1326 {
1327 	size_t			i;
1328 	kmem_cache_t		*prev_cache = NULL;
1329 	kmem_cache_t		*prev_data_cache = NULL;
1330 	extern kmem_cache_t	*zio_buf_cache[];
1331 	extern kmem_cache_t	*zio_data_buf_cache[];
1332 
1333 #ifdef _KERNEL
1334 	/*
1335 	 * First purge some DNLC entries, in case the DNLC is using
1336 	 * up too much memory.
1337 	 */
1338 	dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
1339 
1340 #if defined(__i386)
1341 	/*
1342 	 * Reclaim unused memory from all kmem caches.
1343 	 */
1344 	kmem_reap();
1345 #endif
1346 #endif
1347 
1348 	/*
1349 	 * An agressive reclamation will shrink the cache size as well as
1350 	 * reap free buffers from the arc kmem caches.
1351 	 */
1352 	if (strat == ARC_RECLAIM_AGGR)
1353 		arc_shrink();
1354 
1355 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1356 		if (zio_buf_cache[i] != prev_cache) {
1357 			prev_cache = zio_buf_cache[i];
1358 			kmem_cache_reap_now(zio_buf_cache[i]);
1359 		}
1360 		if (zio_data_buf_cache[i] != prev_data_cache) {
1361 			prev_data_cache = zio_data_buf_cache[i];
1362 			kmem_cache_reap_now(zio_data_buf_cache[i]);
1363 		}
1364 	}
1365 	kmem_cache_reap_now(buf_cache);
1366 	kmem_cache_reap_now(hdr_cache);
1367 }
1368 
1369 static void
1370 arc_reclaim_thread(void)
1371 {
1372 	clock_t			growtime = 0;
1373 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1374 	callb_cpr_t		cpr;
1375 
1376 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1377 
1378 	mutex_enter(&arc_reclaim_thr_lock);
1379 	while (arc_thread_exit == 0) {
1380 		if (arc_reclaim_needed()) {
1381 
1382 			if (arc.no_grow) {
1383 				if (last_reclaim == ARC_RECLAIM_CONS) {
1384 					last_reclaim = ARC_RECLAIM_AGGR;
1385 				} else {
1386 					last_reclaim = ARC_RECLAIM_CONS;
1387 				}
1388 			} else {
1389 				arc.no_grow = TRUE;
1390 				last_reclaim = ARC_RECLAIM_AGGR;
1391 				membar_producer();
1392 			}
1393 
1394 			/* reset the growth delay for every reclaim */
1395 			growtime = lbolt + (arc_grow_retry * hz);
1396 			ASSERT(growtime > 0);
1397 
1398 			arc_kmem_reap_now(last_reclaim);
1399 
1400 		} else if ((growtime > 0) && ((growtime - lbolt) <= 0)) {
1401 			arc.no_grow = FALSE;
1402 		}
1403 
1404 		if (2 * arc.c <
1405 		    arc.size + arc.mru_ghost->size + arc.mfu_ghost->size)
1406 			arc_adjust();
1407 
1408 		if (arc_eviction_list != NULL)
1409 			arc_do_user_evicts();
1410 
1411 		/* block until needed, or one second, whichever is shorter */
1412 		CALLB_CPR_SAFE_BEGIN(&cpr);
1413 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1414 		    &arc_reclaim_thr_lock, (lbolt + hz));
1415 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1416 	}
1417 
1418 	arc_thread_exit = 0;
1419 	cv_broadcast(&arc_reclaim_thr_cv);
1420 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1421 	thread_exit();
1422 }
1423 
1424 /*
1425  * Adapt arc info given the number of bytes we are trying to add and
1426  * the state that we are comming from.  This function is only called
1427  * when we are adding new content to the cache.
1428  */
1429 static void
1430 arc_adapt(int bytes, arc_state_t *state)
1431 {
1432 	int mult;
1433 
1434 	ASSERT(bytes > 0);
1435 	/*
1436 	 * Adapt the target size of the MRU list:
1437 	 *	- if we just hit in the MRU ghost list, then increase
1438 	 *	  the target size of the MRU list.
1439 	 *	- if we just hit in the MFU ghost list, then increase
1440 	 *	  the target size of the MFU list by decreasing the
1441 	 *	  target size of the MRU list.
1442 	 */
1443 	if (state == arc.mru_ghost) {
1444 		mult = ((arc.mru_ghost->size >= arc.mfu_ghost->size) ?
1445 		    1 : (arc.mfu_ghost->size/arc.mru_ghost->size));
1446 
1447 		arc.p = MIN(arc.c, arc.p + bytes * mult);
1448 	} else if (state == arc.mfu_ghost) {
1449 		mult = ((arc.mfu_ghost->size >= arc.mru_ghost->size) ?
1450 		    1 : (arc.mru_ghost->size/arc.mfu_ghost->size));
1451 
1452 		arc.p = MAX(0, (int64_t)arc.p - bytes * mult);
1453 	}
1454 	ASSERT((int64_t)arc.p >= 0);
1455 
1456 	if (arc_reclaim_needed()) {
1457 		cv_signal(&arc_reclaim_thr_cv);
1458 		return;
1459 	}
1460 
1461 	if (arc.no_grow)
1462 		return;
1463 
1464 	if (arc.c >= arc.c_max)
1465 		return;
1466 
1467 	/*
1468 	 * If we're within (2 * maxblocksize) bytes of the target
1469 	 * cache size, increment the target cache size
1470 	 */
1471 	if (arc.size > arc.c - (2ULL << SPA_MAXBLOCKSHIFT)) {
1472 		atomic_add_64(&arc.c, (int64_t)bytes);
1473 		if (arc.c > arc.c_max)
1474 			arc.c = arc.c_max;
1475 		else if (state == arc.anon)
1476 			atomic_add_64(&arc.p, (int64_t)bytes);
1477 		if (arc.p > arc.c)
1478 			arc.p = arc.c;
1479 	}
1480 	ASSERT((int64_t)arc.p >= 0);
1481 }
1482 
1483 /*
1484  * Check if the cache has reached its limits and eviction is required
1485  * prior to insert.
1486  */
1487 static int
1488 arc_evict_needed()
1489 {
1490 	if (arc_reclaim_needed())
1491 		return (1);
1492 
1493 	return (arc.size > arc.c);
1494 }
1495 
1496 /*
1497  * The buffer, supplied as the first argument, needs a data block.
1498  * So, if we are at cache max, determine which cache should be victimized.
1499  * We have the following cases:
1500  *
1501  * 1. Insert for MRU, p > sizeof(arc.anon + arc.mru) ->
1502  * In this situation if we're out of space, but the resident size of the MFU is
1503  * under the limit, victimize the MFU cache to satisfy this insertion request.
1504  *
1505  * 2. Insert for MRU, p <= sizeof(arc.anon + arc.mru) ->
1506  * Here, we've used up all of the available space for the MRU, so we need to
1507  * evict from our own cache instead.  Evict from the set of resident MRU
1508  * entries.
1509  *
1510  * 3. Insert for MFU (c - p) > sizeof(arc.mfu) ->
1511  * c minus p represents the MFU space in the cache, since p is the size of the
1512  * cache that is dedicated to the MRU.  In this situation there's still space on
1513  * the MFU side, so the MRU side needs to be victimized.
1514  *
1515  * 4. Insert for MFU (c - p) < sizeof(arc.mfu) ->
1516  * MFU's resident set is consuming more space than it has been allotted.  In
1517  * this situation, we must victimize our own cache, the MFU, for this insertion.
1518  */
1519 static void
1520 arc_get_data_buf(arc_buf_t *buf)
1521 {
1522 	arc_state_t		*state = buf->b_hdr->b_state;
1523 	uint64_t		size = buf->b_hdr->b_size;
1524 	arc_buf_contents_t	type = buf->b_hdr->b_type;
1525 
1526 	arc_adapt(size, state);
1527 
1528 	/*
1529 	 * We have not yet reached cache maximum size,
1530 	 * just allocate a new buffer.
1531 	 */
1532 	if (!arc_evict_needed()) {
1533 		if (type == ARC_BUFC_METADATA) {
1534 			buf->b_data = zio_buf_alloc(size);
1535 		} else {
1536 			ASSERT(type == ARC_BUFC_DATA);
1537 			buf->b_data = zio_data_buf_alloc(size);
1538 		}
1539 		atomic_add_64(&arc.size, size);
1540 		goto out;
1541 	}
1542 
1543 	/*
1544 	 * If we are prefetching from the mfu ghost list, this buffer
1545 	 * will end up on the mru list; so steal space from there.
1546 	 */
1547 	if (state == arc.mfu_ghost)
1548 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc.mru : arc.mfu;
1549 	else if (state == arc.mru_ghost)
1550 		state = arc.mru;
1551 
1552 	if (state == arc.mru || state == arc.anon) {
1553 		uint64_t mru_used = arc.anon->size + arc.mru->size;
1554 		state = (arc.p > mru_used) ? arc.mfu : arc.mru;
1555 	} else {
1556 		/* MFU cases */
1557 		uint64_t mfu_space = arc.c - arc.p;
1558 		state =  (mfu_space > arc.mfu->size) ? arc.mru : arc.mfu;
1559 	}
1560 	if ((buf->b_data = arc_evict(state, size, TRUE, type)) == NULL) {
1561 		if (type == ARC_BUFC_METADATA) {
1562 			buf->b_data = zio_buf_alloc(size);
1563 		} else {
1564 			ASSERT(type == ARC_BUFC_DATA);
1565 			buf->b_data = zio_data_buf_alloc(size);
1566 		}
1567 		atomic_add_64(&arc.size, size);
1568 		atomic_add_64(&arc.recycle_miss, 1);
1569 	}
1570 	ASSERT(buf->b_data != NULL);
1571 out:
1572 	/*
1573 	 * Update the state size.  Note that ghost states have a
1574 	 * "ghost size" and so don't need to be updated.
1575 	 */
1576 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
1577 		arc_buf_hdr_t *hdr = buf->b_hdr;
1578 
1579 		atomic_add_64(&hdr->b_state->size, size);
1580 		if (list_link_active(&hdr->b_arc_node)) {
1581 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
1582 			atomic_add_64(&hdr->b_state->lsize, size);
1583 		}
1584 		/*
1585 		 * If we are growing the cache, and we are adding anonymous
1586 		 * data, and we have outgrown arc.p, update arc.p
1587 		 */
1588 		if (arc.size < arc.c && hdr->b_state == arc.anon &&
1589 		    arc.anon->size + arc.mru->size > arc.p)
1590 			arc.p = MIN(arc.c, arc.p + size);
1591 	}
1592 }
1593 
1594 /*
1595  * This routine is called whenever a buffer is accessed.
1596  * NOTE: the hash lock is dropped in this function.
1597  */
1598 static void
1599 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
1600 {
1601 	ASSERT(MUTEX_HELD(hash_lock));
1602 
1603 	if (buf->b_state == arc.anon) {
1604 		/*
1605 		 * This buffer is not in the cache, and does not
1606 		 * appear in our "ghost" list.  Add the new buffer
1607 		 * to the MRU state.
1608 		 */
1609 
1610 		ASSERT(buf->b_arc_access == 0);
1611 		buf->b_arc_access = lbolt;
1612 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1613 		arc_change_state(arc.mru, buf, hash_lock);
1614 
1615 	} else if (buf->b_state == arc.mru) {
1616 		/*
1617 		 * If this buffer is here because of a prefetch, then either:
1618 		 * - clear the flag if this is a "referencing" read
1619 		 *   (any subsequent access will bump this into the MFU state).
1620 		 * or
1621 		 * - move the buffer to the head of the list if this is
1622 		 *   another prefetch (to make it less likely to be evicted).
1623 		 */
1624 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1625 			if (refcount_count(&buf->b_refcnt) == 0) {
1626 				ASSERT(list_link_active(&buf->b_arc_node));
1627 				mutex_enter(&arc.mru->mtx);
1628 				list_remove(&arc.mru->list, buf);
1629 				list_insert_head(&arc.mru->list, buf);
1630 				mutex_exit(&arc.mru->mtx);
1631 			} else {
1632 				buf->b_flags &= ~ARC_PREFETCH;
1633 				atomic_add_64(&arc.mru->hits, 1);
1634 			}
1635 			buf->b_arc_access = lbolt;
1636 			return;
1637 		}
1638 
1639 		/*
1640 		 * This buffer has been "accessed" only once so far,
1641 		 * but it is still in the cache. Move it to the MFU
1642 		 * state.
1643 		 */
1644 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
1645 			/*
1646 			 * More than 125ms have passed since we
1647 			 * instantiated this buffer.  Move it to the
1648 			 * most frequently used state.
1649 			 */
1650 			buf->b_arc_access = lbolt;
1651 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1652 			arc_change_state(arc.mfu, buf, hash_lock);
1653 		}
1654 		atomic_add_64(&arc.mru->hits, 1);
1655 	} else if (buf->b_state == arc.mru_ghost) {
1656 		arc_state_t	*new_state;
1657 		/*
1658 		 * This buffer has been "accessed" recently, but
1659 		 * was evicted from the cache.  Move it to the
1660 		 * MFU state.
1661 		 */
1662 
1663 		if (buf->b_flags & ARC_PREFETCH) {
1664 			new_state = arc.mru;
1665 			if (refcount_count(&buf->b_refcnt) > 0)
1666 				buf->b_flags &= ~ARC_PREFETCH;
1667 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1668 		} else {
1669 			new_state = arc.mfu;
1670 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1671 		}
1672 
1673 		buf->b_arc_access = lbolt;
1674 		arc_change_state(new_state, buf, hash_lock);
1675 
1676 		atomic_add_64(&arc.mru_ghost->hits, 1);
1677 	} else if (buf->b_state == arc.mfu) {
1678 		/*
1679 		 * This buffer has been accessed more than once and is
1680 		 * still in the cache.  Keep it in the MFU state.
1681 		 *
1682 		 * NOTE: an add_reference() that occurred when we did
1683 		 * the arc_read() will have kicked this off the list.
1684 		 * If it was a prefetch, we will explicitly move it to
1685 		 * the head of the list now.
1686 		 */
1687 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1688 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
1689 			ASSERT(list_link_active(&buf->b_arc_node));
1690 			mutex_enter(&arc.mfu->mtx);
1691 			list_remove(&arc.mfu->list, buf);
1692 			list_insert_head(&arc.mfu->list, buf);
1693 			mutex_exit(&arc.mfu->mtx);
1694 		}
1695 		atomic_add_64(&arc.mfu->hits, 1);
1696 		buf->b_arc_access = lbolt;
1697 	} else if (buf->b_state == arc.mfu_ghost) {
1698 		arc_state_t	*new_state = arc.mfu;
1699 		/*
1700 		 * This buffer has been accessed more than once but has
1701 		 * been evicted from the cache.  Move it back to the
1702 		 * MFU state.
1703 		 */
1704 
1705 		if (buf->b_flags & ARC_PREFETCH) {
1706 			/*
1707 			 * This is a prefetch access...
1708 			 * move this block back to the MRU state.
1709 			 */
1710 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
1711 			new_state = arc.mru;
1712 		}
1713 
1714 		buf->b_arc_access = lbolt;
1715 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1716 		arc_change_state(new_state, buf, hash_lock);
1717 
1718 		atomic_add_64(&arc.mfu_ghost->hits, 1);
1719 	} else {
1720 		ASSERT(!"invalid arc state");
1721 	}
1722 }
1723 
1724 /* a generic arc_done_func_t which you can use */
1725 /* ARGSUSED */
1726 void
1727 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
1728 {
1729 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
1730 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1731 }
1732 
1733 /* a generic arc_done_func_t which you can use */
1734 void
1735 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
1736 {
1737 	arc_buf_t **bufp = arg;
1738 	if (zio && zio->io_error) {
1739 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1740 		*bufp = NULL;
1741 	} else {
1742 		*bufp = buf;
1743 	}
1744 }
1745 
1746 static void
1747 arc_read_done(zio_t *zio)
1748 {
1749 	arc_buf_hdr_t	*hdr, *found;
1750 	arc_buf_t	*buf;
1751 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
1752 	kmutex_t	*hash_lock;
1753 	arc_callback_t	*callback_list, *acb;
1754 	int		freeable = FALSE;
1755 
1756 	buf = zio->io_private;
1757 	hdr = buf->b_hdr;
1758 
1759 	/*
1760 	 * The hdr was inserted into hash-table and removed from lists
1761 	 * prior to starting I/O.  We should find this header, since
1762 	 * it's in the hash table, and it should be legit since it's
1763 	 * not possible to evict it during the I/O.  The only possible
1764 	 * reason for it not to be found is if we were freed during the
1765 	 * read.
1766 	 */
1767 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
1768 	    &hash_lock);
1769 
1770 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
1771 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))));
1772 
1773 	/* byteswap if necessary */
1774 	callback_list = hdr->b_acb;
1775 	ASSERT(callback_list != NULL);
1776 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && callback_list->acb_byteswap)
1777 		callback_list->acb_byteswap(buf->b_data, hdr->b_size);
1778 
1779 	arc_cksum_compute(buf);
1780 
1781 	/* create copies of the data buffer for the callers */
1782 	abuf = buf;
1783 	for (acb = callback_list; acb; acb = acb->acb_next) {
1784 		if (acb->acb_done) {
1785 			if (abuf == NULL)
1786 				abuf = arc_buf_clone(buf);
1787 			acb->acb_buf = abuf;
1788 			abuf = NULL;
1789 		}
1790 	}
1791 	hdr->b_acb = NULL;
1792 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
1793 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
1794 	if (abuf == buf)
1795 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1796 
1797 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
1798 
1799 	if (zio->io_error != 0) {
1800 		hdr->b_flags |= ARC_IO_ERROR;
1801 		if (hdr->b_state != arc.anon)
1802 			arc_change_state(arc.anon, hdr, hash_lock);
1803 		if (HDR_IN_HASH_TABLE(hdr))
1804 			buf_hash_remove(hdr);
1805 		freeable = refcount_is_zero(&hdr->b_refcnt);
1806 		/* convert checksum errors into IO errors */
1807 		if (zio->io_error == ECKSUM)
1808 			zio->io_error = EIO;
1809 	}
1810 
1811 	/*
1812 	 * Broadcast before we drop the hash_lock to avoid the possibility
1813 	 * that the hdr (and hence the cv) might be freed before we get to
1814 	 * the cv_broadcast().
1815 	 */
1816 	cv_broadcast(&hdr->b_cv);
1817 
1818 	if (hash_lock) {
1819 		/*
1820 		 * Only call arc_access on anonymous buffers.  This is because
1821 		 * if we've issued an I/O for an evicted buffer, we've already
1822 		 * called arc_access (to prevent any simultaneous readers from
1823 		 * getting confused).
1824 		 */
1825 		if (zio->io_error == 0 && hdr->b_state == arc.anon)
1826 			arc_access(hdr, hash_lock);
1827 		mutex_exit(hash_lock);
1828 	} else {
1829 		/*
1830 		 * This block was freed while we waited for the read to
1831 		 * complete.  It has been removed from the hash table and
1832 		 * moved to the anonymous state (so that it won't show up
1833 		 * in the cache).
1834 		 */
1835 		ASSERT3P(hdr->b_state, ==, arc.anon);
1836 		freeable = refcount_is_zero(&hdr->b_refcnt);
1837 	}
1838 
1839 	/* execute each callback and free its structure */
1840 	while ((acb = callback_list) != NULL) {
1841 		if (acb->acb_done)
1842 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
1843 
1844 		if (acb->acb_zio_dummy != NULL) {
1845 			acb->acb_zio_dummy->io_error = zio->io_error;
1846 			zio_nowait(acb->acb_zio_dummy);
1847 		}
1848 
1849 		callback_list = acb->acb_next;
1850 		kmem_free(acb, sizeof (arc_callback_t));
1851 	}
1852 
1853 	if (freeable)
1854 		arc_hdr_destroy(hdr);
1855 }
1856 
1857 /*
1858  * "Read" the block block at the specified DVA (in bp) via the
1859  * cache.  If the block is found in the cache, invoke the provided
1860  * callback immediately and return.  Note that the `zio' parameter
1861  * in the callback will be NULL in this case, since no IO was
1862  * required.  If the block is not in the cache pass the read request
1863  * on to the spa with a substitute callback function, so that the
1864  * requested block will be added to the cache.
1865  *
1866  * If a read request arrives for a block that has a read in-progress,
1867  * either wait for the in-progress read to complete (and return the
1868  * results); or, if this is a read with a "done" func, add a record
1869  * to the read to invoke the "done" func when the read completes,
1870  * and return; or just return.
1871  *
1872  * arc_read_done() will invoke all the requested "done" functions
1873  * for readers of this block.
1874  */
1875 int
1876 arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_byteswap_func_t *swap,
1877     arc_done_func_t *done, void *private, int priority, int flags,
1878     uint32_t *arc_flags, zbookmark_t *zb)
1879 {
1880 	arc_buf_hdr_t *hdr;
1881 	arc_buf_t *buf;
1882 	kmutex_t *hash_lock;
1883 	zio_t	*rzio;
1884 
1885 top:
1886 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
1887 	if (hdr && hdr->b_datacnt > 0) {
1888 
1889 		*arc_flags |= ARC_CACHED;
1890 
1891 		if (HDR_IO_IN_PROGRESS(hdr)) {
1892 
1893 			if (*arc_flags & ARC_WAIT) {
1894 				cv_wait(&hdr->b_cv, hash_lock);
1895 				mutex_exit(hash_lock);
1896 				goto top;
1897 			}
1898 			ASSERT(*arc_flags & ARC_NOWAIT);
1899 
1900 			if (done) {
1901 				arc_callback_t	*acb = NULL;
1902 
1903 				acb = kmem_zalloc(sizeof (arc_callback_t),
1904 				    KM_SLEEP);
1905 				acb->acb_done = done;
1906 				acb->acb_private = private;
1907 				acb->acb_byteswap = swap;
1908 				if (pio != NULL)
1909 					acb->acb_zio_dummy = zio_null(pio,
1910 					    spa, NULL, NULL, flags);
1911 
1912 				ASSERT(acb->acb_done != NULL);
1913 				acb->acb_next = hdr->b_acb;
1914 				hdr->b_acb = acb;
1915 				add_reference(hdr, hash_lock, private);
1916 				mutex_exit(hash_lock);
1917 				return (0);
1918 			}
1919 			mutex_exit(hash_lock);
1920 			return (0);
1921 		}
1922 
1923 		ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
1924 
1925 		if (done) {
1926 			add_reference(hdr, hash_lock, private);
1927 			/*
1928 			 * If this block is already in use, create a new
1929 			 * copy of the data so that we will be guaranteed
1930 			 * that arc_release() will always succeed.
1931 			 */
1932 			buf = hdr->b_buf;
1933 			ASSERT(buf);
1934 			ASSERT(buf->b_data);
1935 			if (HDR_BUF_AVAILABLE(hdr)) {
1936 				ASSERT(buf->b_efunc == NULL);
1937 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
1938 			} else {
1939 				buf = arc_buf_clone(buf);
1940 			}
1941 		} else if (*arc_flags & ARC_PREFETCH &&
1942 		    refcount_count(&hdr->b_refcnt) == 0) {
1943 			hdr->b_flags |= ARC_PREFETCH;
1944 		}
1945 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1946 		arc_access(hdr, hash_lock);
1947 		mutex_exit(hash_lock);
1948 		atomic_add_64(&arc.hits, 1);
1949 		if (done)
1950 			done(NULL, buf, private);
1951 	} else {
1952 		uint64_t size = BP_GET_LSIZE(bp);
1953 		arc_callback_t	*acb;
1954 
1955 		if (hdr == NULL) {
1956 			/* this block is not in the cache */
1957 			arc_buf_hdr_t	*exists;
1958 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
1959 			buf = arc_buf_alloc(spa, size, private, type);
1960 			hdr = buf->b_hdr;
1961 			hdr->b_dva = *BP_IDENTITY(bp);
1962 			hdr->b_birth = bp->blk_birth;
1963 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
1964 			exists = buf_hash_insert(hdr, &hash_lock);
1965 			if (exists) {
1966 				/* somebody beat us to the hash insert */
1967 				mutex_exit(hash_lock);
1968 				bzero(&hdr->b_dva, sizeof (dva_t));
1969 				hdr->b_birth = 0;
1970 				hdr->b_cksum0 = 0;
1971 				(void) arc_buf_remove_ref(buf, private);
1972 				goto top; /* restart the IO request */
1973 			}
1974 			/* if this is a prefetch, we don't have a reference */
1975 			if (*arc_flags & ARC_PREFETCH) {
1976 				(void) remove_reference(hdr, hash_lock,
1977 				    private);
1978 				hdr->b_flags |= ARC_PREFETCH;
1979 			}
1980 			if (BP_GET_LEVEL(bp) > 0)
1981 				hdr->b_flags |= ARC_INDIRECT;
1982 		} else {
1983 			/* this block is in the ghost cache */
1984 			ASSERT(GHOST_STATE(hdr->b_state));
1985 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1986 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
1987 			ASSERT(hdr->b_buf == NULL);
1988 
1989 			/* if this is a prefetch, we don't have a reference */
1990 			if (*arc_flags & ARC_PREFETCH)
1991 				hdr->b_flags |= ARC_PREFETCH;
1992 			else
1993 				add_reference(hdr, hash_lock, private);
1994 			buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
1995 			buf->b_hdr = hdr;
1996 			buf->b_data = NULL;
1997 			buf->b_efunc = NULL;
1998 			buf->b_private = NULL;
1999 			buf->b_next = NULL;
2000 			hdr->b_buf = buf;
2001 			arc_get_data_buf(buf);
2002 			ASSERT(hdr->b_datacnt == 0);
2003 			hdr->b_datacnt = 1;
2004 
2005 		}
2006 
2007 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2008 		acb->acb_done = done;
2009 		acb->acb_private = private;
2010 		acb->acb_byteswap = swap;
2011 
2012 		ASSERT(hdr->b_acb == NULL);
2013 		hdr->b_acb = acb;
2014 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2015 
2016 		/*
2017 		 * If the buffer has been evicted, migrate it to a present state
2018 		 * before issuing the I/O.  Once we drop the hash-table lock,
2019 		 * the header will be marked as I/O in progress and have an
2020 		 * attached buffer.  At this point, anybody who finds this
2021 		 * buffer ought to notice that it's legit but has a pending I/O.
2022 		 */
2023 
2024 		if (GHOST_STATE(hdr->b_state))
2025 			arc_access(hdr, hash_lock);
2026 		mutex_exit(hash_lock);
2027 
2028 		ASSERT3U(hdr->b_size, ==, size);
2029 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
2030 		    zbookmark_t *, zb);
2031 		atomic_add_64(&arc.misses, 1);
2032 
2033 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
2034 		    arc_read_done, buf, priority, flags, zb);
2035 
2036 		if (*arc_flags & ARC_WAIT)
2037 			return (zio_wait(rzio));
2038 
2039 		ASSERT(*arc_flags & ARC_NOWAIT);
2040 		zio_nowait(rzio);
2041 	}
2042 	return (0);
2043 }
2044 
2045 /*
2046  * arc_read() variant to support pool traversal.  If the block is already
2047  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2048  * The idea is that we don't want pool traversal filling up memory, but
2049  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2050  */
2051 int
2052 arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2053 {
2054 	arc_buf_hdr_t *hdr;
2055 	kmutex_t *hash_mtx;
2056 	int rc = 0;
2057 
2058 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2059 
2060 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
2061 		arc_buf_t *buf = hdr->b_buf;
2062 
2063 		ASSERT(buf);
2064 		while (buf->b_data == NULL) {
2065 			buf = buf->b_next;
2066 			ASSERT(buf);
2067 		}
2068 		bcopy(buf->b_data, data, hdr->b_size);
2069 	} else {
2070 		rc = ENOENT;
2071 	}
2072 
2073 	if (hash_mtx)
2074 		mutex_exit(hash_mtx);
2075 
2076 	return (rc);
2077 }
2078 
2079 void
2080 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
2081 {
2082 	ASSERT(buf->b_hdr != NULL);
2083 	ASSERT(buf->b_hdr->b_state != arc.anon);
2084 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
2085 	buf->b_efunc = func;
2086 	buf->b_private = private;
2087 }
2088 
2089 /*
2090  * This is used by the DMU to let the ARC know that a buffer is
2091  * being evicted, so the ARC should clean up.  If this arc buf
2092  * is not yet in the evicted state, it will be put there.
2093  */
2094 int
2095 arc_buf_evict(arc_buf_t *buf)
2096 {
2097 	arc_buf_hdr_t *hdr;
2098 	kmutex_t *hash_lock;
2099 	arc_buf_t **bufp;
2100 
2101 	mutex_enter(&arc_eviction_mtx);
2102 	hdr = buf->b_hdr;
2103 	if (hdr == NULL) {
2104 		/*
2105 		 * We are in arc_do_user_evicts().
2106 		 */
2107 		ASSERT(buf->b_data == NULL);
2108 		mutex_exit(&arc_eviction_mtx);
2109 		return (0);
2110 	}
2111 	hash_lock = HDR_LOCK(hdr);
2112 	mutex_exit(&arc_eviction_mtx);
2113 
2114 	mutex_enter(hash_lock);
2115 
2116 	if (buf->b_data == NULL) {
2117 		/*
2118 		 * We are on the eviction list.
2119 		 */
2120 		mutex_exit(hash_lock);
2121 		mutex_enter(&arc_eviction_mtx);
2122 		if (buf->b_hdr == NULL) {
2123 			/*
2124 			 * We are already in arc_do_user_evicts().
2125 			 */
2126 			mutex_exit(&arc_eviction_mtx);
2127 			return (0);
2128 		} else {
2129 			arc_buf_t copy = *buf; /* structure assignment */
2130 			/*
2131 			 * Process this buffer now
2132 			 * but let arc_do_user_evicts() do the reaping.
2133 			 */
2134 			buf->b_efunc = NULL;
2135 			mutex_exit(&arc_eviction_mtx);
2136 			VERIFY(copy.b_efunc(&copy) == 0);
2137 			return (1);
2138 		}
2139 	}
2140 
2141 	ASSERT(buf->b_hdr == hdr);
2142 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
2143 	ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
2144 
2145 	/*
2146 	 * Pull this buffer off of the hdr
2147 	 */
2148 	bufp = &hdr->b_buf;
2149 	while (*bufp != buf)
2150 		bufp = &(*bufp)->b_next;
2151 	*bufp = buf->b_next;
2152 
2153 	ASSERT(buf->b_data != NULL);
2154 	arc_buf_destroy(buf, FALSE, FALSE);
2155 
2156 	if (hdr->b_datacnt == 0) {
2157 		arc_state_t *old_state = hdr->b_state;
2158 		arc_state_t *evicted_state;
2159 
2160 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
2161 
2162 		evicted_state =
2163 		    (old_state == arc.mru) ? arc.mru_ghost : arc.mfu_ghost;
2164 
2165 		mutex_enter(&old_state->mtx);
2166 		mutex_enter(&evicted_state->mtx);
2167 
2168 		arc_change_state(evicted_state, hdr, hash_lock);
2169 		ASSERT(HDR_IN_HASH_TABLE(hdr));
2170 		hdr->b_flags = ARC_IN_HASH_TABLE;
2171 
2172 		mutex_exit(&evicted_state->mtx);
2173 		mutex_exit(&old_state->mtx);
2174 	}
2175 	mutex_exit(hash_lock);
2176 
2177 	VERIFY(buf->b_efunc(buf) == 0);
2178 	buf->b_efunc = NULL;
2179 	buf->b_private = NULL;
2180 	buf->b_hdr = NULL;
2181 	kmem_cache_free(buf_cache, buf);
2182 	return (1);
2183 }
2184 
2185 /*
2186  * Release this buffer from the cache.  This must be done
2187  * after a read and prior to modifying the buffer contents.
2188  * If the buffer has more than one reference, we must make
2189  * make a new hdr for the buffer.
2190  */
2191 void
2192 arc_release(arc_buf_t *buf, void *tag)
2193 {
2194 	arc_buf_hdr_t *hdr = buf->b_hdr;
2195 	kmutex_t *hash_lock = HDR_LOCK(hdr);
2196 
2197 	/* this buffer is not on any list */
2198 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2199 
2200 	if (hdr->b_state == arc.anon) {
2201 		/* this buffer is already released */
2202 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2203 		ASSERT(BUF_EMPTY(hdr));
2204 		ASSERT(buf->b_efunc == NULL);
2205 		arc_buf_thaw(buf);
2206 		return;
2207 	}
2208 
2209 	mutex_enter(hash_lock);
2210 
2211 	/*
2212 	 * Do we have more than one buf?
2213 	 */
2214 	if (hdr->b_buf != buf || buf->b_next != NULL) {
2215 		arc_buf_hdr_t *nhdr;
2216 		arc_buf_t **bufp;
2217 		uint64_t blksz = hdr->b_size;
2218 		spa_t *spa = hdr->b_spa;
2219 		arc_buf_contents_t type = hdr->b_type;
2220 
2221 		ASSERT(hdr->b_datacnt > 1);
2222 		/*
2223 		 * Pull the data off of this buf and attach it to
2224 		 * a new anonymous buf.
2225 		 */
2226 		(void) remove_reference(hdr, hash_lock, tag);
2227 		bufp = &hdr->b_buf;
2228 		while (*bufp != buf)
2229 			bufp = &(*bufp)->b_next;
2230 		*bufp = (*bufp)->b_next;
2231 
2232 		ASSERT3U(hdr->b_state->size, >=, hdr->b_size);
2233 		atomic_add_64(&hdr->b_state->size, -hdr->b_size);
2234 		if (refcount_is_zero(&hdr->b_refcnt)) {
2235 			ASSERT3U(hdr->b_state->lsize, >=, hdr->b_size);
2236 			atomic_add_64(&hdr->b_state->lsize, -hdr->b_size);
2237 		}
2238 		hdr->b_datacnt -= 1;
2239 
2240 		mutex_exit(hash_lock);
2241 
2242 		nhdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
2243 		nhdr->b_size = blksz;
2244 		nhdr->b_spa = spa;
2245 		nhdr->b_type = type;
2246 		nhdr->b_buf = buf;
2247 		nhdr->b_state = arc.anon;
2248 		nhdr->b_arc_access = 0;
2249 		nhdr->b_flags = 0;
2250 		nhdr->b_datacnt = 1;
2251 		nhdr->b_freeze_cksum =
2252 		    kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
2253 		*nhdr->b_freeze_cksum = *hdr->b_freeze_cksum; /* struct copy */
2254 		buf->b_hdr = nhdr;
2255 		buf->b_next = NULL;
2256 		(void) refcount_add(&nhdr->b_refcnt, tag);
2257 		atomic_add_64(&arc.anon->size, blksz);
2258 
2259 		hdr = nhdr;
2260 	} else {
2261 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
2262 		ASSERT(!list_link_active(&hdr->b_arc_node));
2263 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2264 		arc_change_state(arc.anon, hdr, hash_lock);
2265 		hdr->b_arc_access = 0;
2266 		mutex_exit(hash_lock);
2267 		bzero(&hdr->b_dva, sizeof (dva_t));
2268 		hdr->b_birth = 0;
2269 		hdr->b_cksum0 = 0;
2270 	}
2271 	buf->b_efunc = NULL;
2272 	buf->b_private = NULL;
2273 	arc_buf_thaw(buf);
2274 }
2275 
2276 int
2277 arc_released(arc_buf_t *buf)
2278 {
2279 	return (buf->b_data != NULL && buf->b_hdr->b_state == arc.anon);
2280 }
2281 
2282 int
2283 arc_has_callback(arc_buf_t *buf)
2284 {
2285 	return (buf->b_efunc != NULL);
2286 }
2287 
2288 #ifdef ZFS_DEBUG
2289 int
2290 arc_referenced(arc_buf_t *buf)
2291 {
2292 	return (refcount_count(&buf->b_hdr->b_refcnt));
2293 }
2294 #endif
2295 
2296 static void
2297 arc_write_done(zio_t *zio)
2298 {
2299 	arc_buf_t *buf;
2300 	arc_buf_hdr_t *hdr;
2301 	arc_callback_t *acb;
2302 
2303 	buf = zio->io_private;
2304 	hdr = buf->b_hdr;
2305 	acb = hdr->b_acb;
2306 	hdr->b_acb = NULL;
2307 	ASSERT(acb != NULL);
2308 
2309 	/* this buffer is on no lists and is not in the hash table */
2310 	ASSERT3P(hdr->b_state, ==, arc.anon);
2311 
2312 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
2313 	hdr->b_birth = zio->io_bp->blk_birth;
2314 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
2315 	/*
2316 	 * If the block to be written was all-zero, we may have
2317 	 * compressed it away.  In this case no write was performed
2318 	 * so there will be no dva/birth-date/checksum.  The buffer
2319 	 * must therefor remain anonymous (and uncached).
2320 	 */
2321 	if (!BUF_EMPTY(hdr)) {
2322 		arc_buf_hdr_t *exists;
2323 		kmutex_t *hash_lock;
2324 
2325 		arc_cksum_verify(buf);
2326 
2327 		exists = buf_hash_insert(hdr, &hash_lock);
2328 		if (exists) {
2329 			/*
2330 			 * This can only happen if we overwrite for
2331 			 * sync-to-convergence, because we remove
2332 			 * buffers from the hash table when we arc_free().
2333 			 */
2334 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
2335 			    BP_IDENTITY(zio->io_bp)));
2336 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
2337 			    zio->io_bp->blk_birth);
2338 
2339 			ASSERT(refcount_is_zero(&exists->b_refcnt));
2340 			arc_change_state(arc.anon, exists, hash_lock);
2341 			mutex_exit(hash_lock);
2342 			arc_hdr_destroy(exists);
2343 			exists = buf_hash_insert(hdr, &hash_lock);
2344 			ASSERT3P(exists, ==, NULL);
2345 		}
2346 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2347 		arc_access(hdr, hash_lock);
2348 		mutex_exit(hash_lock);
2349 	} else if (acb->acb_done == NULL) {
2350 		int destroy_hdr;
2351 		/*
2352 		 * This is an anonymous buffer with no user callback,
2353 		 * destroy it if there are no active references.
2354 		 */
2355 		mutex_enter(&arc_eviction_mtx);
2356 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
2357 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2358 		mutex_exit(&arc_eviction_mtx);
2359 		if (destroy_hdr)
2360 			arc_hdr_destroy(hdr);
2361 	} else {
2362 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2363 	}
2364 
2365 	if (acb->acb_done) {
2366 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
2367 		acb->acb_done(zio, buf, acb->acb_private);
2368 	}
2369 
2370 	kmem_free(acb, sizeof (arc_callback_t));
2371 }
2372 
2373 int
2374 arc_write(zio_t *pio, spa_t *spa, int checksum, int compress, int ncopies,
2375     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
2376     arc_done_func_t *done, void *private, int priority, int flags,
2377     uint32_t arc_flags, zbookmark_t *zb)
2378 {
2379 	arc_buf_hdr_t *hdr = buf->b_hdr;
2380 	arc_callback_t	*acb;
2381 	zio_t	*rzio;
2382 
2383 	/* this is a private buffer - no locking required */
2384 	ASSERT3P(hdr->b_state, ==, arc.anon);
2385 	ASSERT(BUF_EMPTY(hdr));
2386 	ASSERT(!HDR_IO_ERROR(hdr));
2387 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
2388 	ASSERT(hdr->b_acb == 0);
2389 	acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2390 	acb->acb_done = done;
2391 	acb->acb_private = private;
2392 	acb->acb_byteswap = (arc_byteswap_func_t *)-1;
2393 	hdr->b_acb = acb;
2394 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
2395 	arc_cksum_compute(buf);
2396 	rzio = zio_write(pio, spa, checksum, compress, ncopies, txg, bp,
2397 	    buf->b_data, hdr->b_size, arc_write_done, buf, priority, flags, zb);
2398 
2399 	if (arc_flags & ARC_WAIT)
2400 		return (zio_wait(rzio));
2401 
2402 	ASSERT(arc_flags & ARC_NOWAIT);
2403 	zio_nowait(rzio);
2404 
2405 	return (0);
2406 }
2407 
2408 int
2409 arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
2410     zio_done_func_t *done, void *private, uint32_t arc_flags)
2411 {
2412 	arc_buf_hdr_t *ab;
2413 	kmutex_t *hash_lock;
2414 	zio_t	*zio;
2415 
2416 	/*
2417 	 * If this buffer is in the cache, release it, so it
2418 	 * can be re-used.
2419 	 */
2420 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
2421 	if (ab != NULL) {
2422 		/*
2423 		 * The checksum of blocks to free is not always
2424 		 * preserved (eg. on the deadlist).  However, if it is
2425 		 * nonzero, it should match what we have in the cache.
2426 		 */
2427 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
2428 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
2429 		if (ab->b_state != arc.anon)
2430 			arc_change_state(arc.anon, ab, hash_lock);
2431 		if (HDR_IO_IN_PROGRESS(ab)) {
2432 			/*
2433 			 * This should only happen when we prefetch.
2434 			 */
2435 			ASSERT(ab->b_flags & ARC_PREFETCH);
2436 			ASSERT3U(ab->b_datacnt, ==, 1);
2437 			ab->b_flags |= ARC_FREED_IN_READ;
2438 			if (HDR_IN_HASH_TABLE(ab))
2439 				buf_hash_remove(ab);
2440 			ab->b_arc_access = 0;
2441 			bzero(&ab->b_dva, sizeof (dva_t));
2442 			ab->b_birth = 0;
2443 			ab->b_cksum0 = 0;
2444 			ab->b_buf->b_efunc = NULL;
2445 			ab->b_buf->b_private = NULL;
2446 			mutex_exit(hash_lock);
2447 		} else if (refcount_is_zero(&ab->b_refcnt)) {
2448 			mutex_exit(hash_lock);
2449 			arc_hdr_destroy(ab);
2450 			atomic_add_64(&arc.deleted, 1);
2451 		} else {
2452 			/*
2453 			 * We still have an active reference on this
2454 			 * buffer.  This can happen, e.g., from
2455 			 * dbuf_unoverride().
2456 			 */
2457 			ASSERT(!HDR_IN_HASH_TABLE(ab));
2458 			ab->b_arc_access = 0;
2459 			bzero(&ab->b_dva, sizeof (dva_t));
2460 			ab->b_birth = 0;
2461 			ab->b_cksum0 = 0;
2462 			ab->b_buf->b_efunc = NULL;
2463 			ab->b_buf->b_private = NULL;
2464 			mutex_exit(hash_lock);
2465 		}
2466 	}
2467 
2468 	zio = zio_free(pio, spa, txg, bp, done, private);
2469 
2470 	if (arc_flags & ARC_WAIT)
2471 		return (zio_wait(zio));
2472 
2473 	ASSERT(arc_flags & ARC_NOWAIT);
2474 	zio_nowait(zio);
2475 
2476 	return (0);
2477 }
2478 
2479 void
2480 arc_tempreserve_clear(uint64_t tempreserve)
2481 {
2482 	atomic_add_64(&arc_tempreserve, -tempreserve);
2483 	ASSERT((int64_t)arc_tempreserve >= 0);
2484 }
2485 
2486 int
2487 arc_tempreserve_space(uint64_t tempreserve)
2488 {
2489 #ifdef ZFS_DEBUG
2490 	/*
2491 	 * Once in a while, fail for no reason.  Everything should cope.
2492 	 */
2493 	if (spa_get_random(10000) == 0) {
2494 		dprintf("forcing random failure\n");
2495 		return (ERESTART);
2496 	}
2497 #endif
2498 	if (tempreserve > arc.c/4 && !arc.no_grow)
2499 		arc.c = MIN(arc.c_max, tempreserve * 4);
2500 	if (tempreserve > arc.c)
2501 		return (ENOMEM);
2502 
2503 	/*
2504 	 * Throttle writes when the amount of dirty data in the cache
2505 	 * gets too large.  We try to keep the cache less than half full
2506 	 * of dirty blocks so that our sync times don't grow too large.
2507 	 * Note: if two requests come in concurrently, we might let them
2508 	 * both succeed, when one of them should fail.  Not a huge deal.
2509 	 *
2510 	 * XXX The limit should be adjusted dynamically to keep the time
2511 	 * to sync a dataset fixed (around 1-5 seconds?).
2512 	 */
2513 
2514 	if (tempreserve + arc_tempreserve + arc.anon->size > arc.c / 2 &&
2515 	    arc_tempreserve + arc.anon->size > arc.c / 4) {
2516 		dprintf("failing, arc_tempreserve=%lluK anon=%lluK "
2517 		    "tempreserve=%lluK arc.c=%lluK\n",
2518 		    arc_tempreserve>>10, arc.anon->lsize>>10,
2519 		    tempreserve>>10, arc.c>>10);
2520 		return (ERESTART);
2521 	}
2522 	atomic_add_64(&arc_tempreserve, tempreserve);
2523 	return (0);
2524 }
2525 
2526 void
2527 arc_init(void)
2528 {
2529 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
2530 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
2531 
2532 	/* Convert seconds to clock ticks */
2533 	arc_min_prefetch_lifespan = 1 * hz;
2534 
2535 	/* Start out with 1/8 of all memory */
2536 	arc.c = physmem * PAGESIZE / 8;
2537 
2538 #ifdef _KERNEL
2539 	/*
2540 	 * On architectures where the physical memory can be larger
2541 	 * than the addressable space (intel in 32-bit mode), we may
2542 	 * need to limit the cache to 1/8 of VM size.
2543 	 */
2544 	arc.c = MIN(arc.c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
2545 #endif
2546 
2547 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
2548 	arc.c_min = MAX(arc.c / 4, 64<<20);
2549 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
2550 	if (arc.c * 8 >= 1<<30)
2551 		arc.c_max = (arc.c * 8) - (1<<30);
2552 	else
2553 		arc.c_max = arc.c_min;
2554 	arc.c_max = MAX(arc.c * 6, arc.c_max);
2555 
2556 	/*
2557 	 * Allow the tunables to override our calculations if they are
2558 	 * reasonable (ie. over 64MB)
2559 	 */
2560 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
2561 		arc.c_max = zfs_arc_max;
2562 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc.c_max)
2563 		arc.c_min = zfs_arc_min;
2564 
2565 	arc.c = arc.c_max;
2566 	arc.p = (arc.c >> 1);
2567 
2568 	/* if kmem_flags are set, lets try to use less memory */
2569 	if (kmem_debugging())
2570 		arc.c = arc.c / 2;
2571 	if (arc.c < arc.c_min)
2572 		arc.c = arc.c_min;
2573 
2574 	arc.anon = &ARC_anon;
2575 	arc.mru = &ARC_mru;
2576 	arc.mru_ghost = &ARC_mru_ghost;
2577 	arc.mfu = &ARC_mfu;
2578 	arc.mfu_ghost = &ARC_mfu_ghost;
2579 	arc.size = 0;
2580 
2581 	arc.hits = 0;
2582 	arc.recycle_miss = 0;
2583 	arc.evict_skip = 0;
2584 	arc.mutex_miss = 0;
2585 
2586 	mutex_init(&arc.anon->mtx, NULL, MUTEX_DEFAULT, NULL);
2587 	mutex_init(&arc.mru->mtx, NULL, MUTEX_DEFAULT, NULL);
2588 	mutex_init(&arc.mru_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2589 	mutex_init(&arc.mfu->mtx, NULL, MUTEX_DEFAULT, NULL);
2590 	mutex_init(&arc.mfu_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2591 
2592 	list_create(&arc.mru->list, sizeof (arc_buf_hdr_t),
2593 	    offsetof(arc_buf_hdr_t, b_arc_node));
2594 	list_create(&arc.mru_ghost->list, sizeof (arc_buf_hdr_t),
2595 	    offsetof(arc_buf_hdr_t, b_arc_node));
2596 	list_create(&arc.mfu->list, sizeof (arc_buf_hdr_t),
2597 	    offsetof(arc_buf_hdr_t, b_arc_node));
2598 	list_create(&arc.mfu_ghost->list, sizeof (arc_buf_hdr_t),
2599 	    offsetof(arc_buf_hdr_t, b_arc_node));
2600 
2601 	buf_init();
2602 
2603 	arc_thread_exit = 0;
2604 	arc_eviction_list = NULL;
2605 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
2606 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
2607 
2608 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
2609 	    TS_RUN, minclsyspri);
2610 
2611 	arc_dead = FALSE;
2612 }
2613 
2614 void
2615 arc_fini(void)
2616 {
2617 	mutex_enter(&arc_reclaim_thr_lock);
2618 	arc_thread_exit = 1;
2619 	while (arc_thread_exit != 0)
2620 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
2621 	mutex_exit(&arc_reclaim_thr_lock);
2622 
2623 	arc_flush();
2624 
2625 	arc_dead = TRUE;
2626 
2627 	mutex_destroy(&arc_eviction_mtx);
2628 	mutex_destroy(&arc_reclaim_thr_lock);
2629 	cv_destroy(&arc_reclaim_thr_cv);
2630 
2631 	list_destroy(&arc.mru->list);
2632 	list_destroy(&arc.mru_ghost->list);
2633 	list_destroy(&arc.mfu->list);
2634 	list_destroy(&arc.mfu_ghost->list);
2635 
2636 	mutex_destroy(&arc.anon->mtx);
2637 	mutex_destroy(&arc.mru->mtx);
2638 	mutex_destroy(&arc.mru_ghost->mtx);
2639 	mutex_destroy(&arc.mfu->mtx);
2640 	mutex_destroy(&arc.mfu_ghost->mtx);
2641 
2642 	buf_fini();
2643 }
2644