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