xref: /titanic_52/usr/src/uts/common/fs/zfs/arc.c (revision 107875b08504ad7f74a2abc64d3862ee8845d5ef)
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 	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
609 		return;
610 
611 	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
612 	    buf->b_hdr->b_state == arc.anon);
613 	arc_cksum_compute(buf);
614 }
615 
616 static void
617 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
618 {
619 	ASSERT(MUTEX_HELD(hash_lock));
620 
621 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
622 	    (ab->b_state != arc.anon)) {
623 		int delta = ab->b_size * ab->b_datacnt;
624 
625 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
626 		mutex_enter(&ab->b_state->mtx);
627 		ASSERT(list_link_active(&ab->b_arc_node));
628 		list_remove(&ab->b_state->list, ab);
629 		if (GHOST_STATE(ab->b_state)) {
630 			ASSERT3U(ab->b_datacnt, ==, 0);
631 			ASSERT3P(ab->b_buf, ==, NULL);
632 			delta = ab->b_size;
633 		}
634 		ASSERT(delta > 0);
635 		ASSERT3U(ab->b_state->lsize, >=, delta);
636 		atomic_add_64(&ab->b_state->lsize, -delta);
637 		mutex_exit(&ab->b_state->mtx);
638 		/* remove the prefetch flag is we get a reference */
639 		if (ab->b_flags & ARC_PREFETCH)
640 			ab->b_flags &= ~ARC_PREFETCH;
641 	}
642 }
643 
644 static int
645 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
646 {
647 	int cnt;
648 
649 	ASSERT(ab->b_state == arc.anon || MUTEX_HELD(hash_lock));
650 	ASSERT(!GHOST_STATE(ab->b_state));
651 
652 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
653 	    (ab->b_state != arc.anon)) {
654 
655 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
656 		mutex_enter(&ab->b_state->mtx);
657 		ASSERT(!list_link_active(&ab->b_arc_node));
658 		list_insert_head(&ab->b_state->list, ab);
659 		ASSERT(ab->b_datacnt > 0);
660 		atomic_add_64(&ab->b_state->lsize, ab->b_size * ab->b_datacnt);
661 		ASSERT3U(ab->b_state->size, >=, ab->b_state->lsize);
662 		mutex_exit(&ab->b_state->mtx);
663 	}
664 	return (cnt);
665 }
666 
667 /*
668  * Move the supplied buffer to the indicated state.  The mutex
669  * for the buffer must be held by the caller.
670  */
671 static void
672 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
673 {
674 	arc_state_t *old_state = ab->b_state;
675 	int refcnt = refcount_count(&ab->b_refcnt);
676 	int from_delta, to_delta;
677 
678 	ASSERT(MUTEX_HELD(hash_lock));
679 	ASSERT(new_state != old_state);
680 	ASSERT(refcnt == 0 || ab->b_datacnt > 0);
681 	ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
682 
683 	from_delta = to_delta = ab->b_datacnt * ab->b_size;
684 
685 	/*
686 	 * If this buffer is evictable, transfer it from the
687 	 * old state list to the new state list.
688 	 */
689 	if (refcnt == 0) {
690 		if (old_state != arc.anon) {
691 			int use_mutex = !MUTEX_HELD(&old_state->mtx);
692 
693 			if (use_mutex)
694 				mutex_enter(&old_state->mtx);
695 
696 			ASSERT(list_link_active(&ab->b_arc_node));
697 			list_remove(&old_state->list, ab);
698 
699 			/*
700 			 * If prefetching out of the ghost cache,
701 			 * we will have a non-null datacnt.
702 			 */
703 			if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
704 				/* ghost elements have a ghost size */
705 				ASSERT(ab->b_buf == NULL);
706 				from_delta = ab->b_size;
707 			}
708 			ASSERT3U(old_state->lsize, >=, from_delta);
709 			atomic_add_64(&old_state->lsize, -from_delta);
710 
711 			if (use_mutex)
712 				mutex_exit(&old_state->mtx);
713 		}
714 		if (new_state != arc.anon) {
715 			int use_mutex = !MUTEX_HELD(&new_state->mtx);
716 
717 			if (use_mutex)
718 				mutex_enter(&new_state->mtx);
719 
720 			list_insert_head(&new_state->list, ab);
721 
722 			/* ghost elements have a ghost size */
723 			if (GHOST_STATE(new_state)) {
724 				ASSERT(ab->b_datacnt == 0);
725 				ASSERT(ab->b_buf == NULL);
726 				to_delta = ab->b_size;
727 			}
728 			atomic_add_64(&new_state->lsize, to_delta);
729 			ASSERT3U(new_state->size + to_delta, >=,
730 			    new_state->lsize);
731 
732 			if (use_mutex)
733 				mutex_exit(&new_state->mtx);
734 		}
735 	}
736 
737 	ASSERT(!BUF_EMPTY(ab));
738 	if (new_state == arc.anon && old_state != arc.anon) {
739 		buf_hash_remove(ab);
740 	}
741 
742 	/* adjust state sizes */
743 	if (to_delta)
744 		atomic_add_64(&new_state->size, to_delta);
745 	if (from_delta) {
746 		ASSERT3U(old_state->size, >=, from_delta);
747 		atomic_add_64(&old_state->size, -from_delta);
748 	}
749 	ab->b_state = new_state;
750 }
751 
752 arc_buf_t *
753 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
754 {
755 	arc_buf_hdr_t *hdr;
756 	arc_buf_t *buf;
757 
758 	ASSERT3U(size, >, 0);
759 	hdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
760 	ASSERT(BUF_EMPTY(hdr));
761 	hdr->b_size = size;
762 	hdr->b_type = type;
763 	hdr->b_spa = spa;
764 	hdr->b_state = arc.anon;
765 	hdr->b_arc_access = 0;
766 	buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
767 	buf->b_hdr = hdr;
768 	buf->b_data = NULL;
769 	buf->b_efunc = NULL;
770 	buf->b_private = NULL;
771 	buf->b_next = NULL;
772 	hdr->b_buf = buf;
773 	arc_get_data_buf(buf);
774 	hdr->b_datacnt = 1;
775 	hdr->b_flags = 0;
776 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
777 	(void) refcount_add(&hdr->b_refcnt, tag);
778 
779 	return (buf);
780 }
781 
782 static arc_buf_t *
783 arc_buf_clone(arc_buf_t *from)
784 {
785 	arc_buf_t *buf;
786 	arc_buf_hdr_t *hdr = from->b_hdr;
787 	uint64_t size = hdr->b_size;
788 
789 	buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
790 	buf->b_hdr = hdr;
791 	buf->b_data = NULL;
792 	buf->b_efunc = NULL;
793 	buf->b_private = NULL;
794 	buf->b_next = hdr->b_buf;
795 	hdr->b_buf = buf;
796 	arc_get_data_buf(buf);
797 	bcopy(from->b_data, buf->b_data, size);
798 	hdr->b_datacnt += 1;
799 	return (buf);
800 }
801 
802 void
803 arc_buf_add_ref(arc_buf_t *buf, void* tag)
804 {
805 	arc_buf_hdr_t *hdr;
806 	kmutex_t *hash_lock;
807 
808 	/*
809 	 * Check to see if this buffer is currently being evicted via
810 	 * arc_do_user_evicts().
811 	 */
812 	mutex_enter(&arc_eviction_mtx);
813 	hdr = buf->b_hdr;
814 	if (hdr == NULL) {
815 		mutex_exit(&arc_eviction_mtx);
816 		return;
817 	}
818 	hash_lock = HDR_LOCK(hdr);
819 	mutex_exit(&arc_eviction_mtx);
820 
821 	mutex_enter(hash_lock);
822 	if (buf->b_data == NULL) {
823 		/*
824 		 * This buffer is evicted.
825 		 */
826 		mutex_exit(hash_lock);
827 		return;
828 	}
829 
830 	ASSERT(buf->b_hdr == hdr);
831 	ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
832 	add_reference(hdr, hash_lock, tag);
833 	arc_access(hdr, hash_lock);
834 	mutex_exit(hash_lock);
835 	atomic_add_64(&arc.hits, 1);
836 }
837 
838 static void
839 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
840 {
841 	arc_buf_t **bufp;
842 
843 	/* free up data associated with the buf */
844 	if (buf->b_data) {
845 		arc_state_t *state = buf->b_hdr->b_state;
846 		uint64_t size = buf->b_hdr->b_size;
847 		arc_buf_contents_t type = buf->b_hdr->b_type;
848 
849 		arc_cksum_verify(buf);
850 		if (!recycle) {
851 			if (type == ARC_BUFC_METADATA) {
852 				zio_buf_free(buf->b_data, size);
853 			} else {
854 				ASSERT(type == ARC_BUFC_DATA);
855 				zio_data_buf_free(buf->b_data, size);
856 			}
857 			atomic_add_64(&arc.size, -size);
858 		}
859 		if (list_link_active(&buf->b_hdr->b_arc_node)) {
860 			ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
861 			ASSERT(state != arc.anon);
862 			ASSERT3U(state->lsize, >=, size);
863 			atomic_add_64(&state->lsize, -size);
864 		}
865 		ASSERT3U(state->size, >=, size);
866 		atomic_add_64(&state->size, -size);
867 		buf->b_data = NULL;
868 		ASSERT(buf->b_hdr->b_datacnt > 0);
869 		buf->b_hdr->b_datacnt -= 1;
870 	}
871 
872 	/* only remove the buf if requested */
873 	if (!all)
874 		return;
875 
876 	/* remove the buf from the hdr list */
877 	for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
878 		continue;
879 	*bufp = buf->b_next;
880 
881 	ASSERT(buf->b_efunc == NULL);
882 
883 	/* clean up the buf */
884 	buf->b_hdr = NULL;
885 	kmem_cache_free(buf_cache, buf);
886 }
887 
888 static void
889 arc_hdr_destroy(arc_buf_hdr_t *hdr)
890 {
891 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
892 	ASSERT3P(hdr->b_state, ==, arc.anon);
893 	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
894 
895 	if (!BUF_EMPTY(hdr)) {
896 		ASSERT(!HDR_IN_HASH_TABLE(hdr));
897 		bzero(&hdr->b_dva, sizeof (dva_t));
898 		hdr->b_birth = 0;
899 		hdr->b_cksum0 = 0;
900 	}
901 	while (hdr->b_buf) {
902 		arc_buf_t *buf = hdr->b_buf;
903 
904 		if (buf->b_efunc) {
905 			mutex_enter(&arc_eviction_mtx);
906 			ASSERT(buf->b_hdr != NULL);
907 			arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
908 			hdr->b_buf = buf->b_next;
909 			buf->b_hdr = &arc_eviction_hdr;
910 			buf->b_next = arc_eviction_list;
911 			arc_eviction_list = buf;
912 			mutex_exit(&arc_eviction_mtx);
913 		} else {
914 			arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
915 		}
916 	}
917 	if (hdr->b_freeze_cksum != NULL) {
918 		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
919 		hdr->b_freeze_cksum = NULL;
920 	}
921 
922 	ASSERT(!list_link_active(&hdr->b_arc_node));
923 	ASSERT3P(hdr->b_hash_next, ==, NULL);
924 	ASSERT3P(hdr->b_acb, ==, NULL);
925 	kmem_cache_free(hdr_cache, hdr);
926 }
927 
928 void
929 arc_buf_free(arc_buf_t *buf, void *tag)
930 {
931 	arc_buf_hdr_t *hdr = buf->b_hdr;
932 	int hashed = hdr->b_state != arc.anon;
933 
934 	ASSERT(buf->b_efunc == NULL);
935 	ASSERT(buf->b_data != NULL);
936 
937 	if (hashed) {
938 		kmutex_t *hash_lock = HDR_LOCK(hdr);
939 
940 		mutex_enter(hash_lock);
941 		(void) remove_reference(hdr, hash_lock, tag);
942 		if (hdr->b_datacnt > 1)
943 			arc_buf_destroy(buf, FALSE, TRUE);
944 		else
945 			hdr->b_flags |= ARC_BUF_AVAILABLE;
946 		mutex_exit(hash_lock);
947 	} else if (HDR_IO_IN_PROGRESS(hdr)) {
948 		int destroy_hdr;
949 		/*
950 		 * We are in the middle of an async write.  Don't destroy
951 		 * this buffer unless the write completes before we finish
952 		 * decrementing the reference count.
953 		 */
954 		mutex_enter(&arc_eviction_mtx);
955 		(void) remove_reference(hdr, NULL, tag);
956 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
957 		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
958 		mutex_exit(&arc_eviction_mtx);
959 		if (destroy_hdr)
960 			arc_hdr_destroy(hdr);
961 	} else {
962 		if (remove_reference(hdr, NULL, tag) > 0) {
963 			ASSERT(HDR_IO_ERROR(hdr));
964 			arc_buf_destroy(buf, FALSE, TRUE);
965 		} else {
966 			arc_hdr_destroy(hdr);
967 		}
968 	}
969 }
970 
971 int
972 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
973 {
974 	arc_buf_hdr_t *hdr = buf->b_hdr;
975 	kmutex_t *hash_lock = HDR_LOCK(hdr);
976 	int no_callback = (buf->b_efunc == NULL);
977 
978 	if (hdr->b_state == arc.anon) {
979 		arc_buf_free(buf, tag);
980 		return (no_callback);
981 	}
982 
983 	mutex_enter(hash_lock);
984 	ASSERT(hdr->b_state != arc.anon);
985 	ASSERT(buf->b_data != NULL);
986 
987 	(void) remove_reference(hdr, hash_lock, tag);
988 	if (hdr->b_datacnt > 1) {
989 		if (no_callback)
990 			arc_buf_destroy(buf, FALSE, TRUE);
991 	} else if (no_callback) {
992 		ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
993 		hdr->b_flags |= ARC_BUF_AVAILABLE;
994 	}
995 	ASSERT(no_callback || hdr->b_datacnt > 1 ||
996 	    refcount_is_zero(&hdr->b_refcnt));
997 	mutex_exit(hash_lock);
998 	return (no_callback);
999 }
1000 
1001 int
1002 arc_buf_size(arc_buf_t *buf)
1003 {
1004 	return (buf->b_hdr->b_size);
1005 }
1006 
1007 /*
1008  * Evict buffers from list until we've removed the specified number of
1009  * bytes.  Move the removed buffers to the appropriate evict state.
1010  * If the recycle flag is set, then attempt to "recycle" a buffer:
1011  * - look for a buffer to evict that is `bytes' long.
1012  * - return the data block from this buffer rather than freeing it.
1013  * This flag is used by callers that are trying to make space for a
1014  * new buffer in a full arc cache.
1015  */
1016 static void *
1017 arc_evict(arc_state_t *state, int64_t bytes, boolean_t recycle,
1018     arc_buf_contents_t type)
1019 {
1020 	arc_state_t *evicted_state;
1021 	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1022 	arc_buf_hdr_t *ab, *ab_prev = NULL;
1023 	kmutex_t *hash_lock;
1024 	boolean_t have_lock;
1025 	void *stolen = NULL;
1026 
1027 	ASSERT(state == arc.mru || state == arc.mfu);
1028 
1029 	evicted_state = (state == arc.mru) ? arc.mru_ghost : arc.mfu_ghost;
1030 
1031 	mutex_enter(&state->mtx);
1032 	mutex_enter(&evicted_state->mtx);
1033 
1034 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
1035 		ab_prev = list_prev(&state->list, ab);
1036 		/* prefetch buffers have a minimum lifespan */
1037 		if (HDR_IO_IN_PROGRESS(ab) ||
1038 		    (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1039 		    lbolt - ab->b_arc_access < arc_min_prefetch_lifespan)) {
1040 			skipped++;
1041 			continue;
1042 		}
1043 		/* "lookahead" for better eviction candidate */
1044 		if (recycle && ab->b_size != bytes &&
1045 		    ab_prev && ab_prev->b_size == bytes)
1046 			continue;
1047 		hash_lock = HDR_LOCK(ab);
1048 		have_lock = MUTEX_HELD(hash_lock);
1049 		if (have_lock || mutex_tryenter(hash_lock)) {
1050 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
1051 			ASSERT(ab->b_datacnt > 0);
1052 			while (ab->b_buf) {
1053 				arc_buf_t *buf = ab->b_buf;
1054 				if (buf->b_data) {
1055 					bytes_evicted += ab->b_size;
1056 					if (recycle && ab->b_type == type &&
1057 					    ab->b_size == bytes) {
1058 						stolen = buf->b_data;
1059 						recycle = FALSE;
1060 					}
1061 				}
1062 				if (buf->b_efunc) {
1063 					mutex_enter(&arc_eviction_mtx);
1064 					arc_buf_destroy(buf,
1065 					    buf->b_data == stolen, FALSE);
1066 					ab->b_buf = buf->b_next;
1067 					buf->b_hdr = &arc_eviction_hdr;
1068 					buf->b_next = arc_eviction_list;
1069 					arc_eviction_list = buf;
1070 					mutex_exit(&arc_eviction_mtx);
1071 				} else {
1072 					arc_buf_destroy(buf,
1073 					    buf->b_data == stolen, TRUE);
1074 				}
1075 			}
1076 			ASSERT(ab->b_datacnt == 0);
1077 			arc_change_state(evicted_state, ab, hash_lock);
1078 			ASSERT(HDR_IN_HASH_TABLE(ab));
1079 			ab->b_flags = ARC_IN_HASH_TABLE;
1080 			DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1081 			if (!have_lock)
1082 				mutex_exit(hash_lock);
1083 			if (bytes >= 0 && bytes_evicted >= bytes)
1084 				break;
1085 		} else {
1086 			missed += 1;
1087 		}
1088 	}
1089 	mutex_exit(&evicted_state->mtx);
1090 	mutex_exit(&state->mtx);
1091 
1092 	if (bytes_evicted < bytes)
1093 		dprintf("only evicted %lld bytes from %x",
1094 		    (longlong_t)bytes_evicted, state);
1095 
1096 	if (skipped)
1097 		atomic_add_64(&arc.evict_skip, skipped);
1098 	if (missed)
1099 		atomic_add_64(&arc.mutex_miss, missed);
1100 	return (stolen);
1101 }
1102 
1103 /*
1104  * Remove buffers from list until we've removed the specified number of
1105  * bytes.  Destroy the buffers that are removed.
1106  */
1107 static void
1108 arc_evict_ghost(arc_state_t *state, int64_t bytes)
1109 {
1110 	arc_buf_hdr_t *ab, *ab_prev;
1111 	kmutex_t *hash_lock;
1112 	uint64_t bytes_deleted = 0;
1113 	uint_t bufs_skipped = 0;
1114 
1115 	ASSERT(GHOST_STATE(state));
1116 top:
1117 	mutex_enter(&state->mtx);
1118 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
1119 		ab_prev = list_prev(&state->list, ab);
1120 		hash_lock = HDR_LOCK(ab);
1121 		if (mutex_tryenter(hash_lock)) {
1122 			ASSERT(!HDR_IO_IN_PROGRESS(ab));
1123 			ASSERT(ab->b_buf == NULL);
1124 			arc_change_state(arc.anon, ab, hash_lock);
1125 			mutex_exit(hash_lock);
1126 			atomic_add_64(&arc.deleted, 1);
1127 			bytes_deleted += ab->b_size;
1128 			arc_hdr_destroy(ab);
1129 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
1130 			if (bytes >= 0 && bytes_deleted >= bytes)
1131 				break;
1132 		} else {
1133 			if (bytes < 0) {
1134 				mutex_exit(&state->mtx);
1135 				mutex_enter(hash_lock);
1136 				mutex_exit(hash_lock);
1137 				goto top;
1138 			}
1139 			bufs_skipped += 1;
1140 		}
1141 	}
1142 	mutex_exit(&state->mtx);
1143 
1144 	if (bufs_skipped) {
1145 		atomic_add_64(&arc.mutex_miss, bufs_skipped);
1146 		ASSERT(bytes >= 0);
1147 	}
1148 
1149 	if (bytes_deleted < bytes)
1150 		dprintf("only deleted %lld bytes from %p",
1151 		    (longlong_t)bytes_deleted, state);
1152 }
1153 
1154 static void
1155 arc_adjust(void)
1156 {
1157 	int64_t top_sz, mru_over, arc_over;
1158 
1159 	top_sz = arc.anon->size + arc.mru->size;
1160 
1161 	if (top_sz > arc.p && arc.mru->lsize > 0) {
1162 		int64_t toevict = MIN(arc.mru->lsize, top_sz-arc.p);
1163 		(void) arc_evict(arc.mru, toevict, FALSE, ARC_BUFC_UNDEF);
1164 		top_sz = arc.anon->size + arc.mru->size;
1165 	}
1166 
1167 	mru_over = top_sz + arc.mru_ghost->size - arc.c;
1168 
1169 	if (mru_over > 0) {
1170 		if (arc.mru_ghost->lsize > 0) {
1171 			int64_t todelete = MIN(arc.mru_ghost->lsize, mru_over);
1172 			arc_evict_ghost(arc.mru_ghost, todelete);
1173 		}
1174 	}
1175 
1176 	if ((arc_over = arc.size - arc.c) > 0) {
1177 		int64_t tbl_over;
1178 
1179 		if (arc.mfu->lsize > 0) {
1180 			int64_t toevict = MIN(arc.mfu->lsize, arc_over);
1181 			(void) arc_evict(arc.mfu, toevict, FALSE,
1182 			    ARC_BUFC_UNDEF);
1183 		}
1184 
1185 		tbl_over = arc.size + arc.mru_ghost->lsize +
1186 		    arc.mfu_ghost->lsize - arc.c*2;
1187 
1188 		if (tbl_over > 0 && arc.mfu_ghost->lsize > 0) {
1189 			int64_t todelete = MIN(arc.mfu_ghost->lsize, tbl_over);
1190 			arc_evict_ghost(arc.mfu_ghost, todelete);
1191 		}
1192 	}
1193 }
1194 
1195 static void
1196 arc_do_user_evicts(void)
1197 {
1198 	mutex_enter(&arc_eviction_mtx);
1199 	while (arc_eviction_list != NULL) {
1200 		arc_buf_t *buf = arc_eviction_list;
1201 		arc_eviction_list = buf->b_next;
1202 		buf->b_hdr = NULL;
1203 		mutex_exit(&arc_eviction_mtx);
1204 
1205 		if (buf->b_efunc != NULL)
1206 			VERIFY(buf->b_efunc(buf) == 0);
1207 
1208 		buf->b_efunc = NULL;
1209 		buf->b_private = NULL;
1210 		kmem_cache_free(buf_cache, buf);
1211 		mutex_enter(&arc_eviction_mtx);
1212 	}
1213 	mutex_exit(&arc_eviction_mtx);
1214 }
1215 
1216 /*
1217  * Flush all *evictable* data from the cache.
1218  * NOTE: this will not touch "active" (i.e. referenced) data.
1219  */
1220 void
1221 arc_flush(void)
1222 {
1223 	while (list_head(&arc.mru->list))
1224 		(void) arc_evict(arc.mru, -1, FALSE, ARC_BUFC_UNDEF);
1225 	while (list_head(&arc.mfu->list))
1226 		(void) arc_evict(arc.mfu, -1, FALSE, ARC_BUFC_UNDEF);
1227 
1228 	arc_evict_ghost(arc.mru_ghost, -1);
1229 	arc_evict_ghost(arc.mfu_ghost, -1);
1230 
1231 	mutex_enter(&arc_reclaim_thr_lock);
1232 	arc_do_user_evicts();
1233 	mutex_exit(&arc_reclaim_thr_lock);
1234 	ASSERT(arc_eviction_list == NULL);
1235 }
1236 
1237 int arc_shrink_shift = 5;		/* log2(fraction of arc to reclaim) */
1238 
1239 void
1240 arc_shrink(void)
1241 {
1242 	if (arc.c > arc.c_min) {
1243 		uint64_t to_free;
1244 
1245 #ifdef _KERNEL
1246 		to_free = MAX(arc.c >> arc_shrink_shift, ptob(needfree));
1247 #else
1248 		to_free = arc.c >> arc_shrink_shift;
1249 #endif
1250 		if (arc.c > arc.c_min + to_free)
1251 			atomic_add_64(&arc.c, -to_free);
1252 		else
1253 			arc.c = arc.c_min;
1254 
1255 		atomic_add_64(&arc.p, -(arc.p >> arc_shrink_shift));
1256 		if (arc.c > arc.size)
1257 			arc.c = MAX(arc.size, arc.c_min);
1258 		if (arc.p > arc.c)
1259 			arc.p = (arc.c >> 1);
1260 		ASSERT(arc.c >= arc.c_min);
1261 		ASSERT((int64_t)arc.p >= 0);
1262 	}
1263 
1264 	if (arc.size > arc.c)
1265 		arc_adjust();
1266 }
1267 
1268 static int
1269 arc_reclaim_needed(void)
1270 {
1271 	uint64_t extra;
1272 
1273 #ifdef _KERNEL
1274 
1275 	if (needfree)
1276 		return (1);
1277 
1278 	/*
1279 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
1280 	 */
1281 	extra = desfree;
1282 
1283 	/*
1284 	 * check that we're out of range of the pageout scanner.  It starts to
1285 	 * schedule paging if freemem is less than lotsfree and needfree.
1286 	 * lotsfree is the high-water mark for pageout, and needfree is the
1287 	 * number of needed free pages.  We add extra pages here to make sure
1288 	 * the scanner doesn't start up while we're freeing memory.
1289 	 */
1290 	if (freemem < lotsfree + needfree + extra)
1291 		return (1);
1292 
1293 	/*
1294 	 * check to make sure that swapfs has enough space so that anon
1295 	 * reservations can still succeeed. anon_resvmem() checks that the
1296 	 * availrmem is greater than swapfs_minfree, and the number of reserved
1297 	 * swap pages.  We also add a bit of extra here just to prevent
1298 	 * circumstances from getting really dire.
1299 	 */
1300 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
1301 		return (1);
1302 
1303 	/*
1304 	 * If zio data pages are being allocated out of a separate heap segment,
1305 	 * then check that the size of available vmem for this area remains
1306 	 * above 1/4th free.  This needs to be done since the size of the
1307 	 * non-default segment is smaller than physical memory, so we could
1308 	 * conceivably run out of VA in that segment before running out of
1309 	 * physical memory.
1310 	 */
1311 	if ((zio_arena != NULL) && (btop(vmem_size(zio_arena, VMEM_FREE)) <
1312 	    (btop(vmem_size(zio_arena, VMEM_FREE | VMEM_ALLOC)) >> 2)))
1313 		return (1);
1314 
1315 #if defined(__i386)
1316 	/*
1317 	 * If we're on an i386 platform, it's possible that we'll exhaust the
1318 	 * kernel heap space before we ever run out of available physical
1319 	 * memory.  Most checks of the size of the heap_area compare against
1320 	 * tune.t_minarmem, which is the minimum available real memory that we
1321 	 * can have in the system.  However, this is generally fixed at 25 pages
1322 	 * which is so low that it's useless.  In this comparison, we seek to
1323 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
1324 	 * heap is allocated.  (Or, in the caclulation, if less than 1/4th is
1325 	 * free)
1326 	 */
1327 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
1328 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
1329 		return (1);
1330 #endif
1331 
1332 #else
1333 	if (spa_get_random(100) == 0)
1334 		return (1);
1335 #endif
1336 	return (0);
1337 }
1338 
1339 static void
1340 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
1341 {
1342 	size_t			i;
1343 	kmem_cache_t		*prev_cache = NULL;
1344 	kmem_cache_t		*prev_data_cache = NULL;
1345 	extern kmem_cache_t	*zio_buf_cache[];
1346 	extern kmem_cache_t	*zio_data_buf_cache[];
1347 
1348 #ifdef _KERNEL
1349 	/*
1350 	 * First purge some DNLC entries, in case the DNLC is using
1351 	 * up too much memory.
1352 	 */
1353 	dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
1354 
1355 #if defined(__i386)
1356 	/*
1357 	 * Reclaim unused memory from all kmem caches.
1358 	 */
1359 	kmem_reap();
1360 #endif
1361 #endif
1362 
1363 	/*
1364 	 * An agressive reclamation will shrink the cache size as well as
1365 	 * reap free buffers from the arc kmem caches.
1366 	 */
1367 	if (strat == ARC_RECLAIM_AGGR)
1368 		arc_shrink();
1369 
1370 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
1371 		if (zio_buf_cache[i] != prev_cache) {
1372 			prev_cache = zio_buf_cache[i];
1373 			kmem_cache_reap_now(zio_buf_cache[i]);
1374 		}
1375 		if (zio_data_buf_cache[i] != prev_data_cache) {
1376 			prev_data_cache = zio_data_buf_cache[i];
1377 			kmem_cache_reap_now(zio_data_buf_cache[i]);
1378 		}
1379 	}
1380 	kmem_cache_reap_now(buf_cache);
1381 	kmem_cache_reap_now(hdr_cache);
1382 }
1383 
1384 static void
1385 arc_reclaim_thread(void)
1386 {
1387 	clock_t			growtime = 0;
1388 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1389 	callb_cpr_t		cpr;
1390 
1391 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1392 
1393 	mutex_enter(&arc_reclaim_thr_lock);
1394 	while (arc_thread_exit == 0) {
1395 		if (arc_reclaim_needed()) {
1396 
1397 			if (arc.no_grow) {
1398 				if (last_reclaim == ARC_RECLAIM_CONS) {
1399 					last_reclaim = ARC_RECLAIM_AGGR;
1400 				} else {
1401 					last_reclaim = ARC_RECLAIM_CONS;
1402 				}
1403 			} else {
1404 				arc.no_grow = TRUE;
1405 				last_reclaim = ARC_RECLAIM_AGGR;
1406 				membar_producer();
1407 			}
1408 
1409 			/* reset the growth delay for every reclaim */
1410 			growtime = lbolt + (arc_grow_retry * hz);
1411 			ASSERT(growtime > 0);
1412 
1413 			arc_kmem_reap_now(last_reclaim);
1414 
1415 		} else if ((growtime > 0) && ((growtime - lbolt) <= 0)) {
1416 			arc.no_grow = FALSE;
1417 		}
1418 
1419 		if (2 * arc.c <
1420 		    arc.size + arc.mru_ghost->size + arc.mfu_ghost->size)
1421 			arc_adjust();
1422 
1423 		if (arc_eviction_list != NULL)
1424 			arc_do_user_evicts();
1425 
1426 		/* block until needed, or one second, whichever is shorter */
1427 		CALLB_CPR_SAFE_BEGIN(&cpr);
1428 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1429 		    &arc_reclaim_thr_lock, (lbolt + hz));
1430 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1431 	}
1432 
1433 	arc_thread_exit = 0;
1434 	cv_broadcast(&arc_reclaim_thr_cv);
1435 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1436 	thread_exit();
1437 }
1438 
1439 /*
1440  * Adapt arc info given the number of bytes we are trying to add and
1441  * the state that we are comming from.  This function is only called
1442  * when we are adding new content to the cache.
1443  */
1444 static void
1445 arc_adapt(int bytes, arc_state_t *state)
1446 {
1447 	int mult;
1448 
1449 	ASSERT(bytes > 0);
1450 	/*
1451 	 * Adapt the target size of the MRU list:
1452 	 *	- if we just hit in the MRU ghost list, then increase
1453 	 *	  the target size of the MRU list.
1454 	 *	- if we just hit in the MFU ghost list, then increase
1455 	 *	  the target size of the MFU list by decreasing the
1456 	 *	  target size of the MRU list.
1457 	 */
1458 	if (state == arc.mru_ghost) {
1459 		mult = ((arc.mru_ghost->size >= arc.mfu_ghost->size) ?
1460 		    1 : (arc.mfu_ghost->size/arc.mru_ghost->size));
1461 
1462 		arc.p = MIN(arc.c, arc.p + bytes * mult);
1463 	} else if (state == arc.mfu_ghost) {
1464 		mult = ((arc.mfu_ghost->size >= arc.mru_ghost->size) ?
1465 		    1 : (arc.mru_ghost->size/arc.mfu_ghost->size));
1466 
1467 		arc.p = MAX(0, (int64_t)arc.p - bytes * mult);
1468 	}
1469 	ASSERT((int64_t)arc.p >= 0);
1470 
1471 	if (arc_reclaim_needed()) {
1472 		cv_signal(&arc_reclaim_thr_cv);
1473 		return;
1474 	}
1475 
1476 	if (arc.no_grow)
1477 		return;
1478 
1479 	if (arc.c >= arc.c_max)
1480 		return;
1481 
1482 	/*
1483 	 * If we're within (2 * maxblocksize) bytes of the target
1484 	 * cache size, increment the target cache size
1485 	 */
1486 	if (arc.size > arc.c - (2ULL << SPA_MAXBLOCKSHIFT)) {
1487 		atomic_add_64(&arc.c, (int64_t)bytes);
1488 		if (arc.c > arc.c_max)
1489 			arc.c = arc.c_max;
1490 		else if (state == arc.anon)
1491 			atomic_add_64(&arc.p, (int64_t)bytes);
1492 		if (arc.p > arc.c)
1493 			arc.p = arc.c;
1494 	}
1495 	ASSERT((int64_t)arc.p >= 0);
1496 }
1497 
1498 /*
1499  * Check if the cache has reached its limits and eviction is required
1500  * prior to insert.
1501  */
1502 static int
1503 arc_evict_needed()
1504 {
1505 	if (arc_reclaim_needed())
1506 		return (1);
1507 
1508 	return (arc.size > arc.c);
1509 }
1510 
1511 /*
1512  * The buffer, supplied as the first argument, needs a data block.
1513  * So, if we are at cache max, determine which cache should be victimized.
1514  * We have the following cases:
1515  *
1516  * 1. Insert for MRU, p > sizeof(arc.anon + arc.mru) ->
1517  * In this situation if we're out of space, but the resident size of the MFU is
1518  * under the limit, victimize the MFU cache to satisfy this insertion request.
1519  *
1520  * 2. Insert for MRU, p <= sizeof(arc.anon + arc.mru) ->
1521  * Here, we've used up all of the available space for the MRU, so we need to
1522  * evict from our own cache instead.  Evict from the set of resident MRU
1523  * entries.
1524  *
1525  * 3. Insert for MFU (c - p) > sizeof(arc.mfu) ->
1526  * c minus p represents the MFU space in the cache, since p is the size of the
1527  * cache that is dedicated to the MRU.  In this situation there's still space on
1528  * the MFU side, so the MRU side needs to be victimized.
1529  *
1530  * 4. Insert for MFU (c - p) < sizeof(arc.mfu) ->
1531  * MFU's resident set is consuming more space than it has been allotted.  In
1532  * this situation, we must victimize our own cache, the MFU, for this insertion.
1533  */
1534 static void
1535 arc_get_data_buf(arc_buf_t *buf)
1536 {
1537 	arc_state_t		*state = buf->b_hdr->b_state;
1538 	uint64_t		size = buf->b_hdr->b_size;
1539 	arc_buf_contents_t	type = buf->b_hdr->b_type;
1540 
1541 	arc_adapt(size, state);
1542 
1543 	/*
1544 	 * We have not yet reached cache maximum size,
1545 	 * just allocate a new buffer.
1546 	 */
1547 	if (!arc_evict_needed()) {
1548 		if (type == ARC_BUFC_METADATA) {
1549 			buf->b_data = zio_buf_alloc(size);
1550 		} else {
1551 			ASSERT(type == ARC_BUFC_DATA);
1552 			buf->b_data = zio_data_buf_alloc(size);
1553 		}
1554 		atomic_add_64(&arc.size, size);
1555 		goto out;
1556 	}
1557 
1558 	/*
1559 	 * If we are prefetching from the mfu ghost list, this buffer
1560 	 * will end up on the mru list; so steal space from there.
1561 	 */
1562 	if (state == arc.mfu_ghost)
1563 		state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc.mru : arc.mfu;
1564 	else if (state == arc.mru_ghost)
1565 		state = arc.mru;
1566 
1567 	if (state == arc.mru || state == arc.anon) {
1568 		uint64_t mru_used = arc.anon->size + arc.mru->size;
1569 		state = (arc.p > mru_used) ? arc.mfu : arc.mru;
1570 	} else {
1571 		/* MFU cases */
1572 		uint64_t mfu_space = arc.c - arc.p;
1573 		state =  (mfu_space > arc.mfu->size) ? arc.mru : arc.mfu;
1574 	}
1575 	if ((buf->b_data = arc_evict(state, size, TRUE, type)) == NULL) {
1576 		if (type == ARC_BUFC_METADATA) {
1577 			buf->b_data = zio_buf_alloc(size);
1578 		} else {
1579 			ASSERT(type == ARC_BUFC_DATA);
1580 			buf->b_data = zio_data_buf_alloc(size);
1581 		}
1582 		atomic_add_64(&arc.size, size);
1583 		atomic_add_64(&arc.recycle_miss, 1);
1584 	}
1585 	ASSERT(buf->b_data != NULL);
1586 out:
1587 	/*
1588 	 * Update the state size.  Note that ghost states have a
1589 	 * "ghost size" and so don't need to be updated.
1590 	 */
1591 	if (!GHOST_STATE(buf->b_hdr->b_state)) {
1592 		arc_buf_hdr_t *hdr = buf->b_hdr;
1593 
1594 		atomic_add_64(&hdr->b_state->size, size);
1595 		if (list_link_active(&hdr->b_arc_node)) {
1596 			ASSERT(refcount_is_zero(&hdr->b_refcnt));
1597 			atomic_add_64(&hdr->b_state->lsize, size);
1598 		}
1599 		/*
1600 		 * If we are growing the cache, and we are adding anonymous
1601 		 * data, and we have outgrown arc.p, update arc.p
1602 		 */
1603 		if (arc.size < arc.c && hdr->b_state == arc.anon &&
1604 		    arc.anon->size + arc.mru->size > arc.p)
1605 			arc.p = MIN(arc.c, arc.p + size);
1606 	}
1607 }
1608 
1609 /*
1610  * This routine is called whenever a buffer is accessed.
1611  * NOTE: the hash lock is dropped in this function.
1612  */
1613 static void
1614 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
1615 {
1616 	ASSERT(MUTEX_HELD(hash_lock));
1617 
1618 	if (buf->b_state == arc.anon) {
1619 		/*
1620 		 * This buffer is not in the cache, and does not
1621 		 * appear in our "ghost" list.  Add the new buffer
1622 		 * to the MRU state.
1623 		 */
1624 
1625 		ASSERT(buf->b_arc_access == 0);
1626 		buf->b_arc_access = lbolt;
1627 		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1628 		arc_change_state(arc.mru, buf, hash_lock);
1629 
1630 	} else if (buf->b_state == arc.mru) {
1631 		/*
1632 		 * If this buffer is here because of a prefetch, then either:
1633 		 * - clear the flag if this is a "referencing" read
1634 		 *   (any subsequent access will bump this into the MFU state).
1635 		 * or
1636 		 * - move the buffer to the head of the list if this is
1637 		 *   another prefetch (to make it less likely to be evicted).
1638 		 */
1639 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1640 			if (refcount_count(&buf->b_refcnt) == 0) {
1641 				ASSERT(list_link_active(&buf->b_arc_node));
1642 				mutex_enter(&arc.mru->mtx);
1643 				list_remove(&arc.mru->list, buf);
1644 				list_insert_head(&arc.mru->list, buf);
1645 				mutex_exit(&arc.mru->mtx);
1646 			} else {
1647 				buf->b_flags &= ~ARC_PREFETCH;
1648 				atomic_add_64(&arc.mru->hits, 1);
1649 			}
1650 			buf->b_arc_access = lbolt;
1651 			return;
1652 		}
1653 
1654 		/*
1655 		 * This buffer has been "accessed" only once so far,
1656 		 * but it is still in the cache. Move it to the MFU
1657 		 * state.
1658 		 */
1659 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
1660 			/*
1661 			 * More than 125ms have passed since we
1662 			 * instantiated this buffer.  Move it to the
1663 			 * most frequently used state.
1664 			 */
1665 			buf->b_arc_access = lbolt;
1666 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1667 			arc_change_state(arc.mfu, buf, hash_lock);
1668 		}
1669 		atomic_add_64(&arc.mru->hits, 1);
1670 	} else if (buf->b_state == arc.mru_ghost) {
1671 		arc_state_t	*new_state;
1672 		/*
1673 		 * This buffer has been "accessed" recently, but
1674 		 * was evicted from the cache.  Move it to the
1675 		 * MFU state.
1676 		 */
1677 
1678 		if (buf->b_flags & ARC_PREFETCH) {
1679 			new_state = arc.mru;
1680 			if (refcount_count(&buf->b_refcnt) > 0)
1681 				buf->b_flags &= ~ARC_PREFETCH;
1682 			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
1683 		} else {
1684 			new_state = arc.mfu;
1685 			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1686 		}
1687 
1688 		buf->b_arc_access = lbolt;
1689 		arc_change_state(new_state, buf, hash_lock);
1690 
1691 		atomic_add_64(&arc.mru_ghost->hits, 1);
1692 	} else if (buf->b_state == arc.mfu) {
1693 		/*
1694 		 * This buffer has been accessed more than once and is
1695 		 * still in the cache.  Keep it in the MFU state.
1696 		 *
1697 		 * NOTE: an add_reference() that occurred when we did
1698 		 * the arc_read() will have kicked this off the list.
1699 		 * If it was a prefetch, we will explicitly move it to
1700 		 * the head of the list now.
1701 		 */
1702 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1703 			ASSERT(refcount_count(&buf->b_refcnt) == 0);
1704 			ASSERT(list_link_active(&buf->b_arc_node));
1705 			mutex_enter(&arc.mfu->mtx);
1706 			list_remove(&arc.mfu->list, buf);
1707 			list_insert_head(&arc.mfu->list, buf);
1708 			mutex_exit(&arc.mfu->mtx);
1709 		}
1710 		atomic_add_64(&arc.mfu->hits, 1);
1711 		buf->b_arc_access = lbolt;
1712 	} else if (buf->b_state == arc.mfu_ghost) {
1713 		arc_state_t	*new_state = arc.mfu;
1714 		/*
1715 		 * This buffer has been accessed more than once but has
1716 		 * been evicted from the cache.  Move it back to the
1717 		 * MFU state.
1718 		 */
1719 
1720 		if (buf->b_flags & ARC_PREFETCH) {
1721 			/*
1722 			 * This is a prefetch access...
1723 			 * move this block back to the MRU state.
1724 			 */
1725 			ASSERT3U(refcount_count(&buf->b_refcnt), ==, 0);
1726 			new_state = arc.mru;
1727 		}
1728 
1729 		buf->b_arc_access = lbolt;
1730 		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
1731 		arc_change_state(new_state, buf, hash_lock);
1732 
1733 		atomic_add_64(&arc.mfu_ghost->hits, 1);
1734 	} else {
1735 		ASSERT(!"invalid arc state");
1736 	}
1737 }
1738 
1739 /* a generic arc_done_func_t which you can use */
1740 /* ARGSUSED */
1741 void
1742 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
1743 {
1744 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
1745 	VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1746 }
1747 
1748 /* a generic arc_done_func_t which you can use */
1749 void
1750 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
1751 {
1752 	arc_buf_t **bufp = arg;
1753 	if (zio && zio->io_error) {
1754 		VERIFY(arc_buf_remove_ref(buf, arg) == 1);
1755 		*bufp = NULL;
1756 	} else {
1757 		*bufp = buf;
1758 	}
1759 }
1760 
1761 static void
1762 arc_read_done(zio_t *zio)
1763 {
1764 	arc_buf_hdr_t	*hdr, *found;
1765 	arc_buf_t	*buf;
1766 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
1767 	kmutex_t	*hash_lock;
1768 	arc_callback_t	*callback_list, *acb;
1769 	int		freeable = FALSE;
1770 
1771 	buf = zio->io_private;
1772 	hdr = buf->b_hdr;
1773 
1774 	/*
1775 	 * The hdr was inserted into hash-table and removed from lists
1776 	 * prior to starting I/O.  We should find this header, since
1777 	 * it's in the hash table, and it should be legit since it's
1778 	 * not possible to evict it during the I/O.  The only possible
1779 	 * reason for it not to be found is if we were freed during the
1780 	 * read.
1781 	 */
1782 	found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
1783 	    &hash_lock);
1784 
1785 	ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
1786 	    (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))));
1787 
1788 	/* byteswap if necessary */
1789 	callback_list = hdr->b_acb;
1790 	ASSERT(callback_list != NULL);
1791 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && callback_list->acb_byteswap)
1792 		callback_list->acb_byteswap(buf->b_data, hdr->b_size);
1793 
1794 	arc_cksum_compute(buf);
1795 
1796 	/* create copies of the data buffer for the callers */
1797 	abuf = buf;
1798 	for (acb = callback_list; acb; acb = acb->acb_next) {
1799 		if (acb->acb_done) {
1800 			if (abuf == NULL)
1801 				abuf = arc_buf_clone(buf);
1802 			acb->acb_buf = abuf;
1803 			abuf = NULL;
1804 		}
1805 	}
1806 	hdr->b_acb = NULL;
1807 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
1808 	ASSERT(!HDR_BUF_AVAILABLE(hdr));
1809 	if (abuf == buf)
1810 		hdr->b_flags |= ARC_BUF_AVAILABLE;
1811 
1812 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
1813 
1814 	if (zio->io_error != 0) {
1815 		hdr->b_flags |= ARC_IO_ERROR;
1816 		if (hdr->b_state != arc.anon)
1817 			arc_change_state(arc.anon, hdr, hash_lock);
1818 		if (HDR_IN_HASH_TABLE(hdr))
1819 			buf_hash_remove(hdr);
1820 		freeable = refcount_is_zero(&hdr->b_refcnt);
1821 		/* convert checksum errors into IO errors */
1822 		if (zio->io_error == ECKSUM)
1823 			zio->io_error = EIO;
1824 	}
1825 
1826 	/*
1827 	 * Broadcast before we drop the hash_lock to avoid the possibility
1828 	 * that the hdr (and hence the cv) might be freed before we get to
1829 	 * the cv_broadcast().
1830 	 */
1831 	cv_broadcast(&hdr->b_cv);
1832 
1833 	if (hash_lock) {
1834 		/*
1835 		 * Only call arc_access on anonymous buffers.  This is because
1836 		 * if we've issued an I/O for an evicted buffer, we've already
1837 		 * called arc_access (to prevent any simultaneous readers from
1838 		 * getting confused).
1839 		 */
1840 		if (zio->io_error == 0 && hdr->b_state == arc.anon)
1841 			arc_access(hdr, hash_lock);
1842 		mutex_exit(hash_lock);
1843 	} else {
1844 		/*
1845 		 * This block was freed while we waited for the read to
1846 		 * complete.  It has been removed from the hash table and
1847 		 * moved to the anonymous state (so that it won't show up
1848 		 * in the cache).
1849 		 */
1850 		ASSERT3P(hdr->b_state, ==, arc.anon);
1851 		freeable = refcount_is_zero(&hdr->b_refcnt);
1852 	}
1853 
1854 	/* execute each callback and free its structure */
1855 	while ((acb = callback_list) != NULL) {
1856 		if (acb->acb_done)
1857 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
1858 
1859 		if (acb->acb_zio_dummy != NULL) {
1860 			acb->acb_zio_dummy->io_error = zio->io_error;
1861 			zio_nowait(acb->acb_zio_dummy);
1862 		}
1863 
1864 		callback_list = acb->acb_next;
1865 		kmem_free(acb, sizeof (arc_callback_t));
1866 	}
1867 
1868 	if (freeable)
1869 		arc_hdr_destroy(hdr);
1870 }
1871 
1872 /*
1873  * "Read" the block block at the specified DVA (in bp) via the
1874  * cache.  If the block is found in the cache, invoke the provided
1875  * callback immediately and return.  Note that the `zio' parameter
1876  * in the callback will be NULL in this case, since no IO was
1877  * required.  If the block is not in the cache pass the read request
1878  * on to the spa with a substitute callback function, so that the
1879  * requested block will be added to the cache.
1880  *
1881  * If a read request arrives for a block that has a read in-progress,
1882  * either wait for the in-progress read to complete (and return the
1883  * results); or, if this is a read with a "done" func, add a record
1884  * to the read to invoke the "done" func when the read completes,
1885  * and return; or just return.
1886  *
1887  * arc_read_done() will invoke all the requested "done" functions
1888  * for readers of this block.
1889  */
1890 int
1891 arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_byteswap_func_t *swap,
1892     arc_done_func_t *done, void *private, int priority, int flags,
1893     uint32_t *arc_flags, zbookmark_t *zb)
1894 {
1895 	arc_buf_hdr_t *hdr;
1896 	arc_buf_t *buf;
1897 	kmutex_t *hash_lock;
1898 	zio_t	*rzio;
1899 
1900 top:
1901 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
1902 	if (hdr && hdr->b_datacnt > 0) {
1903 
1904 		*arc_flags |= ARC_CACHED;
1905 
1906 		if (HDR_IO_IN_PROGRESS(hdr)) {
1907 
1908 			if (*arc_flags & ARC_WAIT) {
1909 				cv_wait(&hdr->b_cv, hash_lock);
1910 				mutex_exit(hash_lock);
1911 				goto top;
1912 			}
1913 			ASSERT(*arc_flags & ARC_NOWAIT);
1914 
1915 			if (done) {
1916 				arc_callback_t	*acb = NULL;
1917 
1918 				acb = kmem_zalloc(sizeof (arc_callback_t),
1919 				    KM_SLEEP);
1920 				acb->acb_done = done;
1921 				acb->acb_private = private;
1922 				acb->acb_byteswap = swap;
1923 				if (pio != NULL)
1924 					acb->acb_zio_dummy = zio_null(pio,
1925 					    spa, NULL, NULL, flags);
1926 
1927 				ASSERT(acb->acb_done != NULL);
1928 				acb->acb_next = hdr->b_acb;
1929 				hdr->b_acb = acb;
1930 				add_reference(hdr, hash_lock, private);
1931 				mutex_exit(hash_lock);
1932 				return (0);
1933 			}
1934 			mutex_exit(hash_lock);
1935 			return (0);
1936 		}
1937 
1938 		ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
1939 
1940 		if (done) {
1941 			add_reference(hdr, hash_lock, private);
1942 			/*
1943 			 * If this block is already in use, create a new
1944 			 * copy of the data so that we will be guaranteed
1945 			 * that arc_release() will always succeed.
1946 			 */
1947 			buf = hdr->b_buf;
1948 			ASSERT(buf);
1949 			ASSERT(buf->b_data);
1950 			if (HDR_BUF_AVAILABLE(hdr)) {
1951 				ASSERT(buf->b_efunc == NULL);
1952 				hdr->b_flags &= ~ARC_BUF_AVAILABLE;
1953 			} else {
1954 				buf = arc_buf_clone(buf);
1955 			}
1956 		} else if (*arc_flags & ARC_PREFETCH &&
1957 		    refcount_count(&hdr->b_refcnt) == 0) {
1958 			hdr->b_flags |= ARC_PREFETCH;
1959 		}
1960 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1961 		arc_access(hdr, hash_lock);
1962 		mutex_exit(hash_lock);
1963 		atomic_add_64(&arc.hits, 1);
1964 		if (done)
1965 			done(NULL, buf, private);
1966 	} else {
1967 		uint64_t size = BP_GET_LSIZE(bp);
1968 		arc_callback_t	*acb;
1969 
1970 		if (hdr == NULL) {
1971 			/* this block is not in the cache */
1972 			arc_buf_hdr_t	*exists;
1973 			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
1974 			buf = arc_buf_alloc(spa, size, private, type);
1975 			hdr = buf->b_hdr;
1976 			hdr->b_dva = *BP_IDENTITY(bp);
1977 			hdr->b_birth = bp->blk_birth;
1978 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
1979 			exists = buf_hash_insert(hdr, &hash_lock);
1980 			if (exists) {
1981 				/* somebody beat us to the hash insert */
1982 				mutex_exit(hash_lock);
1983 				bzero(&hdr->b_dva, sizeof (dva_t));
1984 				hdr->b_birth = 0;
1985 				hdr->b_cksum0 = 0;
1986 				(void) arc_buf_remove_ref(buf, private);
1987 				goto top; /* restart the IO request */
1988 			}
1989 			/* if this is a prefetch, we don't have a reference */
1990 			if (*arc_flags & ARC_PREFETCH) {
1991 				(void) remove_reference(hdr, hash_lock,
1992 				    private);
1993 				hdr->b_flags |= ARC_PREFETCH;
1994 			}
1995 			if (BP_GET_LEVEL(bp) > 0)
1996 				hdr->b_flags |= ARC_INDIRECT;
1997 		} else {
1998 			/* this block is in the ghost cache */
1999 			ASSERT(GHOST_STATE(hdr->b_state));
2000 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2001 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 0);
2002 			ASSERT(hdr->b_buf == NULL);
2003 
2004 			/* if this is a prefetch, we don't have a reference */
2005 			if (*arc_flags & ARC_PREFETCH)
2006 				hdr->b_flags |= ARC_PREFETCH;
2007 			else
2008 				add_reference(hdr, hash_lock, private);
2009 			buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
2010 			buf->b_hdr = hdr;
2011 			buf->b_data = NULL;
2012 			buf->b_efunc = NULL;
2013 			buf->b_private = NULL;
2014 			buf->b_next = NULL;
2015 			hdr->b_buf = buf;
2016 			arc_get_data_buf(buf);
2017 			ASSERT(hdr->b_datacnt == 0);
2018 			hdr->b_datacnt = 1;
2019 
2020 		}
2021 
2022 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2023 		acb->acb_done = done;
2024 		acb->acb_private = private;
2025 		acb->acb_byteswap = swap;
2026 
2027 		ASSERT(hdr->b_acb == NULL);
2028 		hdr->b_acb = acb;
2029 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
2030 
2031 		/*
2032 		 * If the buffer has been evicted, migrate it to a present state
2033 		 * before issuing the I/O.  Once we drop the hash-table lock,
2034 		 * the header will be marked as I/O in progress and have an
2035 		 * attached buffer.  At this point, anybody who finds this
2036 		 * buffer ought to notice that it's legit but has a pending I/O.
2037 		 */
2038 
2039 		if (GHOST_STATE(hdr->b_state))
2040 			arc_access(hdr, hash_lock);
2041 		mutex_exit(hash_lock);
2042 
2043 		ASSERT3U(hdr->b_size, ==, size);
2044 		DTRACE_PROBE3(arc__miss, blkptr_t *, bp, uint64_t, size,
2045 		    zbookmark_t *, zb);
2046 		atomic_add_64(&arc.misses, 1);
2047 
2048 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
2049 		    arc_read_done, buf, priority, flags, zb);
2050 
2051 		if (*arc_flags & ARC_WAIT)
2052 			return (zio_wait(rzio));
2053 
2054 		ASSERT(*arc_flags & ARC_NOWAIT);
2055 		zio_nowait(rzio);
2056 	}
2057 	return (0);
2058 }
2059 
2060 /*
2061  * arc_read() variant to support pool traversal.  If the block is already
2062  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
2063  * The idea is that we don't want pool traversal filling up memory, but
2064  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
2065  */
2066 int
2067 arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
2068 {
2069 	arc_buf_hdr_t *hdr;
2070 	kmutex_t *hash_mtx;
2071 	int rc = 0;
2072 
2073 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
2074 
2075 	if (hdr && hdr->b_datacnt > 0 && !HDR_IO_IN_PROGRESS(hdr)) {
2076 		arc_buf_t *buf = hdr->b_buf;
2077 
2078 		ASSERT(buf);
2079 		while (buf->b_data == NULL) {
2080 			buf = buf->b_next;
2081 			ASSERT(buf);
2082 		}
2083 		bcopy(buf->b_data, data, hdr->b_size);
2084 	} else {
2085 		rc = ENOENT;
2086 	}
2087 
2088 	if (hash_mtx)
2089 		mutex_exit(hash_mtx);
2090 
2091 	return (rc);
2092 }
2093 
2094 void
2095 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
2096 {
2097 	ASSERT(buf->b_hdr != NULL);
2098 	ASSERT(buf->b_hdr->b_state != arc.anon);
2099 	ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
2100 	buf->b_efunc = func;
2101 	buf->b_private = private;
2102 }
2103 
2104 /*
2105  * This is used by the DMU to let the ARC know that a buffer is
2106  * being evicted, so the ARC should clean up.  If this arc buf
2107  * is not yet in the evicted state, it will be put there.
2108  */
2109 int
2110 arc_buf_evict(arc_buf_t *buf)
2111 {
2112 	arc_buf_hdr_t *hdr;
2113 	kmutex_t *hash_lock;
2114 	arc_buf_t **bufp;
2115 
2116 	mutex_enter(&arc_eviction_mtx);
2117 	hdr = buf->b_hdr;
2118 	if (hdr == NULL) {
2119 		/*
2120 		 * We are in arc_do_user_evicts().
2121 		 */
2122 		ASSERT(buf->b_data == NULL);
2123 		mutex_exit(&arc_eviction_mtx);
2124 		return (0);
2125 	}
2126 	hash_lock = HDR_LOCK(hdr);
2127 	mutex_exit(&arc_eviction_mtx);
2128 
2129 	mutex_enter(hash_lock);
2130 
2131 	if (buf->b_data == NULL) {
2132 		/*
2133 		 * We are on the eviction list.
2134 		 */
2135 		mutex_exit(hash_lock);
2136 		mutex_enter(&arc_eviction_mtx);
2137 		if (buf->b_hdr == NULL) {
2138 			/*
2139 			 * We are already in arc_do_user_evicts().
2140 			 */
2141 			mutex_exit(&arc_eviction_mtx);
2142 			return (0);
2143 		} else {
2144 			arc_buf_t copy = *buf; /* structure assignment */
2145 			/*
2146 			 * Process this buffer now
2147 			 * but let arc_do_user_evicts() do the reaping.
2148 			 */
2149 			buf->b_efunc = NULL;
2150 			mutex_exit(&arc_eviction_mtx);
2151 			VERIFY(copy.b_efunc(&copy) == 0);
2152 			return (1);
2153 		}
2154 	}
2155 
2156 	ASSERT(buf->b_hdr == hdr);
2157 	ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
2158 	ASSERT(hdr->b_state == arc.mru || hdr->b_state == arc.mfu);
2159 
2160 	/*
2161 	 * Pull this buffer off of the hdr
2162 	 */
2163 	bufp = &hdr->b_buf;
2164 	while (*bufp != buf)
2165 		bufp = &(*bufp)->b_next;
2166 	*bufp = buf->b_next;
2167 
2168 	ASSERT(buf->b_data != NULL);
2169 	arc_buf_destroy(buf, FALSE, FALSE);
2170 
2171 	if (hdr->b_datacnt == 0) {
2172 		arc_state_t *old_state = hdr->b_state;
2173 		arc_state_t *evicted_state;
2174 
2175 		ASSERT(refcount_is_zero(&hdr->b_refcnt));
2176 
2177 		evicted_state =
2178 		    (old_state == arc.mru) ? arc.mru_ghost : arc.mfu_ghost;
2179 
2180 		mutex_enter(&old_state->mtx);
2181 		mutex_enter(&evicted_state->mtx);
2182 
2183 		arc_change_state(evicted_state, hdr, hash_lock);
2184 		ASSERT(HDR_IN_HASH_TABLE(hdr));
2185 		hdr->b_flags = ARC_IN_HASH_TABLE;
2186 
2187 		mutex_exit(&evicted_state->mtx);
2188 		mutex_exit(&old_state->mtx);
2189 	}
2190 	mutex_exit(hash_lock);
2191 
2192 	VERIFY(buf->b_efunc(buf) == 0);
2193 	buf->b_efunc = NULL;
2194 	buf->b_private = NULL;
2195 	buf->b_hdr = NULL;
2196 	kmem_cache_free(buf_cache, buf);
2197 	return (1);
2198 }
2199 
2200 /*
2201  * Release this buffer from the cache.  This must be done
2202  * after a read and prior to modifying the buffer contents.
2203  * If the buffer has more than one reference, we must make
2204  * make a new hdr for the buffer.
2205  */
2206 void
2207 arc_release(arc_buf_t *buf, void *tag)
2208 {
2209 	arc_buf_hdr_t *hdr = buf->b_hdr;
2210 	kmutex_t *hash_lock = HDR_LOCK(hdr);
2211 
2212 	/* this buffer is not on any list */
2213 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
2214 
2215 	if (hdr->b_state == arc.anon) {
2216 		/* this buffer is already released */
2217 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
2218 		ASSERT(BUF_EMPTY(hdr));
2219 		ASSERT(buf->b_efunc == NULL);
2220 		arc_buf_thaw(buf);
2221 		return;
2222 	}
2223 
2224 	mutex_enter(hash_lock);
2225 
2226 	/*
2227 	 * Do we have more than one buf?
2228 	 */
2229 	if (hdr->b_buf != buf || buf->b_next != NULL) {
2230 		arc_buf_hdr_t *nhdr;
2231 		arc_buf_t **bufp;
2232 		uint64_t blksz = hdr->b_size;
2233 		spa_t *spa = hdr->b_spa;
2234 		arc_buf_contents_t type = hdr->b_type;
2235 
2236 		ASSERT(hdr->b_datacnt > 1);
2237 		/*
2238 		 * Pull the data off of this buf and attach it to
2239 		 * a new anonymous buf.
2240 		 */
2241 		(void) remove_reference(hdr, hash_lock, tag);
2242 		bufp = &hdr->b_buf;
2243 		while (*bufp != buf)
2244 			bufp = &(*bufp)->b_next;
2245 		*bufp = (*bufp)->b_next;
2246 
2247 		ASSERT3U(hdr->b_state->size, >=, hdr->b_size);
2248 		atomic_add_64(&hdr->b_state->size, -hdr->b_size);
2249 		if (refcount_is_zero(&hdr->b_refcnt)) {
2250 			ASSERT3U(hdr->b_state->lsize, >=, hdr->b_size);
2251 			atomic_add_64(&hdr->b_state->lsize, -hdr->b_size);
2252 		}
2253 		hdr->b_datacnt -= 1;
2254 
2255 		mutex_exit(hash_lock);
2256 
2257 		nhdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
2258 		nhdr->b_size = blksz;
2259 		nhdr->b_spa = spa;
2260 		nhdr->b_type = type;
2261 		nhdr->b_buf = buf;
2262 		nhdr->b_state = arc.anon;
2263 		nhdr->b_arc_access = 0;
2264 		nhdr->b_flags = 0;
2265 		nhdr->b_datacnt = 1;
2266 		if (hdr->b_freeze_cksum != NULL) {
2267 			nhdr->b_freeze_cksum =
2268 			    kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
2269 			*nhdr->b_freeze_cksum = *hdr->b_freeze_cksum;
2270 		}
2271 		buf->b_hdr = nhdr;
2272 		buf->b_next = NULL;
2273 		(void) refcount_add(&nhdr->b_refcnt, tag);
2274 		atomic_add_64(&arc.anon->size, blksz);
2275 
2276 		hdr = nhdr;
2277 	} else {
2278 		ASSERT(refcount_count(&hdr->b_refcnt) == 1);
2279 		ASSERT(!list_link_active(&hdr->b_arc_node));
2280 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2281 		arc_change_state(arc.anon, hdr, hash_lock);
2282 		hdr->b_arc_access = 0;
2283 		mutex_exit(hash_lock);
2284 		bzero(&hdr->b_dva, sizeof (dva_t));
2285 		hdr->b_birth = 0;
2286 		hdr->b_cksum0 = 0;
2287 	}
2288 	buf->b_efunc = NULL;
2289 	buf->b_private = NULL;
2290 	arc_buf_thaw(buf);
2291 }
2292 
2293 int
2294 arc_released(arc_buf_t *buf)
2295 {
2296 	return (buf->b_data != NULL && buf->b_hdr->b_state == arc.anon);
2297 }
2298 
2299 int
2300 arc_has_callback(arc_buf_t *buf)
2301 {
2302 	return (buf->b_efunc != NULL);
2303 }
2304 
2305 #ifdef ZFS_DEBUG
2306 int
2307 arc_referenced(arc_buf_t *buf)
2308 {
2309 	return (refcount_count(&buf->b_hdr->b_refcnt));
2310 }
2311 #endif
2312 
2313 static void
2314 arc_write_done(zio_t *zio)
2315 {
2316 	arc_buf_t *buf;
2317 	arc_buf_hdr_t *hdr;
2318 	arc_callback_t *acb;
2319 
2320 	buf = zio->io_private;
2321 	hdr = buf->b_hdr;
2322 	acb = hdr->b_acb;
2323 	hdr->b_acb = NULL;
2324 	ASSERT(acb != NULL);
2325 
2326 	/* this buffer is on no lists and is not in the hash table */
2327 	ASSERT3P(hdr->b_state, ==, arc.anon);
2328 
2329 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
2330 	hdr->b_birth = zio->io_bp->blk_birth;
2331 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
2332 	/*
2333 	 * If the block to be written was all-zero, we may have
2334 	 * compressed it away.  In this case no write was performed
2335 	 * so there will be no dva/birth-date/checksum.  The buffer
2336 	 * must therefor remain anonymous (and uncached).
2337 	 */
2338 	if (!BUF_EMPTY(hdr)) {
2339 		arc_buf_hdr_t *exists;
2340 		kmutex_t *hash_lock;
2341 
2342 		arc_cksum_verify(buf);
2343 
2344 		exists = buf_hash_insert(hdr, &hash_lock);
2345 		if (exists) {
2346 			/*
2347 			 * This can only happen if we overwrite for
2348 			 * sync-to-convergence, because we remove
2349 			 * buffers from the hash table when we arc_free().
2350 			 */
2351 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
2352 			    BP_IDENTITY(zio->io_bp)));
2353 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
2354 			    zio->io_bp->blk_birth);
2355 
2356 			ASSERT(refcount_is_zero(&exists->b_refcnt));
2357 			arc_change_state(arc.anon, exists, hash_lock);
2358 			mutex_exit(hash_lock);
2359 			arc_hdr_destroy(exists);
2360 			exists = buf_hash_insert(hdr, &hash_lock);
2361 			ASSERT3P(exists, ==, NULL);
2362 		}
2363 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2364 		arc_access(hdr, hash_lock);
2365 		mutex_exit(hash_lock);
2366 	} else if (acb->acb_done == NULL) {
2367 		int destroy_hdr;
2368 		/*
2369 		 * This is an anonymous buffer with no user callback,
2370 		 * destroy it if there are no active references.
2371 		 */
2372 		mutex_enter(&arc_eviction_mtx);
2373 		destroy_hdr = refcount_is_zero(&hdr->b_refcnt);
2374 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2375 		mutex_exit(&arc_eviction_mtx);
2376 		if (destroy_hdr)
2377 			arc_hdr_destroy(hdr);
2378 	} else {
2379 		hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
2380 	}
2381 
2382 	if (acb->acb_done) {
2383 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
2384 		acb->acb_done(zio, buf, acb->acb_private);
2385 	}
2386 
2387 	kmem_free(acb, sizeof (arc_callback_t));
2388 }
2389 
2390 int
2391 arc_write(zio_t *pio, spa_t *spa, int checksum, int compress, int ncopies,
2392     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
2393     arc_done_func_t *done, void *private, int priority, int flags,
2394     uint32_t arc_flags, zbookmark_t *zb)
2395 {
2396 	arc_buf_hdr_t *hdr = buf->b_hdr;
2397 	arc_callback_t	*acb;
2398 	zio_t	*rzio;
2399 
2400 	/* this is a private buffer - no locking required */
2401 	ASSERT3P(hdr->b_state, ==, arc.anon);
2402 	ASSERT(BUF_EMPTY(hdr));
2403 	ASSERT(!HDR_IO_ERROR(hdr));
2404 	ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
2405 	ASSERT(hdr->b_acb == 0);
2406 	acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
2407 	acb->acb_done = done;
2408 	acb->acb_private = private;
2409 	acb->acb_byteswap = (arc_byteswap_func_t *)-1;
2410 	hdr->b_acb = acb;
2411 	hdr->b_flags |= ARC_IO_IN_PROGRESS;
2412 	arc_cksum_compute(buf);
2413 	rzio = zio_write(pio, spa, checksum, compress, ncopies, txg, bp,
2414 	    buf->b_data, hdr->b_size, arc_write_done, buf, priority, flags, zb);
2415 
2416 	if (arc_flags & ARC_WAIT)
2417 		return (zio_wait(rzio));
2418 
2419 	ASSERT(arc_flags & ARC_NOWAIT);
2420 	zio_nowait(rzio);
2421 
2422 	return (0);
2423 }
2424 
2425 int
2426 arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
2427     zio_done_func_t *done, void *private, uint32_t arc_flags)
2428 {
2429 	arc_buf_hdr_t *ab;
2430 	kmutex_t *hash_lock;
2431 	zio_t	*zio;
2432 
2433 	/*
2434 	 * If this buffer is in the cache, release it, so it
2435 	 * can be re-used.
2436 	 */
2437 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
2438 	if (ab != NULL) {
2439 		/*
2440 		 * The checksum of blocks to free is not always
2441 		 * preserved (eg. on the deadlist).  However, if it is
2442 		 * nonzero, it should match what we have in the cache.
2443 		 */
2444 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
2445 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
2446 		if (ab->b_state != arc.anon)
2447 			arc_change_state(arc.anon, ab, hash_lock);
2448 		if (HDR_IO_IN_PROGRESS(ab)) {
2449 			/*
2450 			 * This should only happen when we prefetch.
2451 			 */
2452 			ASSERT(ab->b_flags & ARC_PREFETCH);
2453 			ASSERT3U(ab->b_datacnt, ==, 1);
2454 			ab->b_flags |= ARC_FREED_IN_READ;
2455 			if (HDR_IN_HASH_TABLE(ab))
2456 				buf_hash_remove(ab);
2457 			ab->b_arc_access = 0;
2458 			bzero(&ab->b_dva, sizeof (dva_t));
2459 			ab->b_birth = 0;
2460 			ab->b_cksum0 = 0;
2461 			ab->b_buf->b_efunc = NULL;
2462 			ab->b_buf->b_private = NULL;
2463 			mutex_exit(hash_lock);
2464 		} else if (refcount_is_zero(&ab->b_refcnt)) {
2465 			mutex_exit(hash_lock);
2466 			arc_hdr_destroy(ab);
2467 			atomic_add_64(&arc.deleted, 1);
2468 		} else {
2469 			/*
2470 			 * We still have an active reference on this
2471 			 * buffer.  This can happen, e.g., from
2472 			 * dbuf_unoverride().
2473 			 */
2474 			ASSERT(!HDR_IN_HASH_TABLE(ab));
2475 			ab->b_arc_access = 0;
2476 			bzero(&ab->b_dva, sizeof (dva_t));
2477 			ab->b_birth = 0;
2478 			ab->b_cksum0 = 0;
2479 			ab->b_buf->b_efunc = NULL;
2480 			ab->b_buf->b_private = NULL;
2481 			mutex_exit(hash_lock);
2482 		}
2483 	}
2484 
2485 	zio = zio_free(pio, spa, txg, bp, done, private);
2486 
2487 	if (arc_flags & ARC_WAIT)
2488 		return (zio_wait(zio));
2489 
2490 	ASSERT(arc_flags & ARC_NOWAIT);
2491 	zio_nowait(zio);
2492 
2493 	return (0);
2494 }
2495 
2496 void
2497 arc_tempreserve_clear(uint64_t tempreserve)
2498 {
2499 	atomic_add_64(&arc_tempreserve, -tempreserve);
2500 	ASSERT((int64_t)arc_tempreserve >= 0);
2501 }
2502 
2503 int
2504 arc_tempreserve_space(uint64_t tempreserve)
2505 {
2506 #ifdef ZFS_DEBUG
2507 	/*
2508 	 * Once in a while, fail for no reason.  Everything should cope.
2509 	 */
2510 	if (spa_get_random(10000) == 0) {
2511 		dprintf("forcing random failure\n");
2512 		return (ERESTART);
2513 	}
2514 #endif
2515 	if (tempreserve > arc.c/4 && !arc.no_grow)
2516 		arc.c = MIN(arc.c_max, tempreserve * 4);
2517 	if (tempreserve > arc.c)
2518 		return (ENOMEM);
2519 
2520 	/*
2521 	 * Throttle writes when the amount of dirty data in the cache
2522 	 * gets too large.  We try to keep the cache less than half full
2523 	 * of dirty blocks so that our sync times don't grow too large.
2524 	 * Note: if two requests come in concurrently, we might let them
2525 	 * both succeed, when one of them should fail.  Not a huge deal.
2526 	 *
2527 	 * XXX The limit should be adjusted dynamically to keep the time
2528 	 * to sync a dataset fixed (around 1-5 seconds?).
2529 	 */
2530 
2531 	if (tempreserve + arc_tempreserve + arc.anon->size > arc.c / 2 &&
2532 	    arc_tempreserve + arc.anon->size > arc.c / 4) {
2533 		dprintf("failing, arc_tempreserve=%lluK anon=%lluK "
2534 		    "tempreserve=%lluK arc.c=%lluK\n",
2535 		    arc_tempreserve>>10, arc.anon->lsize>>10,
2536 		    tempreserve>>10, arc.c>>10);
2537 		return (ERESTART);
2538 	}
2539 	atomic_add_64(&arc_tempreserve, tempreserve);
2540 	return (0);
2541 }
2542 
2543 void
2544 arc_init(void)
2545 {
2546 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
2547 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
2548 
2549 	/* Convert seconds to clock ticks */
2550 	arc_min_prefetch_lifespan = 1 * hz;
2551 
2552 	/* Start out with 1/8 of all memory */
2553 	arc.c = physmem * PAGESIZE / 8;
2554 
2555 #ifdef _KERNEL
2556 	/*
2557 	 * On architectures where the physical memory can be larger
2558 	 * than the addressable space (intel in 32-bit mode), we may
2559 	 * need to limit the cache to 1/8 of VM size.
2560 	 */
2561 	arc.c = MIN(arc.c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
2562 #endif
2563 
2564 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
2565 	arc.c_min = MAX(arc.c / 4, 64<<20);
2566 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
2567 	if (arc.c * 8 >= 1<<30)
2568 		arc.c_max = (arc.c * 8) - (1<<30);
2569 	else
2570 		arc.c_max = arc.c_min;
2571 	arc.c_max = MAX(arc.c * 6, arc.c_max);
2572 
2573 	/*
2574 	 * Allow the tunables to override our calculations if they are
2575 	 * reasonable (ie. over 64MB)
2576 	 */
2577 	if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
2578 		arc.c_max = zfs_arc_max;
2579 	if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc.c_max)
2580 		arc.c_min = zfs_arc_min;
2581 
2582 	arc.c = arc.c_max;
2583 	arc.p = (arc.c >> 1);
2584 
2585 	/* if kmem_flags are set, lets try to use less memory */
2586 	if (kmem_debugging())
2587 		arc.c = arc.c / 2;
2588 	if (arc.c < arc.c_min)
2589 		arc.c = arc.c_min;
2590 
2591 	arc.anon = &ARC_anon;
2592 	arc.mru = &ARC_mru;
2593 	arc.mru_ghost = &ARC_mru_ghost;
2594 	arc.mfu = &ARC_mfu;
2595 	arc.mfu_ghost = &ARC_mfu_ghost;
2596 	arc.size = 0;
2597 
2598 	arc.hits = 0;
2599 	arc.recycle_miss = 0;
2600 	arc.evict_skip = 0;
2601 	arc.mutex_miss = 0;
2602 
2603 	mutex_init(&arc.anon->mtx, NULL, MUTEX_DEFAULT, NULL);
2604 	mutex_init(&arc.mru->mtx, NULL, MUTEX_DEFAULT, NULL);
2605 	mutex_init(&arc.mru_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2606 	mutex_init(&arc.mfu->mtx, NULL, MUTEX_DEFAULT, NULL);
2607 	mutex_init(&arc.mfu_ghost->mtx, NULL, MUTEX_DEFAULT, NULL);
2608 
2609 	list_create(&arc.mru->list, sizeof (arc_buf_hdr_t),
2610 	    offsetof(arc_buf_hdr_t, b_arc_node));
2611 	list_create(&arc.mru_ghost->list, sizeof (arc_buf_hdr_t),
2612 	    offsetof(arc_buf_hdr_t, b_arc_node));
2613 	list_create(&arc.mfu->list, sizeof (arc_buf_hdr_t),
2614 	    offsetof(arc_buf_hdr_t, b_arc_node));
2615 	list_create(&arc.mfu_ghost->list, sizeof (arc_buf_hdr_t),
2616 	    offsetof(arc_buf_hdr_t, b_arc_node));
2617 
2618 	buf_init();
2619 
2620 	arc_thread_exit = 0;
2621 	arc_eviction_list = NULL;
2622 	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
2623 	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
2624 
2625 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
2626 	    TS_RUN, minclsyspri);
2627 
2628 	arc_dead = FALSE;
2629 }
2630 
2631 void
2632 arc_fini(void)
2633 {
2634 	mutex_enter(&arc_reclaim_thr_lock);
2635 	arc_thread_exit = 1;
2636 	while (arc_thread_exit != 0)
2637 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
2638 	mutex_exit(&arc_reclaim_thr_lock);
2639 
2640 	arc_flush();
2641 
2642 	arc_dead = TRUE;
2643 
2644 	mutex_destroy(&arc_eviction_mtx);
2645 	mutex_destroy(&arc_reclaim_thr_lock);
2646 	cv_destroy(&arc_reclaim_thr_cv);
2647 
2648 	list_destroy(&arc.mru->list);
2649 	list_destroy(&arc.mru_ghost->list);
2650 	list_destroy(&arc.mfu->list);
2651 	list_destroy(&arc.mfu_ghost->list);
2652 
2653 	mutex_destroy(&arc.anon->mtx);
2654 	mutex_destroy(&arc.mru->mtx);
2655 	mutex_destroy(&arc.mru_ghost->mtx);
2656 	mutex_destroy(&arc.mfu->mtx);
2657 	mutex_destroy(&arc.mfu_ghost->mtx);
2658 
2659 	buf_fini();
2660 }
2661