xref: /titanic_51/usr/src/uts/common/fs/zfs/arc.c (revision 3266dff7c77b314b33c74fa8767437ffad5f4a01)
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 	/*
1301 	 * If zio data pages are being allocated out of a separate heap segment,
1302 	 * then check that the size of available vmem for this area remains
1303 	 * above 1/4th free.  This needs to be done since the size of the
1304 	 * non-default segment is smaller than physical memory, so we could
1305 	 * conceivably run out of VA in that segment before running out of
1306 	 * physical memory.
1307 	 */
1308 	if ((zio_arena != NULL) && (btop(vmem_size(zio_arena, VMEM_FREE)) <
1309 	    (btop(vmem_size(zio_arena, VMEM_FREE | VMEM_ALLOC)) >> 2)))
1310 		return (1);
1311 
1312 #if defined(__i386)
1313 	/*
1314 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1315 	 * kernel heap space before we ever run out of available physical
1316 	 * memory.  Most checks of the size of the heap_area compare against
1317 	 * tune.t_minarmem, which is the minimum available real memory that we
1318 	 * can have in the system.  However, this is generally fixed at 25 pages
1319 	 * which is so low that it's useless.  In this comparison, we seek to
1320 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
1321 	 * heap is allocated.  (Or, in the caclulation, if less than 1/4th is
1322 	 * free)
1323 	 */
1324 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1325 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1326 		return (1);
1327 #endif
1328 
1329 #else
1330 	if (spa_get_random(100) == 0)
1331 		return (1);
1332 #endif
1333 	return (0);
1334 }
1335 
1336 static void
1337 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1338 {
1339 	size_t			i;
1340 	kmem_cache_t		*prev_cache = NULL;
1341 	kmem_cache_t		*prev_data_cache = NULL;
1342 	extern kmem_cache_t	*zio_buf_cache[];
1343 	extern kmem_cache_t	*zio_data_buf_cache[];
1344 
1345 #ifdef _KERNEL
1346 	/*
1347 	 * First purge some DNLC entries, in case the DNLC is using
1348 	 * up too much memory.
1349 	 */
1350 	dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
1351 
1352 #if defined(__i386)
1353 	/*
1354 	 * Reclaim unused memory from all kmem caches.
1355 	 */
1356 	kmem_reap();
1357 #endif
1358 #endif
1359 
1360 	/*
1361 	 * An agressive reclamation will shrink the cache size as well as
1362 	 * reap free buffers from the arc kmem caches.
1363 	 */
1364 	if (strat == ARC_RECLAIM_AGGR)
1365 		arc_shrink();
1366 
1367 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1368 		if (zio_buf_cache[i] != prev_cache) {
1369 			prev_cache = zio_buf_cache[i];
1370 			kmem_cache_reap_now(zio_buf_cache[i]);
1371 		}
1372 		if (zio_data_buf_cache[i] != prev_data_cache) {
1373 			prev_data_cache = zio_data_buf_cache[i];
1374 			kmem_cache_reap_now(zio_data_buf_cache[i]);
1375 		}
1376 	}
1377 	kmem_cache_reap_now(buf_cache);
1378 	kmem_cache_reap_now(hdr_cache);
1379 }
1380 
1381 static void
1382 arc_reclaim_thread(void)
1383 {
1384 	clock_t			growtime = 0;
1385 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1386 	callb_cpr_t		cpr;
1387 
1388 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1389 
1390 	mutex_enter(&arc_reclaim_thr_lock);
1391 	while (arc_thread_exit == 0) {
1392 		if (arc_reclaim_needed()) {
1393 
1394 			if (arc.no_grow) {
1395 				if (last_reclaim == ARC_RECLAIM_CONS) {
1396 					last_reclaim = ARC_RECLAIM_AGGR;
1397 				} else {
1398 					last_reclaim = ARC_RECLAIM_CONS;
1399 				}
1400 			} else {
1401 				arc.no_grow = TRUE;
1402 				last_reclaim = ARC_RECLAIM_AGGR;
1403 				membar_producer();
1404 			}
1405 
1406 			/* reset the growth delay for every reclaim */
1407 			growtime = lbolt + (arc_grow_retry * hz);
1408 			ASSERT(growtime > 0);
1409 
1410 			arc_kmem_reap_now(last_reclaim);
1411 
1412 		} else if ((growtime > 0) && ((growtime - lbolt) <= 0)) {
1413 			arc.no_grow = FALSE;
1414 		}
1415 
1416 		if (2 * arc.c <
1417 		    arc.size + arc.mru_ghost->size + arc.mfu_ghost->size)
1418 			arc_adjust();
1419 
1420 		if (arc_eviction_list != NULL)
1421 			arc_do_user_evicts();
1422 
1423 		/* block until needed, or one second, whichever is shorter */
1424 		CALLB_CPR_SAFE_BEGIN(&cpr);
1425 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1426 		    &arc_reclaim_thr_lock, (lbolt + hz));
1427 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1428 	}
1429 
1430 	arc_thread_exit = 0;
1431 	cv_broadcast(&arc_reclaim_thr_cv);
1432 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1433 	thread_exit();
1434 }
1435 
1436 /*
1437  * Adapt arc info given the number of bytes we are trying to add and
1438  * the state that we are comming from.  This function is only called
1439  * when we are adding new content to the cache.
1440  */
1441 static void
1442 arc_adapt(int bytes, arc_state_t *state)
1443 {
1444 	int mult;
1445 
1446 	ASSERT(bytes > 0);
1447 	/*
1448 	 * Adapt the target size of the MRU list:
1449 	 *	- if we just hit in the MRU ghost list, then increase
1450 	 *	  the target size of the MRU list.
1451 	 *	- if we just hit in the MFU ghost list, then increase
1452 	 *	  the target size of the MFU list by decreasing the
1453 	 *	  target size of the MRU list.
1454 	 */
1455 	if (state == arc.mru_ghost) {
1456 		mult = ((arc.mru_ghost->size >= arc.mfu_ghost->size) ?
1457 		    1 : (arc.mfu_ghost->size/arc.mru_ghost->size));
1458 
1459 		arc.p = MIN(arc.c, arc.p + bytes * mult);
1460 	} else if (state == arc.mfu_ghost) {
1461 		mult = ((arc.mfu_ghost->size >= arc.mru_ghost->size) ?
1462 		    1 : (arc.mru_ghost->size/arc.mfu_ghost->size));
1463 
1464 		arc.p = MAX(0, (int64_t)arc.p - bytes * mult);
1465 	}
1466 	ASSERT((int64_t)arc.p >= 0);
1467 
1468 	if (arc_reclaim_needed()) {
1469 		cv_signal(&arc_reclaim_thr_cv);
1470 		return;
1471 	}
1472 
1473 	if (arc.no_grow)
1474 		return;
1475 
1476 	if (arc.c >= arc.c_max)
1477 		return;
1478 
1479 	/*
1480 	 * If we're within (2 * maxblocksize) bytes of the target
1481 	 * cache size, increment the target cache size
1482 	 */
1483 	if (arc.size > arc.c - (2ULL << SPA_MAXBLOCKSHIFT)) {
1484 		atomic_add_64(&arc.c, (int64_t)bytes);
1485 		if (arc.c > arc.c_max)
1486 			arc.c = arc.c_max;
1487 		else if (state == arc.anon)
1488 			atomic_add_64(&arc.p, (int64_t)bytes);
1489 		if (arc.p > arc.c)
1490 			arc.p = arc.c;
1491 	}
1492 	ASSERT((int64_t)arc.p >= 0);
1493 }
1494 
1495 /*
1496  * Check if the cache has reached its limits and eviction is required
1497  * prior to insert.
1498  */
1499 static int
1500 arc_evict_needed()
1501 {
1502 	if (arc_reclaim_needed())
1503 		return (1);
1504 
1505 	return (arc.size > arc.c);
1506 }
1507 
1508 /*
1509  * The buffer, supplied as the first argument, needs a data block.
1510  * So, if we are at cache max, determine which cache should be victimized.
1511  * We have the following cases:
1512  *
1513  * 1. Insert for MRU, p > sizeof(arc.anon + arc.mru) ->
1514  * In this situation if we're out of space, but the resident size of the MFU is
1515  * under the limit, victimize the MFU cache to satisfy this insertion request.
1516  *
1517  * 2. Insert for MRU, p <= sizeof(arc.anon + arc.mru) ->
1518  * Here, we've used up all of the available space for the MRU, so we need to
1519  * evict from our own cache instead.  Evict from the set of resident MRU
1520  * entries.
1521  *
1522  * 3. Insert for MFU (c - p) > sizeof(arc.mfu) ->
1523  * c minus p represents the MFU space in the cache, since p is the size of the
1524  * cache that is dedicated to the MRU.  In this situation there's still space on
1525  * the MFU side, so the MRU side needs to be victimized.
1526  *
1527  * 4. Insert for MFU (c - p) < sizeof(arc.mfu) ->
1528  * MFU's resident set is consuming more space than it has been allotted.  In
1529  * this situation, we must victimize our own cache, the MFU, for this insertion.
1530  */
1531 static void
1532 arc_get_data_buf(arc_buf_t *buf)
1533 {
1534 	arc_state_t		*state = buf->b_hdr->b_state;
1535 	uint64_t		size = buf->b_hdr->b_size;
1536 	arc_buf_contents_t	type = buf->b_hdr->b_type;
1537 
1538 	arc_adapt(size, state);
1539 
1540 	/*
1541 	 * We have not yet reached cache maximum size,
1542 	 * just allocate a new buffer.
1543 	 */
1544 	if (!arc_evict_needed()) {
1545 		if (type == ARC_BUFC_METADATA) {
1546 			buf->b_data = zio_buf_alloc(size);
1547 		} else {
1548 			ASSERT(type == ARC_BUFC_DATA);
1549 			buf->b_data = zio_data_buf_alloc(size);
1550 		}
1551 		atomic_add_64(&arc.size, size);
1552 		goto out;
1553 	}
1554 
1555 	/*
1556 	 * If we are prefetching from the mfu ghost list, this buffer
1557 	 * will end up on the mru list; so steal space from there.
1558 	 */
1559 	if (state == arc.mfu_ghost)
1560 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc.mru : arc.mfu;
1561 	else if (state == arc.mru_ghost)
1562 		state = arc.mru;
1563 
1564 	if (state == arc.mru || state == arc.anon) {
1565 		uint64_t mru_used = arc.anon->size + arc.mru->size;
1566 		state = (arc.p > mru_used) ? arc.mfu : arc.mru;
1567 	} else {
1568 		/* MFU cases */
1569 		uint64_t mfu_space = arc.c - arc.p;
1570 		state =  (mfu_space > arc.mfu->size) ? arc.mru : arc.mfu;
1571 	}
1572 	if ((buf->b_data = arc_evict(state, size, TRUE, type)) == NULL) {
1573 		if (type == ARC_BUFC_METADATA) {
1574 			buf->b_data = zio_buf_alloc(size);
1575 		} else {
1576 			ASSERT(type == ARC_BUFC_DATA);
1577 			buf->b_data = zio_data_buf_alloc(size);
1578 		}
1579 		atomic_add_64(&arc.size, size);
1580 		atomic_add_64(&arc.recycle_miss, 1);
1581 	}
1582 	ASSERT(buf->b_data != NULL);
1583 out:
1584 	/*
1585 	 * Update the state size.  Note that ghost states have a
1586 	 * "ghost size" and so don't need to be updated.
1587 	 */
1588 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
1589 		arc_buf_hdr_t *hdr = buf->b_hdr;
1590 
1591 		atomic_add_64(&hdr->b_state->size, size);
1592 		if (list_link_active(&hdr->b_arc_node)) {
1593 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
1594 			atomic_add_64(&hdr->b_state->lsize, size);
1595 		}
1596 		/*
1597 		 * If we are growing the cache, and we are adding anonymous
1598 		 * data, and we have outgrown arc.p, update arc.p
1599 		 */
1600 		if (arc.size < arc.c && hdr->b_state == arc.anon &&
1601 		    arc.anon->size + arc.mru->size > arc.p)
1602 			arc.p = MIN(arc.c, arc.p + size);
1603 	}
1604 }
1605 
1606 /*
1607  * This routine is called whenever a buffer is accessed.
1608  * NOTE: the hash lock is dropped in this function.
1609  */
1610 static void
1611 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
1612 {
1613 	ASSERT(MUTEX_HELD(hash_lock));
1614 
1615 	if (buf->b_state == arc.anon) {
1616 		/*
1617 		 * This buffer is not in the cache, and does not
1618 		 * appear in our "ghost" list.  Add the new buffer
1619 		 * to the MRU state.
1620 		 */
1621 
1622 		ASSERT(buf->b_arc_access == 0);
1623 		buf->b_arc_access = lbolt;
1624 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1625 		arc_change_state(arc.mru, buf, hash_lock);
1626 
1627 	} else if (buf->b_state == arc.mru) {
1628 		/*
1629 		 * If this buffer is here because of a prefetch, then either:
1630 		 * - clear the flag if this is a "referencing" read
1631 		 *   (any subsequent access will bump this into the MFU state).
1632 		 * or
1633 		 * - move the buffer to the head of the list if this is
1634 		 *   another prefetch (to make it less likely to be evicted).
1635 		 */
1636 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1637 			if (refcount_count(&buf->b_refcnt) == 0) {
1638 				ASSERT(list_link_active(&buf->b_arc_node));
1639 				mutex_enter(&arc.mru->mtx);
1640 				list_remove(&arc.mru->list, buf);
1641 				list_insert_head(&arc.mru->list, buf);
1642 				mutex_exit(&arc.mru->mtx);
1643 			} else {
1644 				buf->b_flags &= ~ARC_PREFETCH;
1645 				atomic_add_64(&arc.mru->hits, 1);
1646 			}
1647 			buf->b_arc_access = lbolt;
1648 			return;
1649 		}
1650 
1651 		/*
1652 		 * This buffer has been "accessed" only once so far,
1653 		 * but it is still in the cache. Move it to the MFU
1654 		 * state.
1655 		 */
1656 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
1657 			/*
1658 			 * More than 125ms have passed since we
1659 			 * instantiated this buffer.  Move it to the
1660 			 * most frequently used state.
1661 			 */
1662 			buf->b_arc_access = lbolt;
1663 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1664 			arc_change_state(arc.mfu, buf, hash_lock);
1665 		}
1666 		atomic_add_64(&arc.mru->hits, 1);
1667 	} else if (buf->b_state == arc.mru_ghost) {
1668 		arc_state_t	*new_state;
1669 		/*
1670 		 * This buffer has been "accessed" recently, but
1671 		 * was evicted from the cache.  Move it to the
1672 		 * MFU state.
1673 		 */
1674 
1675 		if (buf->b_flags & ARC_PREFETCH) {
1676 			new_state = arc.mru;
1677 			if (refcount_count(&buf->b_refcnt) > 0)
1678 				buf->b_flags &= ~ARC_PREFETCH;
1679 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1680 		} else {
1681 			new_state = arc.mfu;
1682 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1683 		}
1684 
1685 		buf->b_arc_access = lbolt;
1686 		arc_change_state(new_state, buf, hash_lock);
1687 
1688 		atomic_add_64(&arc.mru_ghost->hits, 1);
1689 	} else if (buf->b_state == arc.mfu) {
1690 		/*
1691 		 * This buffer has been accessed more than once and is
1692 		 * still in the cache.  Keep it in the MFU state.
1693 		 *
1694 		 * NOTE: an add_reference() that occurred when we did
1695 		 * the arc_read() will have kicked this off the list.
1696 		 * If it was a prefetch, we will explicitly move it to
1697 		 * the head of the list now.
1698 		 */
1699 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1700 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
1701 			ASSERT(list_link_active(&buf->b_arc_node));
1702 			mutex_enter(&arc.mfu->mtx);
1703 			list_remove(&arc.mfu->list, buf);
1704 			list_insert_head(&arc.mfu->list, buf);
1705 			mutex_exit(&arc.mfu->mtx);
1706 		}
1707 		atomic_add_64(&arc.mfu->hits, 1);
1708 		buf->b_arc_access = lbolt;
1709 	} else if (buf->b_state == arc.mfu_ghost) {
1710 		arc_state_t	*new_state = arc.mfu;
1711 		/*
1712 		 * This buffer has been accessed more than once but has
1713 		 * been evicted from the cache.  Move it back to the
1714 		 * MFU state.
1715 		 */
1716 
1717 		if (buf->b_flags & ARC_PREFETCH) {
1718 			/*
1719 			 * This is a prefetch access...
1720 			 * move this block back to the MRU state.
1721 			 */
1722 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
1723 			new_state = arc.mru;
1724 		}
1725 
1726 		buf->b_arc_access = lbolt;
1727 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1728 		arc_change_state(new_state, buf, hash_lock);
1729 
1730 		atomic_add_64(&arc.mfu_ghost->hits, 1);
1731 	} else {
1732 		ASSERT(!"invalid arc state");
1733 	}
1734 }
1735 
1736 /* a generic arc_done_func_t which you can use */
1737 /* ARGSUSED */
1738 void
1739 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
1740 {
1741 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
1742 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1743 }
1744 
1745 /* a generic arc_done_func_t which you can use */
1746 void
1747 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
1748 {
1749 	arc_buf_t **bufp = arg;
1750 	if (zio && zio->io_error) {
1751 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1752 		*bufp = NULL;
1753 	} else {
1754 		*bufp = buf;
1755 	}
1756 }
1757 
1758 static void
1759 arc_read_done(zio_t *zio)
1760 {
1761 	arc_buf_hdr_t	*hdr, *found;
1762 	arc_buf_t	*buf;
1763 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
1764 	kmutex_t	*hash_lock;
1765 	arc_callback_t	*callback_list, *acb;
1766 	int		freeable = FALSE;
1767 
1768 	buf = zio->io_private;
1769 	hdr = buf->b_hdr;
1770 
1771 	/*
1772 	 * The hdr was inserted into hash-table and removed from lists
1773 	 * prior to starting I/O.  We should find this header, since
1774 	 * it's in the hash table, and it should be legit since it's
1775 	 * not possible to evict it during the I/O.  The only possible
1776 	 * reason for it not to be found is if we were freed during the
1777 	 * read.
1778 	 */
1779 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
1780 	    &hash_lock);
1781 
1782 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
1783 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))));
1784 
1785 	/* byteswap if necessary */
1786 	callback_list = hdr->b_acb;
1787 	ASSERT(callback_list != NULL);
1788 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && callback_list->acb_byteswap)
1789 		callback_list->acb_byteswap(buf->b_data, hdr->b_size);
1790 
1791 	arc_cksum_compute(buf);
1792 
1793 	/* create copies of the data buffer for the callers */
1794 	abuf = buf;
1795 	for (acb = callback_list; acb; acb = acb->acb_next) {
1796 		if (acb->acb_done) {
1797 			if (abuf == NULL)
1798 				abuf = arc_buf_clone(buf);
1799 			acb->acb_buf = abuf;
1800 			abuf = NULL;
1801 		}
1802 	}
1803 	hdr->b_acb = NULL;
1804 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
1805 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
1806 	if (abuf == buf)
1807 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1808 
1809 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
1810 
1811 	if (zio->io_error != 0) {
1812 		hdr->b_flags |= ARC_IO_ERROR;
1813 		if (hdr->b_state != arc.anon)
1814 			arc_change_state(arc.anon, hdr, hash_lock);
1815 		if (HDR_IN_HASH_TABLE(hdr))
1816 			buf_hash_remove(hdr);
1817 		freeable = refcount_is_zero(&hdr->b_refcnt);
1818 		/* convert checksum errors into IO errors */
1819 		if (zio->io_error == ECKSUM)
1820 			zio->io_error = EIO;
1821 	}
1822 
1823 	/*
1824 	 * Broadcast before we drop the hash_lock to avoid the possibility
1825 	 * that the hdr (and hence the cv) might be freed before we get to
1826 	 * the cv_broadcast().
1827 	 */
1828 	cv_broadcast(&hdr->b_cv);
1829 
1830 	if (hash_lock) {
1831 		/*
1832 		 * Only call arc_access on anonymous buffers.  This is because
1833 		 * if we've issued an I/O for an evicted buffer, we've already
1834 		 * called arc_access (to prevent any simultaneous readers from
1835 		 * getting confused).
1836 		 */
1837 		if (zio->io_error == 0 && hdr->b_state == arc.anon)
1838 			arc_access(hdr, hash_lock);
1839 		mutex_exit(hash_lock);
1840 	} else {
1841 		/*
1842 		 * This block was freed while we waited for the read to
1843 		 * complete.  It has been removed from the hash table and
1844 		 * moved to the anonymous state (so that it won't show up
1845 		 * in the cache).
1846 		 */
1847 		ASSERT3P(hdr->b_state, ==, arc.anon);
1848 		freeable = refcount_is_zero(&hdr->b_refcnt);
1849 	}
1850 
1851 	/* execute each callback and free its structure */
1852 	while ((acb = callback_list) != NULL) {
1853 		if (acb->acb_done)
1854 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
1855 
1856 		if (acb->acb_zio_dummy != NULL) {
1857 			acb->acb_zio_dummy->io_error = zio->io_error;
1858 			zio_nowait(acb->acb_zio_dummy);
1859 		}
1860 
1861 		callback_list = acb->acb_next;
1862 		kmem_free(acb, sizeof (arc_callback_t));
1863 	}
1864 
1865 	if (freeable)
1866 		arc_hdr_destroy(hdr);
1867 }
1868 
1869 /*
1870  * "Read" the block block at the specified DVA (in bp) via the
1871  * cache.  If the block is found in the cache, invoke the provided
1872  * callback immediately and return.  Note that the `zio' parameter
1873  * in the callback will be NULL in this case, since no IO was
1874  * required.  If the block is not in the cache pass the read request
1875  * on to the spa with a substitute callback function, so that the
1876  * requested block will be added to the cache.
1877  *
1878  * If a read request arrives for a block that has a read in-progress,
1879  * either wait for the in-progress read to complete (and return the
1880  * results); or, if this is a read with a "done" func, add a record
1881  * to the read to invoke the "done" func when the read completes,
1882  * and return; or just return.
1883  *
1884  * arc_read_done() will invoke all the requested "done" functions
1885  * for readers of this block.
1886  */
1887 int
1888 arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_byteswap_func_t *swap,
1889     arc_done_func_t *done, void *private, int priority, int flags,
1890     uint32_t *arc_flags, zbookmark_t *zb)
1891 {
1892 	arc_buf_hdr_t *hdr;
1893 	arc_buf_t *buf;
1894 	kmutex_t *hash_lock;
1895 	zio_t	*rzio;
1896 
1897 top:
1898 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
1899 	if (hdr && hdr->b_datacnt > 0) {
1900 
1901 		*arc_flags |= ARC_CACHED;
1902 
1903 		if (HDR_IO_IN_PROGRESS(hdr)) {
1904 
1905 			if (*arc_flags & ARC_WAIT) {
1906 				cv_wait(&hdr->b_cv, hash_lock);
1907 				mutex_exit(hash_lock);
1908 				goto top;
1909 			}
1910 			ASSERT(*arc_flags & ARC_NOWAIT);
1911 
1912 			if (done) {
1913 				arc_callback_t	*acb = NULL;
1914 
1915 				acb = kmem_zalloc(sizeof (arc_callback_t),
1916 				    KM_SLEEP);
1917 				acb->acb_done = done;
1918 				acb->acb_private = private;
1919 				acb->acb_byteswap = swap;
1920 				if (pio != NULL)
1921 					acb->acb_zio_dummy = zio_null(pio,
1922 					    spa, NULL, NULL, flags);
1923 
1924 				ASSERT(acb->acb_done != NULL);
1925 				acb->acb_next = hdr->b_acb;
1926 				hdr->b_acb = acb;
1927 				add_reference(hdr, hash_lock, private);
1928 				mutex_exit(hash_lock);
1929 				return (0);
1930 			}
1931 			mutex_exit(hash_lock);
1932 			return (0);
1933 		}
1934 
1935 		ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
1936 
1937 		if (done) {
1938 			add_reference(hdr, hash_lock, private);
1939 			/*
1940 			 * If this block is already in use, create a new
1941 			 * copy of the data so that we will be guaranteed
1942 			 * that arc_release() will always succeed.
1943 			 */
1944 			buf = hdr->b_buf;
1945 			ASSERT(buf);
1946 			ASSERT(buf->b_data);
1947 			if (HDR_BUF_AVAILABLE(hdr)) {
1948 				ASSERT(buf->b_efunc == NULL);
1949 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
1950 			} else {
1951 				buf = arc_buf_clone(buf);
1952 			}
1953 		} else if (*arc_flags & ARC_PREFETCH &&
1954 		    refcount_count(&hdr->b_refcnt) == 0) {
1955 			hdr->b_flags |= ARC_PREFETCH;
1956 		}
1957 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1958 		arc_access(hdr, hash_lock);
1959 		mutex_exit(hash_lock);
1960 		atomic_add_64(&arc.hits, 1);
1961 		if (done)
1962 			done(NULL, buf, private);
1963 	} else {
1964 		uint64_t size = BP_GET_LSIZE(bp);
1965 		arc_callback_t	*acb;
1966 
1967 		if (hdr == NULL) {
1968 			/* this block is not in the cache */
1969 			arc_buf_hdr_t	*exists;
1970 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
1971 			buf = arc_buf_alloc(spa, size, private, type);
1972 			hdr = buf->b_hdr;
1973 			hdr->b_dva = *BP_IDENTITY(bp);
1974 			hdr->b_birth = bp->blk_birth;
1975 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
1976 			exists = buf_hash_insert(hdr, &hash_lock);
1977 			if (exists) {
1978 				/* somebody beat us to the hash insert */
1979 				mutex_exit(hash_lock);
1980 				bzero(&hdr->b_dva, sizeof (dva_t));
1981 				hdr->b_birth = 0;
1982 				hdr->b_cksum0 = 0;
1983 				(void) arc_buf_remove_ref(buf, private);
1984 				goto top; /* restart the IO request */
1985 			}
1986 			/* if this is a prefetch, we don't have a reference */
1987 			if (*arc_flags & ARC_PREFETCH) {
1988 				(void) remove_reference(hdr, hash_lock,
1989 				    private);
1990 				hdr->b_flags |= ARC_PREFETCH;
1991 			}
1992 			if (BP_GET_LEVEL(bp) > 0)
1993 				hdr->b_flags |= ARC_INDIRECT;
1994 		} else {
1995 			/* this block is in the ghost cache */
1996 			ASSERT(GHOST_STATE(hdr->b_state));
1997 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1998 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
1999 			ASSERT(hdr->b_buf == NULL);
2000 
2001 			/* if this is a prefetch, we don't have a reference */
2002 			if (*arc_flags & ARC_PREFETCH)
2003 				hdr->b_flags |= ARC_PREFETCH;
2004 			else
2005 				add_reference(hdr, hash_lock, private);
2006 			buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
2007 			buf->b_hdr = hdr;
2008 			buf->b_data = NULL;
2009 			buf->b_efunc = NULL;
2010 			buf->b_private = NULL;
2011 			buf->b_next = NULL;
2012 			hdr->b_buf = buf;
2013 			arc_get_data_buf(buf);
2014 			ASSERT(hdr->b_datacnt == 0);
2015 			hdr->b_datacnt = 1;
2016 
2017 		}
2018 
2019 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2020 		acb->acb_done = done;
2021 		acb->acb_private = private;
2022 		acb->acb_byteswap = swap;
2023 
2024 		ASSERT(hdr->b_acb == NULL);
2025 		hdr->b_acb = acb;
2026 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2027 
2028 		/*
2029 		 * If the buffer has been evicted, migrate it to a present state
2030 		 * before issuing the I/O.  Once we drop the hash-table lock,
2031 		 * the header will be marked as I/O in progress and have an
2032 		 * attached buffer.  At this point, anybody who finds this
2033 		 * buffer ought to notice that it's legit but has a pending I/O.
2034 		 */
2035 
2036 		if (GHOST_STATE(hdr->b_state))
2037 			arc_access(hdr, hash_lock);
2038 		mutex_exit(hash_lock);
2039 
2040 		ASSERT3U(hdr->b_size, ==, size);
2041 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
2042 		    zbookmark_t *, zb);
2043 		atomic_add_64(&arc.misses, 1);
2044 
2045 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
2046 		    arc_read_done, buf, priority, flags, zb);
2047 
2048 		if (*arc_flags & ARC_WAIT)
2049 			return (zio_wait(rzio));
2050 
2051 		ASSERT(*arc_flags & ARC_NOWAIT);
2052 		zio_nowait(rzio);
2053 	}
2054 	return (0);
2055 }
2056 
2057 /*
2058  * arc_read() variant to support pool traversal.  If the block is already
2059  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2060  * The idea is that we don't want pool traversal filling up memory, but
2061  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2062  */
2063 int
2064 arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2065 {
2066 	arc_buf_hdr_t *hdr;
2067 	kmutex_t *hash_mtx;
2068 	int rc = 0;
2069 
2070 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2071 
2072 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
2073 		arc_buf_t *buf = hdr->b_buf;
2074 
2075 		ASSERT(buf);
2076 		while (buf->b_data == NULL) {
2077 			buf = buf->b_next;
2078 			ASSERT(buf);
2079 		}
2080 		bcopy(buf->b_data, data, hdr->b_size);
2081 	} else {
2082 		rc = ENOENT;
2083 	}
2084 
2085 	if (hash_mtx)
2086 		mutex_exit(hash_mtx);
2087 
2088 	return (rc);
2089 }
2090 
2091 void
2092 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
2093 {
2094 	ASSERT(buf->b_hdr != NULL);
2095 	ASSERT(buf->b_hdr->b_state != arc.anon);
2096 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
2097 	buf->b_efunc = func;
2098 	buf->b_private = private;
2099 }
2100 
2101 /*
2102  * This is used by the DMU to let the ARC know that a buffer is
2103  * being evicted, so the ARC should clean up.  If this arc buf
2104  * is not yet in the evicted state, it will be put there.
2105  */
2106 int
2107 arc_buf_evict(arc_buf_t *buf)
2108 {
2109 	arc_buf_hdr_t *hdr;
2110 	kmutex_t *hash_lock;
2111 	arc_buf_t **bufp;
2112 
2113 	mutex_enter(&arc_eviction_mtx);
2114 	hdr = buf->b_hdr;
2115 	if (hdr == NULL) {
2116 		/*
2117 		 * We are in arc_do_user_evicts().
2118 		 */
2119 		ASSERT(buf->b_data == NULL);
2120 		mutex_exit(&arc_eviction_mtx);
2121 		return (0);
2122 	}
2123 	hash_lock = HDR_LOCK(hdr);
2124 	mutex_exit(&arc_eviction_mtx);
2125 
2126 	mutex_enter(hash_lock);
2127 
2128 	if (buf->b_data == NULL) {
2129 		/*
2130 		 * We are on the eviction list.
2131 		 */
2132 		mutex_exit(hash_lock);
2133 		mutex_enter(&arc_eviction_mtx);
2134 		if (buf->b_hdr == NULL) {
2135 			/*
2136 			 * We are already in arc_do_user_evicts().
2137 			 */
2138 			mutex_exit(&arc_eviction_mtx);
2139 			return (0);
2140 		} else {
2141 			arc_buf_t copy = *buf; /* structure assignment */
2142 			/*
2143 			 * Process this buffer now
2144 			 * but let arc_do_user_evicts() do the reaping.
2145 			 */
2146 			buf->b_efunc = NULL;
2147 			mutex_exit(&arc_eviction_mtx);
2148 			VERIFY(copy.b_efunc(&copy) == 0);
2149 			return (1);
2150 		}
2151 	}
2152 
2153 	ASSERT(buf->b_hdr == hdr);
2154 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
2155 	ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
2156 
2157 	/*
2158 	 * Pull this buffer off of the hdr
2159 	 */
2160 	bufp = &hdr->b_buf;
2161 	while (*bufp != buf)
2162 		bufp = &(*bufp)->b_next;
2163 	*bufp = buf->b_next;
2164 
2165 	ASSERT(buf->b_data != NULL);
2166 	arc_buf_destroy(buf, FALSE, FALSE);
2167 
2168 	if (hdr->b_datacnt == 0) {
2169 		arc_state_t *old_state = hdr->b_state;
2170 		arc_state_t *evicted_state;
2171 
2172 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
2173 
2174 		evicted_state =
2175 		    (old_state == arc.mru) ? arc.mru_ghost : arc.mfu_ghost;
2176 
2177 		mutex_enter(&old_state->mtx);
2178 		mutex_enter(&evicted_state->mtx);
2179 
2180 		arc_change_state(evicted_state, hdr, hash_lock);
2181 		ASSERT(HDR_IN_HASH_TABLE(hdr));
2182 		hdr->b_flags = ARC_IN_HASH_TABLE;
2183 
2184 		mutex_exit(&evicted_state->mtx);
2185 		mutex_exit(&old_state->mtx);
2186 	}
2187 	mutex_exit(hash_lock);
2188 
2189 	VERIFY(buf->b_efunc(buf) == 0);
2190 	buf->b_efunc = NULL;
2191 	buf->b_private = NULL;
2192 	buf->b_hdr = NULL;
2193 	kmem_cache_free(buf_cache, buf);
2194 	return (1);
2195 }
2196 
2197 /*
2198  * Release this buffer from the cache.  This must be done
2199  * after a read and prior to modifying the buffer contents.
2200  * If the buffer has more than one reference, we must make
2201  * make a new hdr for the buffer.
2202  */
2203 void
2204 arc_release(arc_buf_t *buf, void *tag)
2205 {
2206 	arc_buf_hdr_t *hdr = buf->b_hdr;
2207 	kmutex_t *hash_lock = HDR_LOCK(hdr);
2208 
2209 	/* this buffer is not on any list */
2210 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2211 
2212 	if (hdr->b_state == arc.anon) {
2213 		/* this buffer is already released */
2214 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2215 		ASSERT(BUF_EMPTY(hdr));
2216 		ASSERT(buf->b_efunc == NULL);
2217 		arc_buf_thaw(buf);
2218 		return;
2219 	}
2220 
2221 	mutex_enter(hash_lock);
2222 
2223 	/*
2224 	 * Do we have more than one buf?
2225 	 */
2226 	if (hdr->b_buf != buf || buf->b_next != NULL) {
2227 		arc_buf_hdr_t *nhdr;
2228 		arc_buf_t **bufp;
2229 		uint64_t blksz = hdr->b_size;
2230 		spa_t *spa = hdr->b_spa;
2231 		arc_buf_contents_t type = hdr->b_type;
2232 
2233 		ASSERT(hdr->b_datacnt > 1);
2234 		/*
2235 		 * Pull the data off of this buf and attach it to
2236 		 * a new anonymous buf.
2237 		 */
2238 		(void) remove_reference(hdr, hash_lock, tag);
2239 		bufp = &hdr->b_buf;
2240 		while (*bufp != buf)
2241 			bufp = &(*bufp)->b_next;
2242 		*bufp = (*bufp)->b_next;
2243 
2244 		ASSERT3U(hdr->b_state->size, >=, hdr->b_size);
2245 		atomic_add_64(&hdr->b_state->size, -hdr->b_size);
2246 		if (refcount_is_zero(&hdr->b_refcnt)) {
2247 			ASSERT3U(hdr->b_state->lsize, >=, hdr->b_size);
2248 			atomic_add_64(&hdr->b_state->lsize, -hdr->b_size);
2249 		}
2250 		hdr->b_datacnt -= 1;
2251 
2252 		mutex_exit(hash_lock);
2253 
2254 		nhdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
2255 		nhdr->b_size = blksz;
2256 		nhdr->b_spa = spa;
2257 		nhdr->b_type = type;
2258 		nhdr->b_buf = buf;
2259 		nhdr->b_state = arc.anon;
2260 		nhdr->b_arc_access = 0;
2261 		nhdr->b_flags = 0;
2262 		nhdr->b_datacnt = 1;
2263 		nhdr->b_freeze_cksum =
2264 		    kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
2265 		*nhdr->b_freeze_cksum = *hdr->b_freeze_cksum; /* struct copy */
2266 		buf->b_hdr = nhdr;
2267 		buf->b_next = NULL;
2268 		(void) refcount_add(&nhdr->b_refcnt, tag);
2269 		atomic_add_64(&arc.anon->size, blksz);
2270 
2271 		hdr = nhdr;
2272 	} else {
2273 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
2274 		ASSERT(!list_link_active(&hdr->b_arc_node));
2275 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2276 		arc_change_state(arc.anon, hdr, hash_lock);
2277 		hdr->b_arc_access = 0;
2278 		mutex_exit(hash_lock);
2279 		bzero(&hdr->b_dva, sizeof (dva_t));
2280 		hdr->b_birth = 0;
2281 		hdr->b_cksum0 = 0;
2282 	}
2283 	buf->b_efunc = NULL;
2284 	buf->b_private = NULL;
2285 	arc_buf_thaw(buf);
2286 }
2287 
2288 int
2289 arc_released(arc_buf_t *buf)
2290 {
2291 	return (buf->b_data != NULL && buf->b_hdr->b_state == arc.anon);
2292 }
2293 
2294 int
2295 arc_has_callback(arc_buf_t *buf)
2296 {
2297 	return (buf->b_efunc != NULL);
2298 }
2299 
2300 #ifdef ZFS_DEBUG
2301 int
2302 arc_referenced(arc_buf_t *buf)
2303 {
2304 	return (refcount_count(&buf->b_hdr->b_refcnt));
2305 }
2306 #endif
2307 
2308 static void
2309 arc_write_done(zio_t *zio)
2310 {
2311 	arc_buf_t *buf;
2312 	arc_buf_hdr_t *hdr;
2313 	arc_callback_t *acb;
2314 
2315 	buf = zio->io_private;
2316 	hdr = buf->b_hdr;
2317 	acb = hdr->b_acb;
2318 	hdr->b_acb = NULL;
2319 	ASSERT(acb != NULL);
2320 
2321 	/* this buffer is on no lists and is not in the hash table */
2322 	ASSERT3P(hdr->b_state, ==, arc.anon);
2323 
2324 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
2325 	hdr->b_birth = zio->io_bp->blk_birth;
2326 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
2327 	/*
2328 	 * If the block to be written was all-zero, we may have
2329 	 * compressed it away.  In this case no write was performed
2330 	 * so there will be no dva/birth-date/checksum.  The buffer
2331 	 * must therefor remain anonymous (and uncached).
2332 	 */
2333 	if (!BUF_EMPTY(hdr)) {
2334 		arc_buf_hdr_t *exists;
2335 		kmutex_t *hash_lock;
2336 
2337 		arc_cksum_verify(buf);
2338 
2339 		exists = buf_hash_insert(hdr, &hash_lock);
2340 		if (exists) {
2341 			/*
2342 			 * This can only happen if we overwrite for
2343 			 * sync-to-convergence, because we remove
2344 			 * buffers from the hash table when we arc_free().
2345 			 */
2346 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
2347 			    BP_IDENTITY(zio->io_bp)));
2348 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
2349 			    zio->io_bp->blk_birth);
2350 
2351 			ASSERT(refcount_is_zero(&exists->b_refcnt));
2352 			arc_change_state(arc.anon, exists, hash_lock);
2353 			mutex_exit(hash_lock);
2354 			arc_hdr_destroy(exists);
2355 			exists = buf_hash_insert(hdr, &hash_lock);
2356 			ASSERT3P(exists, ==, NULL);
2357 		}
2358 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2359 		arc_access(hdr, hash_lock);
2360 		mutex_exit(hash_lock);
2361 	} else if (acb->acb_done == NULL) {
2362 		int destroy_hdr;
2363 		/*
2364 		 * This is an anonymous buffer with no user callback,
2365 		 * destroy it if there are no active references.
2366 		 */
2367 		mutex_enter(&arc_eviction_mtx);
2368 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
2369 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2370 		mutex_exit(&arc_eviction_mtx);
2371 		if (destroy_hdr)
2372 			arc_hdr_destroy(hdr);
2373 	} else {
2374 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2375 	}
2376 
2377 	if (acb->acb_done) {
2378 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
2379 		acb->acb_done(zio, buf, acb->acb_private);
2380 	}
2381 
2382 	kmem_free(acb, sizeof (arc_callback_t));
2383 }
2384 
2385 int
2386 arc_write(zio_t *pio, spa_t *spa, int checksum, int compress, int ncopies,
2387     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
2388     arc_done_func_t *done, void *private, int priority, int flags,
2389     uint32_t arc_flags, zbookmark_t *zb)
2390 {
2391 	arc_buf_hdr_t *hdr = buf->b_hdr;
2392 	arc_callback_t	*acb;
2393 	zio_t	*rzio;
2394 
2395 	/* this is a private buffer - no locking required */
2396 	ASSERT3P(hdr->b_state, ==, arc.anon);
2397 	ASSERT(BUF_EMPTY(hdr));
2398 	ASSERT(!HDR_IO_ERROR(hdr));
2399 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
2400 	ASSERT(hdr->b_acb == 0);
2401 	acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2402 	acb->acb_done = done;
2403 	acb->acb_private = private;
2404 	acb->acb_byteswap = (arc_byteswap_func_t *)-1;
2405 	hdr->b_acb = acb;
2406 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
2407 	arc_cksum_compute(buf);
2408 	rzio = zio_write(pio, spa, checksum, compress, ncopies, txg, bp,
2409 	    buf->b_data, hdr->b_size, arc_write_done, buf, priority, flags, zb);
2410 
2411 	if (arc_flags & ARC_WAIT)
2412 		return (zio_wait(rzio));
2413 
2414 	ASSERT(arc_flags & ARC_NOWAIT);
2415 	zio_nowait(rzio);
2416 
2417 	return (0);
2418 }
2419 
2420 int
2421 arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
2422     zio_done_func_t *done, void *private, uint32_t arc_flags)
2423 {
2424 	arc_buf_hdr_t *ab;
2425 	kmutex_t *hash_lock;
2426 	zio_t	*zio;
2427 
2428 	/*
2429 	 * If this buffer is in the cache, release it, so it
2430 	 * can be re-used.
2431 	 */
2432 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
2433 	if (ab != NULL) {
2434 		/*
2435 		 * The checksum of blocks to free is not always
2436 		 * preserved (eg. on the deadlist).  However, if it is
2437 		 * nonzero, it should match what we have in the cache.
2438 		 */
2439 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
2440 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
2441 		if (ab->b_state != arc.anon)
2442 			arc_change_state(arc.anon, ab, hash_lock);
2443 		if (HDR_IO_IN_PROGRESS(ab)) {
2444 			/*
2445 			 * This should only happen when we prefetch.
2446 			 */
2447 			ASSERT(ab->b_flags & ARC_PREFETCH);
2448 			ASSERT3U(ab->b_datacnt, ==, 1);
2449 			ab->b_flags |= ARC_FREED_IN_READ;
2450 			if (HDR_IN_HASH_TABLE(ab))
2451 				buf_hash_remove(ab);
2452 			ab->b_arc_access = 0;
2453 			bzero(&ab->b_dva, sizeof (dva_t));
2454 			ab->b_birth = 0;
2455 			ab->b_cksum0 = 0;
2456 			ab->b_buf->b_efunc = NULL;
2457 			ab->b_buf->b_private = NULL;
2458 			mutex_exit(hash_lock);
2459 		} else if (refcount_is_zero(&ab->b_refcnt)) {
2460 			mutex_exit(hash_lock);
2461 			arc_hdr_destroy(ab);
2462 			atomic_add_64(&arc.deleted, 1);
2463 		} else {
2464 			/*
2465 			 * We still have an active reference on this
2466 			 * buffer.  This can happen, e.g., from
2467 			 * dbuf_unoverride().
2468 			 */
2469 			ASSERT(!HDR_IN_HASH_TABLE(ab));
2470 			ab->b_arc_access = 0;
2471 			bzero(&ab->b_dva, sizeof (dva_t));
2472 			ab->b_birth = 0;
2473 			ab->b_cksum0 = 0;
2474 			ab->b_buf->b_efunc = NULL;
2475 			ab->b_buf->b_private = NULL;
2476 			mutex_exit(hash_lock);
2477 		}
2478 	}
2479 
2480 	zio = zio_free(pio, spa, txg, bp, done, private);
2481 
2482 	if (arc_flags & ARC_WAIT)
2483 		return (zio_wait(zio));
2484 
2485 	ASSERT(arc_flags & ARC_NOWAIT);
2486 	zio_nowait(zio);
2487 
2488 	return (0);
2489 }
2490 
2491 void
2492 arc_tempreserve_clear(uint64_t tempreserve)
2493 {
2494 	atomic_add_64(&arc_tempreserve, -tempreserve);
2495 	ASSERT((int64_t)arc_tempreserve >= 0);
2496 }
2497 
2498 int
2499 arc_tempreserve_space(uint64_t tempreserve)
2500 {
2501 #ifdef ZFS_DEBUG
2502 	/*
2503 	 * Once in a while, fail for no reason.  Everything should cope.
2504 	 */
2505 	if (spa_get_random(10000) == 0) {
2506 		dprintf("forcing random failure\n");
2507 		return (ERESTART);
2508 	}
2509 #endif
2510 	if (tempreserve > arc.c/4 && !arc.no_grow)
2511 		arc.c = MIN(arc.c_max, tempreserve * 4);
2512 	if (tempreserve > arc.c)
2513 		return (ENOMEM);
2514 
2515 	/*
2516 	 * Throttle writes when the amount of dirty data in the cache
2517 	 * gets too large.  We try to keep the cache less than half full
2518 	 * of dirty blocks so that our sync times don't grow too large.
2519 	 * Note: if two requests come in concurrently, we might let them
2520 	 * both succeed, when one of them should fail.  Not a huge deal.
2521 	 *
2522 	 * XXX The limit should be adjusted dynamically to keep the time
2523 	 * to sync a dataset fixed (around 1-5 seconds?).
2524 	 */
2525 
2526 	if (tempreserve + arc_tempreserve + arc.anon->size > arc.c / 2 &&
2527 	    arc_tempreserve + arc.anon->size > arc.c / 4) {
2528 		dprintf("failing, arc_tempreserve=%lluK anon=%lluK "
2529 		    "tempreserve=%lluK arc.c=%lluK\n",
2530 		    arc_tempreserve>>10, arc.anon->lsize>>10,
2531 		    tempreserve>>10, arc.c>>10);
2532 		return (ERESTART);
2533 	}
2534 	atomic_add_64(&arc_tempreserve, tempreserve);
2535 	return (0);
2536 }
2537 
2538 void
2539 arc_init(void)
2540 {
2541 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
2542 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
2543 
2544 	/* Convert seconds to clock ticks */
2545 	arc_min_prefetch_lifespan = 1 * hz;
2546 
2547 	/* Start out with 1/8 of all memory */
2548 	arc.c = physmem * PAGESIZE / 8;
2549 
2550 #ifdef _KERNEL
2551 	/*
2552 	 * On architectures where the physical memory can be larger
2553 	 * than the addressable space (intel in 32-bit mode), we may
2554 	 * need to limit the cache to 1/8 of VM size.
2555 	 */
2556 	arc.c = MIN(arc.c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
2557 #endif
2558 
2559 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
2560 	arc.c_min = MAX(arc.c / 4, 64<<20);
2561 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
2562 	if (arc.c * 8 >= 1<<30)
2563 		arc.c_max = (arc.c * 8) - (1<<30);
2564 	else
2565 		arc.c_max = arc.c_min;
2566 	arc.c_max = MAX(arc.c * 6, arc.c_max);
2567 
2568 	/*
2569 	 * Allow the tunables to override our calculations if they are
2570 	 * reasonable (ie. over 64MB)
2571 	 */
2572 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
2573 		arc.c_max = zfs_arc_max;
2574 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc.c_max)
2575 		arc.c_min = zfs_arc_min;
2576 
2577 	arc.c = arc.c_max;
2578 	arc.p = (arc.c >> 1);
2579 
2580 	/* if kmem_flags are set, lets try to use less memory */
2581 	if (kmem_debugging())
2582 		arc.c = arc.c / 2;
2583 	if (arc.c < arc.c_min)
2584 		arc.c = arc.c_min;
2585 
2586 	arc.anon = &ARC_anon;
2587 	arc.mru = &ARC_mru;
2588 	arc.mru_ghost = &ARC_mru_ghost;
2589 	arc.mfu = &ARC_mfu;
2590 	arc.mfu_ghost = &ARC_mfu_ghost;
2591 	arc.size = 0;
2592 
2593 	arc.hits = 0;
2594 	arc.recycle_miss = 0;
2595 	arc.evict_skip = 0;
2596 	arc.mutex_miss = 0;
2597 
2598 	mutex_init(&arc.anon->mtx, NULL, MUTEX_DEFAULT, NULL);
2599 	mutex_init(&arc.mru->mtx, NULL, MUTEX_DEFAULT, NULL);
2600 	mutex_init(&arc.mru_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2601 	mutex_init(&arc.mfu->mtx, NULL, MUTEX_DEFAULT, NULL);
2602 	mutex_init(&arc.mfu_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2603 
2604 	list_create(&arc.mru->list, sizeof (arc_buf_hdr_t),
2605 	    offsetof(arc_buf_hdr_t, b_arc_node));
2606 	list_create(&arc.mru_ghost->list, sizeof (arc_buf_hdr_t),
2607 	    offsetof(arc_buf_hdr_t, b_arc_node));
2608 	list_create(&arc.mfu->list, sizeof (arc_buf_hdr_t),
2609 	    offsetof(arc_buf_hdr_t, b_arc_node));
2610 	list_create(&arc.mfu_ghost->list, sizeof (arc_buf_hdr_t),
2611 	    offsetof(arc_buf_hdr_t, b_arc_node));
2612 
2613 	buf_init();
2614 
2615 	arc_thread_exit = 0;
2616 	arc_eviction_list = NULL;
2617 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
2618 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
2619 
2620 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
2621 	    TS_RUN, minclsyspri);
2622 
2623 	arc_dead = FALSE;
2624 }
2625 
2626 void
2627 arc_fini(void)
2628 {
2629 	mutex_enter(&arc_reclaim_thr_lock);
2630 	arc_thread_exit = 1;
2631 	while (arc_thread_exit != 0)
2632 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
2633 	mutex_exit(&arc_reclaim_thr_lock);
2634 
2635 	arc_flush();
2636 
2637 	arc_dead = TRUE;
2638 
2639 	mutex_destroy(&arc_eviction_mtx);
2640 	mutex_destroy(&arc_reclaim_thr_lock);
2641 	cv_destroy(&arc_reclaim_thr_cv);
2642 
2643 	list_destroy(&arc.mru->list);
2644 	list_destroy(&arc.mru_ghost->list);
2645 	list_destroy(&arc.mfu->list);
2646 	list_destroy(&arc.mfu_ghost->list);
2647 
2648 	mutex_destroy(&arc.anon->mtx);
2649 	mutex_destroy(&arc.mru->mtx);
2650 	mutex_destroy(&arc.mru_ghost->mtx);
2651 	mutex_destroy(&arc.mfu->mtx);
2652 	mutex_destroy(&arc.mfu_ghost->mtx);
2653 
2654 	buf_fini();
2655 }
2656