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