xref: /titanic_51/usr/src/uts/common/fs/zfs/arc.c (revision 577f006c50d564d2f93145b2f2044a942d47f314)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * DVA-based Adjustable Relpacement Cache
31  *
32  * While much of the theory of operation and algorithms used here
33  * are based on the self-tuning, low overhead replacement cache
34  * presented by Megiddo and Modha at FAST 2003, there are some
35  * significant differences:
36  *
37  * 1. The Megiddo and Modha model assumes any page is evictable.
38  * Pages in its cache cannot be "locked" into memory.  This makes
39  * the eviction algorithm simple: evict the last page in the list.
40  * This also make the performance characteristics easy to reason
41  * about.  Our cache is not so simple.  At any given moment, some
42  * subset of the blocks in the cache are un-evictable because we
43  * have handed out a reference to them.  Blocks are only evictable
44  * when there are no external references active.  This makes
45  * eviction far more problematic:  we choose to evict the evictable
46  * blocks that are the "lowest" in the list.
47  *
48  * There are times when it is not possible to evict the requested
49  * space.  In these circumstances we are unable to adjust the cache
50  * size.  To prevent the cache growing unbounded at these times we
51  * implement a "cache throttle" that slowes the flow of new data
52  * into the cache until we can make space avaiable.
53  *
54  * 2. The Megiddo and Modha model assumes a fixed cache size.
55  * Pages are evicted when the cache is full and there is a cache
56  * miss.  Our model has a variable sized cache.  It grows with
57  * high use, but also tries to react to memory preasure from the
58  * operating system: decreasing its size when system memory is
59  * tight.
60  *
61  * 3. The Megiddo and Modha model assumes a fixed page size. All
62  * elements of the cache are therefor exactly the same size.  So
63  * when adjusting the cache size following a cache miss, its simply
64  * a matter of choosing a single page to evict.  In our model, we
65  * have variable sized cache blocks (rangeing from 512 bytes to
66  * 128K bytes).  We therefor choose a set of blocks to evict to make
67  * space for a cache miss that approximates as closely as possible
68  * the space used by the new block.
69  *
70  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71  * by N. Megiddo & D. Modha, FAST 2003
72  */
73 
74 /*
75  * The locking model:
76  *
77  * A new reference to a cache buffer can be obtained in two
78  * ways: 1) via a hash table lookup using the DVA as a key,
79  * or 2) via one of the ARC lists.  The arc_read() inerface
80  * uses method 1, while the internal arc algorithms for
81  * adjusting the cache use method 2.  We therefor provide two
82  * types of locks: 1) the hash table lock array, and 2) the
83  * arc list locks.
84  *
85  * Buffers do not have their own mutexs, rather they rely on the
86  * hash table mutexs for the bulk of their protection (i.e. most
87  * fields in the arc_buf_hdr_t are protected by these mutexs).
88  *
89  * buf_hash_find() returns the appropriate mutex (held) when it
90  * locates the requested buffer in the hash table.  It returns
91  * NULL for the mutex if the buffer was not in the table.
92  *
93  * buf_hash_remove() expects the appropriate hash mutex to be
94  * already held before it is invoked.
95  *
96  * Each arc state also has a mutex which is used to protect the
97  * buffer list associated with the state.  When attempting to
98  * obtain a hash table lock while holding an arc list lock you
99  * must use: mutex_tryenter() to avoid deadlock.  Also note that
100  * the "top" state mutex must be held before the "bot" state mutex.
101  *
102  * Note that the majority of the performance stats are manipulated
103  * with atomic operations.
104  */
105 
106 #include <sys/spa.h>
107 #include <sys/zio.h>
108 #include <sys/zfs_context.h>
109 #include <sys/arc.h>
110 #include <sys/refcount.h>
111 #ifdef _KERNEL
112 #include <sys/vmsystm.h>
113 #include <vm/anon.h>
114 #include <sys/fs/swapnode.h>
115 #endif
116 #include <sys/callb.h>
117 
118 static kmutex_t		arc_reclaim_thr_lock;
119 static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
120 static uint8_t		arc_thread_exit;
121 
122 typedef enum arc_reclaim_strategy {
123 	ARC_RECLAIM_AGGR,		/* Aggressive reclaim strategy */
124 	ARC_RECLAIM_CONS		/* Conservative reclaim strategy */
125 } arc_reclaim_strategy_t;
126 
127 /* number of seconds before growing cache again */
128 static int		arc_grow_retry = 60;
129 
130 static kmutex_t arc_reclaim_lock;
131 static int arc_dead;
132 
133 /*
134  * Note that buffers can be on one of 5 states:
135  *	ARC_anon	- anonymous (discussed below)
136  *	ARC_mru_top	- recently used, currently cached
137  *	ARC_mru_bot	- recentely used, no longer in cache
138  *	ARC_mfu_top	- frequently used, currently cached
139  *	ARC_mfu_bot	- frequently used, no longer in cache
140  * When there are no active references to the buffer, they
141  * are linked onto one of the lists in arc.  These are the
142  * only buffers that can be evicted or deleted.
143  *
144  * Anonymous buffers are buffers that are not associated with
145  * a DVA.  These are buffers that hold dirty block copies
146  * before they are written to stable storage.  By definition,
147  * they are "ref'd" and are considered part of arc_mru_top
148  * that cannot be freed.  Generally, they will aquire a DVA
149  * as they are written and migrate onto the arc_mru_top list.
150  */
151 
152 typedef struct arc_state {
153 	list_t	list;	/* linked list of evictable buffer in state */
154 	uint64_t lsize;	/* total size of buffers in the linked list */
155 	uint64_t size;	/* total size of all buffers in this state */
156 	uint64_t hits;
157 	kmutex_t mtx;
158 } arc_state_t;
159 
160 /* The 5 states: */
161 static arc_state_t ARC_anon;
162 static arc_state_t ARC_mru_top;
163 static arc_state_t ARC_mru_bot;
164 static arc_state_t ARC_mfu_top;
165 static arc_state_t ARC_mfu_bot;
166 
167 static struct arc {
168 	arc_state_t 	*anon;
169 	arc_state_t	*mru_top;
170 	arc_state_t	*mru_bot;
171 	arc_state_t	*mfu_top;
172 	arc_state_t	*mfu_bot;
173 	uint64_t	size;		/* Actual total arc size */
174 	uint64_t	p;		/* Target size (in bytes) of mru_top */
175 	uint64_t	c;		/* Target size of cache (in bytes) */
176 	uint64_t	c_min;		/* Minimum target cache size */
177 	uint64_t	c_max;		/* Maximum target cache size */
178 	uint64_t	incr;		/* Size by which to increment arc.c */
179 	int64_t		size_check;
180 
181 	/* performance stats */
182 	uint64_t	hits;
183 	uint64_t	misses;
184 	uint64_t	deleted;
185 	uint64_t	skipped;
186 	uint64_t	hash_elements;
187 	uint64_t	hash_elements_max;
188 	uint64_t	hash_collisions;
189 	uint64_t	hash_chains;
190 	uint32_t	hash_chain_max;
191 
192 	int		no_grow;	/* Don't try to grow cache size */
193 } arc;
194 
195 /* Default amount to grow arc.incr */
196 static int64_t arc_incr_size = 1024;
197 
198 /* > 0 ==> time to increment arc.c */
199 static int64_t arc_size_check_default = -1000;
200 
201 static uint64_t arc_tempreserve;
202 
203 typedef struct arc_callback arc_callback_t;
204 
205 struct arc_callback {
206 	arc_done_func_t		*acb_done;
207 	void			*acb_private;
208 	arc_byteswap_func_t	*acb_byteswap;
209 	arc_buf_t		*acb_buf;
210 	zio_t			*acb_zio_dummy;
211 	arc_callback_t		*acb_next;
212 };
213 
214 struct arc_buf_hdr {
215 	/* immutable */
216 	uint64_t		b_size;
217 	spa_t			*b_spa;
218 
219 	/* protected by hash lock */
220 	dva_t			b_dva;
221 	uint64_t		b_birth;
222 	uint64_t		b_cksum0;
223 
224 	arc_buf_hdr_t		*b_hash_next;
225 	arc_buf_t		*b_buf;
226 	uint32_t		b_flags;
227 
228 	kcondvar_t		b_cv;
229 	arc_callback_t		*b_acb;
230 
231 	/* protected by arc state mutex */
232 	arc_state_t		*b_state;
233 	list_node_t		b_arc_node;
234 
235 	/* updated atomically */
236 	clock_t			b_arc_access;
237 
238 	/* self protecting */
239 	refcount_t		b_refcnt;
240 };
241 
242 /*
243  * Private ARC flags.  These flags are private ARC only flags that will show up
244  * in b_flags in the arc_hdr_buf_t.  Some flags are publicly declared, and can
245  * be passed in as arc_flags in things like arc_read.  However, these flags
246  * should never be passed and should only be set by ARC code.  When adding new
247  * public flags, make sure not to smash the private ones.
248  */
249 
250 #define	ARC_IO_IN_PROGRESS	(1 << 10)	/* I/O in progress for buf */
251 #define	ARC_IO_ERROR		(1 << 11)	/* I/O failed for buf */
252 #define	ARC_FREED_IN_READ	(1 << 12)	/* buf freed while in read */
253 
254 #define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_IO_IN_PROGRESS)
255 #define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_IO_ERROR)
256 #define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FREED_IN_READ)
257 
258 /*
259  * Hash table routines
260  */
261 
262 #define	HT_LOCK_PAD	64
263 
264 struct ht_lock {
265 	kmutex_t	ht_lock;
266 #ifdef _KERNEL
267 	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
268 #endif
269 };
270 
271 #define	BUF_LOCKS 256
272 typedef struct buf_hash_table {
273 	uint64_t ht_mask;
274 	arc_buf_hdr_t **ht_table;
275 	struct ht_lock ht_locks[BUF_LOCKS];
276 } buf_hash_table_t;
277 
278 static buf_hash_table_t buf_hash_table;
279 
280 #define	BUF_HASH_INDEX(spa, dva, birth) \
281 	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
282 #define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
283 #define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
284 #define	HDR_LOCK(buf) \
285 	(BUF_HASH_LOCK(BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth)))
286 
287 uint64_t zfs_crc64_table[256];
288 
289 static uint64_t
290 buf_hash(spa_t *spa, dva_t *dva, uint64_t birth)
291 {
292 	uintptr_t spav = (uintptr_t)spa;
293 	uint8_t *vdva = (uint8_t *)dva;
294 	uint64_t crc = -1ULL;
295 	int i;
296 
297 	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
298 
299 	for (i = 0; i < sizeof (dva_t); i++)
300 		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
301 
302 	crc ^= (spav>>8) ^ birth;
303 
304 	return (crc);
305 }
306 
307 #define	BUF_EMPTY(buf)						\
308 	((buf)->b_dva.dva_word[0] == 0 &&			\
309 	(buf)->b_dva.dva_word[1] == 0 &&			\
310 	(buf)->b_birth == 0)
311 
312 #define	BUF_EQUAL(spa, dva, birth, buf)				\
313 	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
314 	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
315 	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
316 
317 static arc_buf_hdr_t *
318 buf_hash_find(spa_t *spa, dva_t *dva, uint64_t birth, kmutex_t **lockp)
319 {
320 	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
321 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
322 	arc_buf_hdr_t *buf;
323 
324 	mutex_enter(hash_lock);
325 	for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
326 	    buf = buf->b_hash_next) {
327 		if (BUF_EQUAL(spa, dva, birth, buf)) {
328 			*lockp = hash_lock;
329 			return (buf);
330 		}
331 	}
332 	mutex_exit(hash_lock);
333 	*lockp = NULL;
334 	return (NULL);
335 }
336 
337 /*
338  * Insert an entry into the hash table.  If there is already an element
339  * equal to elem in the hash table, then the already existing element
340  * will be returned and the new element will not be inserted.
341  * Otherwise returns NULL.
342  */
343 static arc_buf_hdr_t *fbufs[4]; /* XXX to find 6341326 */
344 static kthread_t *fbufs_lastthread;
345 static arc_buf_hdr_t *
346 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
347 {
348 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
349 	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
350 	arc_buf_hdr_t *fbuf;
351 	uint32_t max, i;
352 
353 	fbufs_lastthread = curthread;
354 	*lockp = hash_lock;
355 	mutex_enter(hash_lock);
356 	for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
357 	    fbuf = fbuf->b_hash_next, i++) {
358 		if (i < sizeof (fbufs) / sizeof (fbufs[0]))
359 			fbufs[i] = fbuf;
360 		if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
361 			return (fbuf);
362 	}
363 
364 	buf->b_hash_next = buf_hash_table.ht_table[idx];
365 	buf_hash_table.ht_table[idx] = buf;
366 
367 	/* collect some hash table performance data */
368 	if (i > 0) {
369 		atomic_add_64(&arc.hash_collisions, 1);
370 		if (i == 1)
371 			atomic_add_64(&arc.hash_chains, 1);
372 	}
373 	while (i > (max = arc.hash_chain_max) &&
374 	    max != atomic_cas_32(&arc.hash_chain_max, max, i)) {
375 		continue;
376 	}
377 	atomic_add_64(&arc.hash_elements, 1);
378 	if (arc.hash_elements > arc.hash_elements_max)
379 		atomic_add_64(&arc.hash_elements_max, 1);
380 
381 	return (NULL);
382 }
383 
384 static void
385 buf_hash_remove(arc_buf_hdr_t *buf)
386 {
387 	arc_buf_hdr_t *fbuf, **bufp;
388 	uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
389 
390 	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
391 
392 	bufp = &buf_hash_table.ht_table[idx];
393 	while ((fbuf = *bufp) != buf) {
394 		ASSERT(fbuf != NULL);
395 		bufp = &fbuf->b_hash_next;
396 	}
397 	*bufp = buf->b_hash_next;
398 	buf->b_hash_next = NULL;
399 
400 	/* collect some hash table performance data */
401 	atomic_add_64(&arc.hash_elements, -1);
402 	if (buf_hash_table.ht_table[idx] &&
403 	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
404 		atomic_add_64(&arc.hash_chains, -1);
405 }
406 
407 /*
408  * Global data structures and functions for the buf kmem cache.
409  */
410 static kmem_cache_t *hdr_cache;
411 static kmem_cache_t *buf_cache;
412 
413 static void
414 buf_fini(void)
415 {
416 	int i;
417 
418 	kmem_free(buf_hash_table.ht_table,
419 	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
420 	for (i = 0; i < BUF_LOCKS; i++)
421 		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
422 	kmem_cache_destroy(hdr_cache);
423 	kmem_cache_destroy(buf_cache);
424 }
425 
426 /*
427  * Constructor callback - called when the cache is empty
428  * and a new buf is requested.
429  */
430 /* ARGSUSED */
431 static int
432 hdr_cons(void *vbuf, void *unused, int kmflag)
433 {
434 	arc_buf_hdr_t *buf = vbuf;
435 
436 	bzero(buf, sizeof (arc_buf_hdr_t));
437 	refcount_create(&buf->b_refcnt);
438 	cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
439 	return (0);
440 }
441 
442 /*
443  * Destructor callback - called when a cached buf is
444  * no longer required.
445  */
446 /* ARGSUSED */
447 static void
448 hdr_dest(void *vbuf, void *unused)
449 {
450 	arc_buf_hdr_t *buf = vbuf;
451 
452 	refcount_destroy(&buf->b_refcnt);
453 	cv_destroy(&buf->b_cv);
454 }
455 
456 void arc_kmem_reclaim(void);
457 
458 /*
459  * Reclaim callback -- invoked when memory is low.
460  */
461 /* ARGSUSED */
462 static void
463 hdr_recl(void *unused)
464 {
465 	dprintf("hdr_recl called\n");
466 	arc_kmem_reclaim();
467 }
468 
469 static void
470 buf_init(void)
471 {
472 	uint64_t *ct;
473 	uint64_t hsize = 1ULL << 10;
474 	int i, j;
475 
476 	/*
477 	 * The hash table is big enough to fill all of physical memory
478 	 * with an average 4k block size.  The table will take up
479 	 * totalmem*sizeof(void*)/4k bytes (eg. 2MB/GB with 8-byte
480 	 * pointers).
481 	 */
482 	while (hsize * 4096 < physmem * PAGESIZE)
483 		hsize <<= 1;
484 
485 	buf_hash_table.ht_mask = hsize - 1;
486 	buf_hash_table.ht_table = kmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
487 
488 	hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
489 	    0, hdr_cons, hdr_dest, hdr_recl, NULL, NULL, 0);
490 	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
491 	    0, NULL, NULL, NULL, NULL, NULL, 0);
492 
493 	for (i = 0; i < 256; i++)
494 		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
495 			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
496 
497 	for (i = 0; i < BUF_LOCKS; i++) {
498 		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
499 		    NULL, MUTEX_DEFAULT, NULL);
500 	}
501 }
502 
503 #define	ARC_MINTIME	(hz>>4) /* 62 ms */
504 
505 #define	ARC_TAG		(void *)0x05201962
506 
507 static void
508 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
509 {
510 	ASSERT(MUTEX_HELD(hash_lock));
511 
512 	if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
513 	    (ab->b_state != arc.anon)) {
514 
515 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
516 		mutex_enter(&ab->b_state->mtx);
517 		ASSERT(!refcount_is_zero(&ab->b_refcnt));
518 		ASSERT(list_link_active(&ab->b_arc_node));
519 		list_remove(&ab->b_state->list, ab);
520 		ASSERT3U(ab->b_state->lsize, >=, ab->b_size);
521 		ab->b_state->lsize -= ab->b_size;
522 		mutex_exit(&ab->b_state->mtx);
523 	}
524 }
525 
526 static int
527 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
528 {
529 	int cnt;
530 
531 	ASSERT(MUTEX_HELD(hash_lock));
532 
533 	if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
534 	    (ab->b_state != arc.anon)) {
535 
536 		ASSERT(!MUTEX_HELD(&ab->b_state->mtx));
537 		mutex_enter(&ab->b_state->mtx);
538 		ASSERT(!list_link_active(&ab->b_arc_node));
539 		list_insert_head(&ab->b_state->list, ab);
540 		ASSERT(ab->b_buf != NULL);
541 		ab->b_state->lsize += ab->b_size;
542 		mutex_exit(&ab->b_state->mtx);
543 	}
544 	return (cnt);
545 }
546 
547 /*
548  * Move the supplied buffer to the indicated state.  The mutex
549  * for the buffer must be held by the caller.
550  */
551 static void
552 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab,
553     kmutex_t *hash_lock)
554 {
555 	arc_buf_t *buf;
556 
557 	ASSERT(MUTEX_HELD(hash_lock));
558 
559 	/*
560 	 * If this buffer is evictable, transfer it from the
561 	 * old state list to the new state list.
562 	 */
563 	if (refcount_is_zero(&ab->b_refcnt)) {
564 		if (ab->b_state != arc.anon) {
565 			int drop_mutex = FALSE;
566 
567 			if (!MUTEX_HELD(&ab->b_state->mtx)) {
568 				mutex_enter(&ab->b_state->mtx);
569 				drop_mutex = TRUE;
570 			}
571 			ASSERT(list_link_active(&ab->b_arc_node));
572 			list_remove(&ab->b_state->list, ab);
573 			ASSERT3U(ab->b_state->lsize, >=, ab->b_size);
574 			ab->b_state->lsize -= ab->b_size;
575 			if (drop_mutex)
576 				mutex_exit(&ab->b_state->mtx);
577 		}
578 		if (new_state != arc.anon) {
579 			int drop_mutex = FALSE;
580 
581 			if (!MUTEX_HELD(&new_state->mtx)) {
582 				mutex_enter(&new_state->mtx);
583 				drop_mutex = TRUE;
584 			}
585 			list_insert_head(&new_state->list, ab);
586 			ASSERT(ab->b_buf != NULL);
587 			new_state->lsize += ab->b_size;
588 			if (drop_mutex)
589 				mutex_exit(&new_state->mtx);
590 		}
591 	}
592 
593 	ASSERT(!BUF_EMPTY(ab));
594 	if (new_state == arc.anon && ab->b_state != arc.anon) {
595 		buf_hash_remove(ab);
596 	}
597 
598 	/*
599 	 * If this buffer isn't being transferred to the MRU-top
600 	 * state, it's safe to clear its prefetch flag
601 	 */
602 	if ((new_state != arc.mru_top) && (new_state != arc.mru_bot)) {
603 		ab->b_flags &= ~ARC_PREFETCH;
604 	}
605 
606 	buf = ab->b_buf;
607 	if (buf == NULL) {
608 		ASSERT3U(ab->b_state->size, >=, ab->b_size);
609 		atomic_add_64(&ab->b_state->size, -ab->b_size);
610 		/* we should only be here if we are deleting state */
611 		ASSERT(new_state == arc.anon &&
612 		    (ab->b_state == arc.mru_bot || ab->b_state == arc.mfu_bot));
613 	} else while (buf) {
614 		ASSERT3U(ab->b_state->size, >=, ab->b_size);
615 		atomic_add_64(&ab->b_state->size, -ab->b_size);
616 		atomic_add_64(&new_state->size, ab->b_size);
617 		buf = buf->b_next;
618 	}
619 	ab->b_state = new_state;
620 }
621 
622 arc_buf_t *
623 arc_buf_alloc(spa_t *spa, int size, void *tag)
624 {
625 	arc_buf_hdr_t *hdr;
626 	arc_buf_t *buf;
627 
628 	ASSERT3U(size, >, 0);
629 	hdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
630 	ASSERT(BUF_EMPTY(hdr));
631 	hdr->b_size = size;
632 	hdr->b_spa = spa;
633 	hdr->b_state = arc.anon;
634 	hdr->b_arc_access = 0;
635 	buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
636 	buf->b_hdr = hdr;
637 	buf->b_next = NULL;
638 	buf->b_data = zio_buf_alloc(size);
639 	hdr->b_buf = buf;
640 	hdr->b_flags = 0;
641 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
642 	(void) refcount_add(&hdr->b_refcnt, tag);
643 
644 	atomic_add_64(&arc.size, size);
645 	atomic_add_64(&arc.anon->size, size);
646 
647 	return (buf);
648 }
649 
650 static void
651 arc_hdr_free(arc_buf_hdr_t *hdr)
652 {
653 	ASSERT(refcount_is_zero(&hdr->b_refcnt));
654 	ASSERT3P(hdr->b_state, ==, arc.anon);
655 
656 	if (!BUF_EMPTY(hdr)) {
657 		/*
658 		 * We can be called with an arc state lock held,
659 		 * so we can't hold a hash lock here.
660 		 * ASSERT(not in hash table)
661 		 */
662 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
663 		bzero(&hdr->b_dva, sizeof (dva_t));
664 		hdr->b_birth = 0;
665 		hdr->b_cksum0 = 0;
666 	}
667 	if (hdr->b_buf) {
668 		arc_buf_t *buf = hdr->b_buf;
669 
670 		ASSERT3U(hdr->b_size, >, 0);
671 		zio_buf_free(buf->b_data, hdr->b_size);
672 		atomic_add_64(&arc.size, -hdr->b_size);
673 		ASSERT3U(arc.anon->size, >=, hdr->b_size);
674 		atomic_add_64(&arc.anon->size, -hdr->b_size);
675 		ASSERT3P(buf->b_next, ==, NULL);
676 		kmem_cache_free(buf_cache, buf);
677 		hdr->b_buf = NULL;
678 	}
679 	ASSERT(!list_link_active(&hdr->b_arc_node));
680 	ASSERT3P(hdr->b_hash_next, ==, NULL);
681 	ASSERT3P(hdr->b_acb, ==, NULL);
682 	kmem_cache_free(hdr_cache, hdr);
683 }
684 
685 void
686 arc_buf_free(arc_buf_t *buf, void *tag)
687 {
688 	arc_buf_hdr_t *hdr = buf->b_hdr;
689 	kmutex_t *hash_lock = HDR_LOCK(hdr);
690 	int freeable;
691 
692 	mutex_enter(hash_lock);
693 	if (remove_reference(hdr, hash_lock, tag) > 0) {
694 		arc_buf_t **bufp = &hdr->b_buf;
695 		arc_state_t *state = hdr->b_state;
696 		uint64_t size = hdr->b_size;
697 
698 		ASSERT(hdr->b_state != arc.anon || HDR_IO_ERROR(hdr));
699 		while (*bufp != buf) {
700 			ASSERT(*bufp);
701 			bufp = &(*bufp)->b_next;
702 		}
703 		*bufp = buf->b_next;
704 		mutex_exit(hash_lock);
705 		zio_buf_free(buf->b_data, size);
706 		atomic_add_64(&arc.size, -size);
707 		kmem_cache_free(buf_cache, buf);
708 		ASSERT3U(state->size, >=, size);
709 		atomic_add_64(&state->size, -size);
710 		return;
711 	}
712 
713 	/* don't free buffers that are in the middle of an async write */
714 	freeable = (hdr->b_state == arc.anon && hdr->b_acb == NULL);
715 	mutex_exit(hash_lock);
716 
717 	if (freeable)
718 		arc_hdr_free(hdr);
719 }
720 
721 int
722 arc_buf_size(arc_buf_t *buf)
723 {
724 	return (buf->b_hdr->b_size);
725 }
726 
727 /*
728  * Evict buffers from list until we've removed the specified number of
729  * bytes.  Move the removed buffers to the appropriate evict state.
730  */
731 static uint64_t
732 arc_evict_state(arc_state_t *state, int64_t bytes)
733 {
734 	arc_state_t *evicted_state;
735 	uint64_t bytes_evicted = 0;
736 	arc_buf_hdr_t *ab, *ab_prev;
737 	kmutex_t *hash_lock;
738 
739 	ASSERT(state == arc.mru_top || state == arc.mfu_top);
740 
741 	if (state == arc.mru_top)
742 		evicted_state = arc.mru_bot;
743 	else
744 		evicted_state = arc.mfu_bot;
745 
746 	mutex_enter(&state->mtx);
747 	mutex_enter(&evicted_state->mtx);
748 
749 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
750 		ab_prev = list_prev(&state->list, ab);
751 		hash_lock = HDR_LOCK(ab);
752 		if (mutex_tryenter(hash_lock)) {
753 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 0);
754 			arc_change_state(evicted_state, ab, hash_lock);
755 			zio_buf_free(ab->b_buf->b_data, ab->b_size);
756 			atomic_add_64(&arc.size, -ab->b_size);
757 			ASSERT3P(ab->b_buf->b_next, ==, NULL);
758 			kmem_cache_free(buf_cache, ab->b_buf);
759 			ab->b_buf = NULL;
760 			DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
761 			bytes_evicted += ab->b_size;
762 			mutex_exit(hash_lock);
763 			if (bytes_evicted >= bytes)
764 				break;
765 		} else {
766 			atomic_add_64(&arc.skipped, 1);
767 		}
768 	}
769 	mutex_exit(&evicted_state->mtx);
770 	mutex_exit(&state->mtx);
771 
772 	if (bytes_evicted < bytes)
773 		dprintf("only evicted %lld bytes from %x",
774 		    (longlong_t)bytes_evicted, state);
775 
776 	return (bytes_evicted);
777 }
778 
779 /*
780  * Remove buffers from list until we've removed the specified number of
781  * bytes.  Destroy the buffers that are removed.
782  */
783 static void
784 arc_delete_state(arc_state_t *state, int64_t bytes)
785 {
786 	uint_t bufs_skipped = 0;
787 	uint64_t bytes_deleted = 0;
788 	arc_buf_hdr_t *ab, *ab_prev;
789 	kmutex_t *hash_lock;
790 
791 top:
792 	mutex_enter(&state->mtx);
793 	for (ab = list_tail(&state->list); ab; ab = ab_prev) {
794 		ab_prev = list_prev(&state->list, ab);
795 		hash_lock = HDR_LOCK(ab);
796 		if (mutex_tryenter(hash_lock)) {
797 			arc_change_state(arc.anon, ab, hash_lock);
798 			mutex_exit(hash_lock);
799 			atomic_add_64(&arc.deleted, 1);
800 			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
801 			bytes_deleted += ab->b_size;
802 			arc_hdr_free(ab);
803 			if (bytes >= 0 && bytes_deleted >= bytes)
804 				break;
805 		} else {
806 			if (bytes < 0) {
807 				mutex_exit(&state->mtx);
808 				mutex_enter(hash_lock);
809 				mutex_exit(hash_lock);
810 				goto top;
811 			}
812 			bufs_skipped += 1;
813 		}
814 	}
815 	mutex_exit(&state->mtx);
816 
817 	if (bufs_skipped) {
818 		atomic_add_64(&arc.skipped, bufs_skipped);
819 		ASSERT(bytes >= 0);
820 	}
821 
822 	if (bytes_deleted < bytes)
823 		dprintf("only deleted %lld bytes from %p",
824 		    (longlong_t)bytes_deleted, state);
825 }
826 
827 static void
828 arc_adjust(void)
829 {
830 	int64_t top_sz, mru_over, arc_over;
831 
832 	top_sz = arc.anon->size + arc.mru_top->size;
833 
834 	if (top_sz > arc.p && arc.mru_top->lsize > 0) {
835 		int64_t toevict = MIN(arc.mru_top->lsize, top_sz-arc.p);
836 		(void) arc_evict_state(arc.mru_top, toevict);
837 		top_sz = arc.anon->size + arc.mru_top->size;
838 	}
839 
840 	mru_over = top_sz + arc.mru_bot->size - arc.c;
841 
842 	if (mru_over > 0) {
843 		if (arc.mru_bot->lsize > 0) {
844 			int64_t todelete = MIN(arc.mru_bot->lsize, mru_over);
845 			arc_delete_state(arc.mru_bot, todelete);
846 		}
847 	}
848 
849 	if ((arc_over = arc.size - arc.c) > 0) {
850 		int64_t table_over;
851 
852 		if (arc.mfu_top->lsize > 0) {
853 			int64_t toevict = MIN(arc.mfu_top->lsize, arc_over);
854 			(void) arc_evict_state(arc.mfu_top, toevict);
855 		}
856 
857 		table_over = arc.size + arc.mru_bot->lsize + arc.mfu_bot->lsize
858 		    - arc.c*2;
859 
860 		if (table_over > 0 && arc.mfu_bot->lsize > 0) {
861 			int64_t todelete = MIN(arc.mfu_bot->lsize, table_over);
862 			arc_delete_state(arc.mfu_bot, todelete);
863 		}
864 	}
865 }
866 
867 /*
868  * Flush all *evictable* data from the cache.
869  * NOTE: this will not touch "active" (i.e. referenced) data.
870  */
871 void
872 arc_flush(void)
873 {
874 	arc_delete_state(arc.mru_top, -1);
875 	arc_delete_state(arc.mfu_top, -1);
876 
877 	arc_delete_state(arc.mru_bot, -1);
878 	arc_delete_state(arc.mfu_bot, -1);
879 }
880 
881 void
882 arc_kmem_reclaim(void)
883 {
884 	/* Remove 6.25% */
885 	/*
886 	 * We need arc_reclaim_lock because we don't want multiple
887 	 * threads trying to reclaim concurrently.
888 	 */
889 
890 	/*
891 	 * umem calls the reclaim func when we destroy the buf cache,
892 	 * which is after we do arc_fini().  So we set a flag to prevent
893 	 * accessing the destroyed mutexes and lists.
894 	 */
895 	if (arc_dead)
896 		return;
897 
898 	mutex_enter(&arc_reclaim_lock);
899 
900 	atomic_add_64(&arc.c, -(arc.c >> 4));
901 	if (arc.c < arc.c_min)
902 		arc.c = arc.c_min;
903 	atomic_add_64(&arc.p, -(arc.p >> 4));
904 
905 	arc_adjust();
906 
907 	/* Cool it for a while */
908 	arc.incr = 0;
909 	arc.size_check = arc_size_check_default << 3;
910 
911 	mutex_exit(&arc_reclaim_lock);
912 }
913 
914 static int
915 arc_reclaim_needed(void)
916 {
917 	uint64_t extra;
918 
919 #ifdef _KERNEL
920 	/*
921 	 * take 'desfree' extra pages, so we reclaim sooner, rather than later
922 	 */
923 	extra = desfree;
924 
925 	/*
926 	 * check that we're out of range of the pageout scanner.  It starts to
927 	 * schedule paging if freemem is less than lotsfree and needfree.
928 	 * lotsfree is the high-water mark for pageout, and needfree is the
929 	 * number of needed free pages.  We add extra pages here to make sure
930 	 * the scanner doesn't start up while we're freeing memory.
931 	 */
932 	if (freemem < lotsfree + needfree + extra)
933 		return (1);
934 
935 	/*
936 	 * check to make sure that swapfs has enough space so that anon
937 	 * reservations can still succeeed. anon_resvmem() checks that the
938 	 * availrmem is greater than swapfs_minfree, and the number of reserved
939 	 * swap pages.  We also add a bit of extra here just to prevent
940 	 * circumstances from getting really dire.
941 	 */
942 	if (availrmem < swapfs_minfree + swapfs_reserve + extra)
943 		return (1);
944 
945 	/*
946 	 * If we're on an i386 platform, it's possible that we'll exhaust the
947 	 * kernel heap space before we ever run out of available physical
948 	 * memory.  Most checks of the size of the heap_area compare against
949 	 * tune.t_minarmem, which is the minimum available real memory that we
950 	 * can have in the system.  However, this is generally fixed at 25 pages
951 	 * which is so low that it's useless.  In this comparison, we seek to
952 	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
953 	 * heap is allocated.  (Or, in the caclulation, if less than 1/4th is
954 	 * free)
955 	 */
956 #if defined(__i386)
957 	if (btop(vmem_size(heap_arena, VMEM_FREE)) <
958 	    (btop(vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC)) >> 2))
959 		return (1);
960 #endif
961 
962 #else
963 	if (spa_get_random(100) == 0)
964 		return (1);
965 #endif
966 	return (0);
967 }
968 
969 static void
970 arc_kmem_reap_now(arc_reclaim_strategy_t strat)
971 {
972 	size_t			i;
973 	kmem_cache_t		*prev_cache = NULL;
974 	extern kmem_cache_t	*zio_buf_cache[];
975 
976 	/*
977 	 * an agressive reclamation will shrink the cache size as well as reap
978 	 * free kmem buffers.  The arc_kmem_reclaim function is called when the
979 	 * header-cache is reaped, so we only reap the header cache if we're
980 	 * performing an agressive reclaim.  If we're not, just clean the kmem
981 	 * buffer caches.
982 	 */
983 	if (strat == ARC_RECLAIM_AGGR)
984 		kmem_cache_reap_now(hdr_cache);
985 
986 	kmem_cache_reap_now(buf_cache);
987 
988 	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
989 		if (zio_buf_cache[i] != prev_cache) {
990 			prev_cache = zio_buf_cache[i];
991 			kmem_cache_reap_now(zio_buf_cache[i]);
992 		}
993 	}
994 }
995 
996 static void
997 arc_reclaim_thread(void)
998 {
999 	clock_t			growtime = 0;
1000 	arc_reclaim_strategy_t	last_reclaim = ARC_RECLAIM_CONS;
1001 	callb_cpr_t		cpr;
1002 
1003 	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
1004 
1005 	mutex_enter(&arc_reclaim_thr_lock);
1006 	while (arc_thread_exit == 0) {
1007 		if (arc_reclaim_needed()) {
1008 
1009 			if (arc.no_grow) {
1010 				if (last_reclaim == ARC_RECLAIM_CONS) {
1011 					last_reclaim = ARC_RECLAIM_AGGR;
1012 				} else {
1013 					last_reclaim = ARC_RECLAIM_CONS;
1014 				}
1015 			} else {
1016 				arc.no_grow = TRUE;
1017 				last_reclaim = ARC_RECLAIM_AGGR;
1018 				membar_producer();
1019 			}
1020 
1021 			/* reset the growth delay for every reclaim */
1022 			growtime = lbolt + (arc_grow_retry * hz);
1023 
1024 			arc_kmem_reap_now(last_reclaim);
1025 
1026 		} else if ((growtime > 0) && ((growtime - lbolt) <= 0)) {
1027 			arc.no_grow = FALSE;
1028 		}
1029 
1030 		/* block until needed, or one second, whichever is shorter */
1031 		CALLB_CPR_SAFE_BEGIN(&cpr);
1032 		(void) cv_timedwait(&arc_reclaim_thr_cv,
1033 		    &arc_reclaim_thr_lock, (lbolt + hz));
1034 		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
1035 	}
1036 
1037 	arc_thread_exit = 0;
1038 	cv_broadcast(&arc_reclaim_thr_cv);
1039 	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
1040 	thread_exit();
1041 }
1042 
1043 static void
1044 arc_try_grow(int64_t bytes)
1045 {
1046 	/*
1047 	 * If we're within (2 * maxblocksize) bytes of the target
1048 	 * cache size, increment the target cache size
1049 	 */
1050 	atomic_add_64((uint64_t *)&arc.size_check, 1);
1051 
1052 	if (arc_reclaim_needed()) {
1053 		cv_signal(&arc_reclaim_thr_cv);
1054 		return;
1055 	}
1056 
1057 	if (arc.no_grow)
1058 		return;
1059 
1060 	/*
1061 	 * return true if we successfully grow, or if there's enough space that
1062 	 * we don't have to grow.  Above, we return false if we can't grow, or
1063 	 * if we shouldn't because a reclaim is in progress.
1064 	 */
1065 	if ((arc.c - arc.size) <= (2ULL << SPA_MAXBLOCKSHIFT)) {
1066 		if (arc.size_check > 0) {
1067 			arc.size_check = arc_size_check_default;
1068 			atomic_add_64(&arc.incr, arc_incr_size);
1069 		}
1070 		atomic_add_64(&arc.c, MIN(bytes, arc.incr));
1071 		if (arc.c > arc.c_max)
1072 			arc.c = arc.c_max;
1073 		else
1074 			atomic_add_64(&arc.p, MIN(bytes, arc.incr));
1075 	} else if (arc.size > arc.c) {
1076 		if (arc.size_check > 0) {
1077 			arc.size_check = arc_size_check_default;
1078 			atomic_add_64(&arc.incr, arc_incr_size);
1079 		}
1080 		atomic_add_64(&arc.c, MIN(bytes, arc.incr));
1081 		if (arc.c > arc.c_max)
1082 			arc.c = arc.c_max;
1083 		else
1084 			atomic_add_64(&arc.p, MIN(bytes, arc.incr));
1085 	}
1086 }
1087 
1088 /*
1089  * check if the cache has reached its limits and eviction is required prior to
1090  * insert.  In this situation, we want to evict if no_grow is set Otherwise, the
1091  * cache is either big enough that we can insert, or a arc_try_grow will result
1092  * in more space being made available.
1093  */
1094 
1095 static int
1096 arc_evict_needed()
1097 {
1098 
1099 	if (arc_reclaim_needed())
1100 		return (1);
1101 
1102 	if (arc.no_grow || (arc.c > arc.c_max) || (arc.size > arc.c))
1103 		return (1);
1104 
1105 	return (0);
1106 }
1107 
1108 /*
1109  * The state, supplied as the first argument, is going to have something
1110  * inserted on its behalf. So, determine which cache must be victimized to
1111  * satisfy an insertion for this state.  We have the following cases:
1112  *
1113  * 1. Insert for MRU, p > sizeof(arc.anon + arc.mru_top) ->
1114  * In this situation if we're out of space, but the resident size of the MFU is
1115  * under the limit, victimize the MFU cache to satisfy this insertion request.
1116  *
1117  * 2. Insert for MRU, p <= sizeof(arc.anon + arc.mru_top) ->
1118  * Here, we've used up all of the available space for the MRU, so we need to
1119  * evict from our own cache instead.  Evict from the set of resident MRU
1120  * entries.
1121  *
1122  * 3. Insert for MFU (c - p) > sizeof(arc.mfu_top) ->
1123  * c minus p represents the MFU space in the cache, since p is the size of the
1124  * cache that is dedicated to the MRU.  In this situation there's still space on
1125  * the MFU side, so the MRU side needs to be victimized.
1126  *
1127  * 4. Insert for MFU (c - p) < sizeof(arc.mfu_top) ->
1128  * MFU's resident set is consuming more space than it has been allotted.  In
1129  * this situation, we must victimize our own cache, the MFU, for this insertion.
1130  */
1131 static void
1132 arc_evict_for_state(arc_state_t *state, uint64_t bytes)
1133 {
1134 	uint64_t	mru_used;
1135 	uint64_t	mfu_space;
1136 	uint64_t	evicted;
1137 
1138 	ASSERT(state == arc.mru_top || state == arc.mfu_top);
1139 
1140 	if (state == arc.mru_top) {
1141 		mru_used = arc.anon->size + arc.mru_top->size;
1142 		if (arc.p > mru_used) {
1143 			/* case 1 */
1144 			evicted = arc_evict_state(arc.mfu_top, bytes);
1145 			if (evicted < bytes) {
1146 				arc_adjust();
1147 			}
1148 		} else {
1149 			/* case 2 */
1150 			evicted = arc_evict_state(arc.mru_top, bytes);
1151 			if (evicted < bytes) {
1152 				arc_adjust();
1153 			}
1154 		}
1155 	} else {
1156 		/* MFU_top case */
1157 		mfu_space = arc.c - arc.p;
1158 		if (mfu_space > arc.mfu_top->size) {
1159 			/* case 3 */
1160 			evicted = arc_evict_state(arc.mru_top, bytes);
1161 			if (evicted < bytes) {
1162 				arc_adjust();
1163 			}
1164 		} else {
1165 			/* case 4 */
1166 			evicted = arc_evict_state(arc.mfu_top, bytes);
1167 			if (evicted < bytes) {
1168 				arc_adjust();
1169 			}
1170 		}
1171 	}
1172 }
1173 
1174 /*
1175  * This routine is called whenever a buffer is accessed.
1176  */
1177 static void
1178 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
1179 {
1180 	int		blksz, mult;
1181 
1182 	ASSERT(MUTEX_HELD(hash_lock));
1183 
1184 	blksz = buf->b_size;
1185 
1186 	if (buf->b_state == arc.anon) {
1187 		/*
1188 		 * This buffer is not in the cache, and does not
1189 		 * appear in our "ghost" list.  Add the new buffer
1190 		 * to the MRU state.
1191 		 */
1192 
1193 		arc_try_grow(blksz);
1194 		if (arc_evict_needed()) {
1195 			arc_evict_for_state(arc.mru_top, blksz);
1196 		}
1197 
1198 		ASSERT(buf->b_arc_access == 0);
1199 		buf->b_arc_access = lbolt;
1200 		DTRACE_PROBE1(new_state__mru_top, arc_buf_hdr_t *,
1201 		    buf);
1202 		arc_change_state(arc.mru_top, buf, hash_lock);
1203 
1204 		/*
1205 		 * If we are using less than 2/3 of our total target
1206 		 * cache size, bump up the target size for the MRU
1207 		 * list.
1208 		 */
1209 		if (arc.size < arc.c*2/3) {
1210 			arc.p = arc.anon->size + arc.mru_top->size + arc.c/6;
1211 		}
1212 
1213 	} else if (buf->b_state == arc.mru_top) {
1214 		/*
1215 		 * If this buffer is in the MRU-top state and has the prefetch
1216 		 * flag, the first read was actually part of a prefetch.  In
1217 		 * this situation, we simply want to clear the flag and return.
1218 		 * A subsequent access should bump this into the MFU state.
1219 		 */
1220 		if ((buf->b_flags & ARC_PREFETCH) != 0) {
1221 			buf->b_flags &= ~ARC_PREFETCH;
1222 			atomic_add_64(&arc.mru_top->hits, 1);
1223 			return;
1224 		}
1225 
1226 		/*
1227 		 * This buffer has been "accessed" only once so far,
1228 		 * but it is still in the cache. Move it to the MFU
1229 		 * state.
1230 		 */
1231 		if (lbolt > buf->b_arc_access + ARC_MINTIME) {
1232 			/*
1233 			 * More than 125ms have passed since we
1234 			 * instantiated this buffer.  Move it to the
1235 			 * most frequently used state.
1236 			 */
1237 			buf->b_arc_access = lbolt;
1238 			DTRACE_PROBE1(new_state__mfu_top,
1239 			    arc_buf_hdr_t *, buf);
1240 			arc_change_state(arc.mfu_top, buf, hash_lock);
1241 		}
1242 		atomic_add_64(&arc.mru_top->hits, 1);
1243 	} else if (buf->b_state == arc.mru_bot) {
1244 		arc_state_t	*new_state;
1245 		/*
1246 		 * This buffer has been "accessed" recently, but
1247 		 * was evicted from the cache.  Move it to the
1248 		 * MFU state.
1249 		 */
1250 
1251 		if (buf->b_flags & ARC_PREFETCH) {
1252 			new_state = arc.mru_top;
1253 			DTRACE_PROBE1(new_state__mru_top,
1254 			    arc_buf_hdr_t *, buf);
1255 		} else {
1256 			new_state = arc.mfu_top;
1257 			DTRACE_PROBE1(new_state__mfu_top,
1258 			    arc_buf_hdr_t *, buf);
1259 		}
1260 
1261 		arc_try_grow(blksz);
1262 		if (arc_evict_needed()) {
1263 			arc_evict_for_state(new_state, blksz);
1264 		}
1265 
1266 		/* Bump up the target size of the MRU list */
1267 		mult = ((arc.mru_bot->size >= arc.mfu_bot->size) ?
1268 		    1 : (arc.mfu_bot->size/arc.mru_bot->size));
1269 		arc.p = MIN(arc.c, arc.p + blksz * mult);
1270 
1271 		buf->b_arc_access = lbolt;
1272 		arc_change_state(new_state, buf, hash_lock);
1273 
1274 		atomic_add_64(&arc.mru_bot->hits, 1);
1275 	} else if (buf->b_state == arc.mfu_top) {
1276 		/*
1277 		 * This buffer has been accessed more than once and is
1278 		 * still in the cache.  Keep it in the MFU state.
1279 		 *
1280 		 * NOTE: the add_reference() that occurred when we did
1281 		 * the arc_read() should have kicked this off the list,
1282 		 * so even if it was a prefetch, it will be put back at
1283 		 * the head of the list when we remove_reference().
1284 		 */
1285 		atomic_add_64(&arc.mfu_top->hits, 1);
1286 	} else if (buf->b_state == arc.mfu_bot) {
1287 		/*
1288 		 * This buffer has been accessed more than once but has
1289 		 * been evicted from the cache.  Move it back to the
1290 		 * MFU state.
1291 		 */
1292 
1293 		arc_try_grow(blksz);
1294 		if (arc_evict_needed()) {
1295 			arc_evict_for_state(arc.mfu_top, blksz);
1296 		}
1297 
1298 		/* Bump up the target size for the MFU list */
1299 		mult = ((arc.mfu_bot->size >= arc.mru_bot->size) ?
1300 		    1 : (arc.mru_bot->size/arc.mfu_bot->size));
1301 		arc.p = MAX(0, (int64_t)arc.p - blksz * mult);
1302 
1303 		buf->b_arc_access = lbolt;
1304 		DTRACE_PROBE1(new_state__mfu_top,
1305 		    arc_buf_hdr_t *, buf);
1306 		arc_change_state(arc.mfu_top, buf, hash_lock);
1307 
1308 		atomic_add_64(&arc.mfu_bot->hits, 1);
1309 	} else {
1310 		ASSERT(!"invalid arc state");
1311 	}
1312 
1313 }
1314 
1315 /* a generic arc_done_func_t which you can use */
1316 /* ARGSUSED */
1317 void
1318 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
1319 {
1320 	bcopy(buf->b_data, arg, buf->b_hdr->b_size);
1321 	arc_buf_free(buf, arg);
1322 }
1323 
1324 /* a generic arc_done_func_t which you can use */
1325 void
1326 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
1327 {
1328 	arc_buf_t **bufp = arg;
1329 	if (zio && zio->io_error) {
1330 		arc_buf_free(buf, arg);
1331 		*bufp = NULL;
1332 	} else {
1333 		*bufp = buf;
1334 	}
1335 }
1336 
1337 static void
1338 arc_read_done(zio_t *zio)
1339 {
1340 	arc_buf_hdr_t	*hdr;
1341 	arc_buf_t	*buf;
1342 	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
1343 	kmutex_t	*hash_lock;
1344 	arc_callback_t	*callback_list, *acb;
1345 	int		freeable = FALSE;
1346 
1347 	buf = zio->io_private;
1348 	hdr = buf->b_hdr;
1349 
1350 	if (!HDR_FREED_IN_READ(hdr)) {
1351 		arc_buf_hdr_t *found;
1352 
1353 		found = buf_hash_find(zio->io_spa, &hdr->b_dva, hdr->b_birth,
1354 		    &hash_lock);
1355 
1356 		/*
1357 		 * Buffer was inserted into hash-table and removed from lists
1358 		 * prior to starting I/O.  We should find this header, since
1359 		 * it's in the hash table, and it should be legit since it's
1360 		 * not possible to evict it during the I/O.
1361 		 */
1362 
1363 		ASSERT(found);
1364 		ASSERT(DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp)));
1365 	}
1366 
1367 	/* byteswap if necessary */
1368 	callback_list = hdr->b_acb;
1369 	ASSERT(callback_list != NULL);
1370 	if (BP_SHOULD_BYTESWAP(zio->io_bp) && callback_list->acb_byteswap)
1371 		callback_list->acb_byteswap(buf->b_data, hdr->b_size);
1372 
1373 	/* create copies of the data buffer for the callers */
1374 	abuf = buf;
1375 	for (acb = callback_list; acb; acb = acb->acb_next) {
1376 		if (acb->acb_done) {
1377 			if (abuf == NULL) {
1378 				abuf = kmem_cache_alloc(buf_cache, KM_SLEEP);
1379 				abuf->b_data = zio_buf_alloc(hdr->b_size);
1380 				atomic_add_64(&arc.size, hdr->b_size);
1381 				bcopy(buf->b_data, abuf->b_data, hdr->b_size);
1382 				abuf->b_hdr = hdr;
1383 				abuf->b_next = hdr->b_buf;
1384 				hdr->b_buf = abuf;
1385 				atomic_add_64(&hdr->b_state->size, hdr->b_size);
1386 			}
1387 			acb->acb_buf = abuf;
1388 			abuf = NULL;
1389 		} else {
1390 			/*
1391 			 * The caller did not provide a callback function.
1392 			 * In this case, we should just remove the reference.
1393 			 */
1394 			if (HDR_FREED_IN_READ(hdr)) {
1395 				ASSERT3P(hdr->b_state, ==, arc.anon);
1396 				(void) refcount_remove(&hdr->b_refcnt,
1397 				    acb->acb_private);
1398 			} else {
1399 				(void) remove_reference(hdr, hash_lock,
1400 				    acb->acb_private);
1401 			}
1402 		}
1403 	}
1404 	hdr->b_acb = NULL;
1405 	hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
1406 
1407 	ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
1408 
1409 	if (zio->io_error != 0) {
1410 		hdr->b_flags |= ARC_IO_ERROR;
1411 		if (hdr->b_state != arc.anon)
1412 			arc_change_state(arc.anon, hdr, hash_lock);
1413 		freeable = refcount_is_zero(&hdr->b_refcnt);
1414 	}
1415 
1416 	if (!HDR_FREED_IN_READ(hdr)) {
1417 		/*
1418 		 * Only call arc_access on anonymous buffers.  This is because
1419 		 * if we've issued an I/O for an evicted buffer, we've already
1420 		 * called arc_access (to prevent any simultaneous readers from
1421 		 * getting confused).
1422 		 */
1423 		if (zio->io_error == 0 && hdr->b_state == arc.anon)
1424 			arc_access(hdr, hash_lock);
1425 		mutex_exit(hash_lock);
1426 	} else {
1427 		/*
1428 		 * This block was freed while we waited for the read to
1429 		 * complete.  It has been removed from the hash table and
1430 		 * moved to the anonymous state (so that it won't show up
1431 		 * in the cache).
1432 		 */
1433 		ASSERT3P(hdr->b_state, ==, arc.anon);
1434 		freeable = refcount_is_zero(&hdr->b_refcnt);
1435 	}
1436 
1437 	cv_broadcast(&hdr->b_cv);
1438 
1439 	/* execute each callback and free its structure */
1440 	while ((acb = callback_list) != NULL) {
1441 		if (acb->acb_done)
1442 			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
1443 
1444 		if (acb->acb_zio_dummy != NULL) {
1445 			acb->acb_zio_dummy->io_error = zio->io_error;
1446 			zio_nowait(acb->acb_zio_dummy);
1447 		}
1448 
1449 		callback_list = acb->acb_next;
1450 		kmem_free(acb, sizeof (arc_callback_t));
1451 	}
1452 
1453 	if (freeable)
1454 		arc_hdr_free(hdr);
1455 }
1456 
1457 /*
1458  * "Read" the block block at the specified DVA (in bp) via the
1459  * cache.  If the block is found in the cache, invoke the provided
1460  * callback immediately and return.  Note that the `zio' parameter
1461  * in the callback will be NULL in this case, since no IO was
1462  * required.  If the block is not in the cache pass the read request
1463  * on to the spa with a substitute callback function, so that the
1464  * requested block will be added to the cache.
1465  *
1466  * If a read request arrives for a block that has a read in-progress,
1467  * either wait for the in-progress read to complete (and return the
1468  * results); or, if this is a read with a "done" func, add a record
1469  * to the read to invoke the "done" func when the read completes,
1470  * and return; or just return.
1471  *
1472  * arc_read_done() will invoke all the requested "done" functions
1473  * for readers of this block.
1474  */
1475 int
1476 arc_read(zio_t *pio, spa_t *spa, blkptr_t *bp, arc_byteswap_func_t *swap,
1477     arc_done_func_t *done, void *private, int priority, int flags,
1478     uint32_t arc_flags)
1479 {
1480 	arc_buf_hdr_t *hdr;
1481 	arc_buf_t *buf;
1482 	kmutex_t *hash_lock;
1483 	zio_t	*rzio;
1484 
1485 top:
1486 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
1487 	if (hdr && hdr->b_buf) {
1488 
1489 		ASSERT((hdr->b_state == arc.mru_top) ||
1490 		    (hdr->b_state == arc.mfu_top) ||
1491 		    ((hdr->b_state == arc.anon) &&
1492 		    (HDR_IO_IN_PROGRESS(hdr))));
1493 
1494 		if (HDR_IO_IN_PROGRESS(hdr)) {
1495 
1496 			if ((arc_flags & ARC_NOWAIT) && done) {
1497 				arc_callback_t	*acb = NULL;
1498 
1499 				acb = kmem_zalloc(sizeof (arc_callback_t),
1500 				    KM_SLEEP);
1501 				acb->acb_done = done;
1502 				acb->acb_private = private;
1503 				acb->acb_byteswap = swap;
1504 				if (pio != NULL)
1505 					acb->acb_zio_dummy = zio_null(pio,
1506 					    spa, NULL, NULL, flags);
1507 
1508 				ASSERT(acb->acb_done != NULL);
1509 				acb->acb_next = hdr->b_acb;
1510 				hdr->b_acb = acb;
1511 				add_reference(hdr, hash_lock, private);
1512 				mutex_exit(hash_lock);
1513 				return (0);
1514 			} else if (arc_flags & ARC_WAIT) {
1515 				cv_wait(&hdr->b_cv, hash_lock);
1516 				mutex_exit(hash_lock);
1517 				goto top;
1518 			}
1519 
1520 			mutex_exit(hash_lock);
1521 			return (0);
1522 		}
1523 
1524 		/*
1525 		 * If there is already a reference on this block, create
1526 		 * a new copy of the data so that we will be guaranteed
1527 		 * that arc_release() will always succeed.
1528 		 */
1529 
1530 		if (done)
1531 			add_reference(hdr, hash_lock, private);
1532 		if (done && refcount_count(&hdr->b_refcnt) > 1) {
1533 			buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
1534 			buf->b_data = zio_buf_alloc(hdr->b_size);
1535 			ASSERT3U(refcount_count(&hdr->b_refcnt), >, 1);
1536 			atomic_add_64(&arc.size, hdr->b_size);
1537 			bcopy(hdr->b_buf->b_data, buf->b_data, hdr->b_size);
1538 			buf->b_hdr = hdr;
1539 			buf->b_next = hdr->b_buf;
1540 			hdr->b_buf = buf;
1541 			atomic_add_64(&hdr->b_state->size, hdr->b_size);
1542 		} else {
1543 			buf = hdr->b_buf;
1544 		}
1545 		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1546 		arc_access(hdr, hash_lock);
1547 		mutex_exit(hash_lock);
1548 		atomic_add_64(&arc.hits, 1);
1549 		if (done)
1550 			done(NULL, buf, private);
1551 	} else {
1552 		uint64_t size = BP_GET_LSIZE(bp);
1553 		arc_callback_t	*acb;
1554 
1555 		if (hdr == NULL) {
1556 			/* this block is not in the cache */
1557 			arc_buf_hdr_t	*exists;
1558 
1559 			buf = arc_buf_alloc(spa, size, private);
1560 			hdr = buf->b_hdr;
1561 			hdr->b_dva = *BP_IDENTITY(bp);
1562 			hdr->b_birth = bp->blk_birth;
1563 			hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
1564 			exists = buf_hash_insert(hdr, &hash_lock);
1565 			if (exists) {
1566 				/* somebody beat us to the hash insert */
1567 				mutex_exit(hash_lock);
1568 				bzero(&hdr->b_dva, sizeof (dva_t));
1569 				hdr->b_birth = 0;
1570 				hdr->b_cksum0 = 0;
1571 				arc_buf_free(buf, private);
1572 				goto top; /* restart the IO request */
1573 			}
1574 
1575 		} else {
1576 			/* this block is in the ghost cache */
1577 			ASSERT((hdr->b_state == arc.mru_bot) ||
1578 			    (hdr->b_state == arc.mfu_bot));
1579 			add_reference(hdr, hash_lock, private);
1580 
1581 			buf = kmem_cache_alloc(buf_cache, KM_SLEEP);
1582 			buf->b_data = zio_buf_alloc(hdr->b_size);
1583 			atomic_add_64(&arc.size, hdr->b_size);
1584 			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1585 			ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
1586 			buf->b_hdr = hdr;
1587 			buf->b_next = NULL;
1588 			hdr->b_buf = buf;
1589 		}
1590 
1591 		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
1592 		acb->acb_done = done;
1593 		acb->acb_private = private;
1594 		acb->acb_byteswap = swap;
1595 
1596 		ASSERT(hdr->b_acb == NULL);
1597 		hdr->b_acb = acb;
1598 
1599 		/*
1600 		 * If this DVA is part of a prefetch, mark the buf
1601 		 * header with the prefetch flag
1602 		 */
1603 		if (arc_flags & ARC_PREFETCH)
1604 			hdr->b_flags |= ARC_PREFETCH;
1605 		hdr->b_flags |= ARC_IO_IN_PROGRESS;
1606 
1607 		/*
1608 		 * If the buffer has been evicted, migrate it to a present state
1609 		 * before issuing the I/O.  Once we drop the hash-table lock,
1610 		 * the header will be marked as I/O in progress and have an
1611 		 * attached buffer.  At this point, anybody who finds this
1612 		 * buffer ought to notice that it's legit but has a pending I/O.
1613 		 */
1614 
1615 		if ((hdr->b_state == arc.mru_bot) ||
1616 		    (hdr->b_state == arc.mfu_bot))
1617 			arc_access(hdr, hash_lock);
1618 
1619 		mutex_exit(hash_lock);
1620 
1621 		ASSERT3U(hdr->b_size, ==, size);
1622 		DTRACE_PROBE2(arc__miss, blkptr_t *, bp,
1623 		    uint64_t, size);
1624 		atomic_add_64(&arc.misses, 1);
1625 		rzio = zio_read(pio, spa, bp, buf->b_data, size,
1626 		    arc_read_done, buf, priority, flags);
1627 
1628 		if (arc_flags & ARC_WAIT)
1629 			return (zio_wait(rzio));
1630 
1631 		ASSERT(arc_flags & ARC_NOWAIT);
1632 		zio_nowait(rzio);
1633 	}
1634 	return (0);
1635 }
1636 
1637 /*
1638  * arc_read() variant to support pool traversal.  If the block is already
1639  * in the ARC, make a copy of it; otherwise, the caller will do the I/O.
1640  * The idea is that we don't want pool traversal filling up memory, but
1641  * if the ARC already has the data anyway, we shouldn't pay for the I/O.
1642  */
1643 int
1644 arc_tryread(spa_t *spa, blkptr_t *bp, void *data)
1645 {
1646 	arc_buf_hdr_t *hdr;
1647 	kmutex_t *hash_mtx;
1648 	int rc = 0;
1649 
1650 	hdr = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_mtx);
1651 
1652 	if (hdr && hdr->b_buf && !HDR_IO_IN_PROGRESS(hdr))
1653 		bcopy(hdr->b_buf->b_data, data, hdr->b_size);
1654 	else
1655 		rc = ENOENT;
1656 
1657 	if (hash_mtx)
1658 		mutex_exit(hash_mtx);
1659 
1660 	return (rc);
1661 }
1662 
1663 /*
1664  * Release this buffer from the cache.  This must be done
1665  * after a read and prior to modifying the buffer contents.
1666  * If the buffer has more than one reference, we must make
1667  * make a new hdr for the buffer.
1668  */
1669 void
1670 arc_release(arc_buf_t *buf, void *tag)
1671 {
1672 	arc_buf_hdr_t *hdr = buf->b_hdr;
1673 	kmutex_t *hash_lock = HDR_LOCK(hdr);
1674 
1675 	/* this buffer is not on any list */
1676 	ASSERT(refcount_count(&hdr->b_refcnt) > 0);
1677 
1678 	if (hdr->b_state == arc.anon) {
1679 		/* this buffer is already released */
1680 		ASSERT3U(refcount_count(&hdr->b_refcnt), ==, 1);
1681 		ASSERT(BUF_EMPTY(hdr));
1682 		return;
1683 	}
1684 
1685 	mutex_enter(hash_lock);
1686 
1687 	if (refcount_count(&hdr->b_refcnt) > 1) {
1688 		arc_buf_hdr_t *nhdr;
1689 		arc_buf_t **bufp;
1690 		uint64_t blksz = hdr->b_size;
1691 		spa_t *spa = hdr->b_spa;
1692 
1693 		/*
1694 		 * Pull the data off of this buf and attach it to
1695 		 * a new anonymous buf.
1696 		 */
1697 		bufp = &hdr->b_buf;
1698 		while (*bufp != buf) {
1699 			ASSERT(*bufp);
1700 			bufp = &(*bufp)->b_next;
1701 		}
1702 		*bufp = (*bufp)->b_next;
1703 		(void) refcount_remove(&hdr->b_refcnt, tag);
1704 		ASSERT3U(hdr->b_state->size, >=, hdr->b_size);
1705 		atomic_add_64(&hdr->b_state->size, -hdr->b_size);
1706 		mutex_exit(hash_lock);
1707 
1708 		nhdr = kmem_cache_alloc(hdr_cache, KM_SLEEP);
1709 		nhdr->b_size = blksz;
1710 		nhdr->b_spa = spa;
1711 		nhdr->b_buf = buf;
1712 		nhdr->b_state = arc.anon;
1713 		nhdr->b_arc_access = 0;
1714 		nhdr->b_flags = 0;
1715 		buf->b_hdr = nhdr;
1716 		buf->b_next = NULL;
1717 		(void) refcount_add(&nhdr->b_refcnt, tag);
1718 		atomic_add_64(&arc.anon->size, blksz);
1719 
1720 		hdr = nhdr;
1721 	} else {
1722 		ASSERT(!list_link_active(&hdr->b_arc_node));
1723 		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1724 		arc_change_state(arc.anon, hdr, hash_lock);
1725 		hdr->b_arc_access = 0;
1726 		mutex_exit(hash_lock);
1727 		bzero(&hdr->b_dva, sizeof (dva_t));
1728 		hdr->b_birth = 0;
1729 		hdr->b_cksum0 = 0;
1730 	}
1731 }
1732 
1733 int
1734 arc_released(arc_buf_t *buf)
1735 {
1736 	return (buf->b_hdr->b_state == arc.anon);
1737 }
1738 
1739 static void
1740 arc_write_done(zio_t *zio)
1741 {
1742 	arc_buf_t *buf;
1743 	arc_buf_hdr_t *hdr;
1744 	arc_callback_t *acb;
1745 
1746 	buf = zio->io_private;
1747 	hdr = buf->b_hdr;
1748 	acb = hdr->b_acb;
1749 	hdr->b_acb = NULL;
1750 
1751 	/* this buffer is on no lists and is not in the hash table */
1752 	ASSERT3P(hdr->b_state, ==, arc.anon);
1753 
1754 	hdr->b_dva = *BP_IDENTITY(zio->io_bp);
1755 	hdr->b_birth = zio->io_bp->blk_birth;
1756 	hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
1757 	/* clear the "in-write" flag */
1758 	hdr->b_hash_next = NULL;
1759 	/* This write may be all-zero */
1760 	if (!BUF_EMPTY(hdr)) {
1761 		arc_buf_hdr_t *exists;
1762 		kmutex_t *hash_lock;
1763 
1764 		exists = buf_hash_insert(hdr, &hash_lock);
1765 		if (exists) {
1766 			/*
1767 			 * This can only happen if we overwrite for
1768 			 * sync-to-convergence, because we remove
1769 			 * buffers from the hash table when we arc_free().
1770 			 */
1771 			ASSERT(DVA_EQUAL(BP_IDENTITY(&zio->io_bp_orig),
1772 			    BP_IDENTITY(zio->io_bp)));
1773 			ASSERT3U(zio->io_bp_orig.blk_birth, ==,
1774 			    zio->io_bp->blk_birth);
1775 
1776 			ASSERT(refcount_is_zero(&exists->b_refcnt));
1777 			arc_change_state(arc.anon, exists, hash_lock);
1778 			mutex_exit(hash_lock);
1779 			arc_hdr_free(exists);
1780 			exists = buf_hash_insert(hdr, &hash_lock);
1781 			ASSERT3P(exists, ==, NULL);
1782 		}
1783 		arc_access(hdr, hash_lock);
1784 		mutex_exit(hash_lock);
1785 	}
1786 	if (acb && acb->acb_done) {
1787 		ASSERT(!refcount_is_zero(&hdr->b_refcnt));
1788 		acb->acb_done(zio, buf, acb->acb_private);
1789 	}
1790 
1791 	if (acb)
1792 		kmem_free(acb, sizeof (arc_callback_t));
1793 }
1794 
1795 int
1796 arc_write(zio_t *pio, spa_t *spa, int checksum, int compress,
1797     uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
1798     arc_done_func_t *done, void *private, int priority, int flags,
1799     uint32_t arc_flags)
1800 {
1801 	arc_buf_hdr_t *hdr = buf->b_hdr;
1802 	arc_callback_t	*acb;
1803 	zio_t	*rzio;
1804 
1805 	/* this is a private buffer - no locking required */
1806 	ASSERT3P(hdr->b_state, ==, arc.anon);
1807 	ASSERT(BUF_EMPTY(hdr));
1808 	ASSERT(!HDR_IO_ERROR(hdr));
1809 	acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
1810 	acb->acb_done = done;
1811 	acb->acb_private = private;
1812 	acb->acb_byteswap = (arc_byteswap_func_t *)-1;
1813 	hdr->b_acb = acb;
1814 	rzio = zio_write(pio, spa, checksum, compress, txg, bp,
1815 	    buf->b_data, hdr->b_size, arc_write_done, buf, priority, flags);
1816 
1817 	if (arc_flags & ARC_WAIT)
1818 		return (zio_wait(rzio));
1819 
1820 	ASSERT(arc_flags & ARC_NOWAIT);
1821 	zio_nowait(rzio);
1822 
1823 	return (0);
1824 }
1825 
1826 int
1827 arc_free(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp,
1828     zio_done_func_t *done, void *private, uint32_t arc_flags)
1829 {
1830 	arc_buf_hdr_t *ab;
1831 	kmutex_t *hash_lock;
1832 	zio_t	*zio;
1833 
1834 	/*
1835 	 * If this buffer is in the cache, release it, so it
1836 	 * can be re-used.
1837 	 */
1838 	ab = buf_hash_find(spa, BP_IDENTITY(bp), bp->blk_birth, &hash_lock);
1839 	if (ab != NULL) {
1840 		/*
1841 		 * The checksum of blocks to free is not always
1842 		 * preserved (eg. on the deadlist).  However, if it is
1843 		 * nonzero, it should match what we have in the cache.
1844 		 */
1845 		ASSERT(bp->blk_cksum.zc_word[0] == 0 ||
1846 		    ab->b_cksum0 == bp->blk_cksum.zc_word[0]);
1847 		arc_change_state(arc.anon, ab, hash_lock);
1848 		if (refcount_is_zero(&ab->b_refcnt)) {
1849 			mutex_exit(hash_lock);
1850 			arc_hdr_free(ab);
1851 			atomic_add_64(&arc.deleted, 1);
1852 		} else {
1853 			ASSERT3U(refcount_count(&ab->b_refcnt), ==, 1);
1854 			if (HDR_IO_IN_PROGRESS(ab))
1855 				ab->b_flags |= ARC_FREED_IN_READ;
1856 			ab->b_arc_access = 0;
1857 			bzero(&ab->b_dva, sizeof (dva_t));
1858 			ab->b_birth = 0;
1859 			ab->b_cksum0 = 0;
1860 			mutex_exit(hash_lock);
1861 		}
1862 	}
1863 
1864 	zio = zio_free(pio, spa, txg, bp, done, private);
1865 
1866 	if (arc_flags & ARC_WAIT)
1867 		return (zio_wait(zio));
1868 
1869 	ASSERT(arc_flags & ARC_NOWAIT);
1870 	zio_nowait(zio);
1871 
1872 	return (0);
1873 }
1874 
1875 void
1876 arc_tempreserve_clear(uint64_t tempreserve)
1877 {
1878 	atomic_add_64(&arc_tempreserve, -tempreserve);
1879 	ASSERT((int64_t)arc_tempreserve >= 0);
1880 }
1881 
1882 int
1883 arc_tempreserve_space(uint64_t tempreserve)
1884 {
1885 #ifdef ZFS_DEBUG
1886 	/*
1887 	 * Once in a while, fail for no reason.  Everything should cope.
1888 	 */
1889 	if (spa_get_random(10000) == 0) {
1890 		dprintf("forcing random failure\n");
1891 		return (ERESTART);
1892 	}
1893 #endif
1894 	if (tempreserve > arc.c/4 && !arc.no_grow)
1895 		arc.c = MIN(arc.c_max, tempreserve * 4);
1896 	if (tempreserve > arc.c)
1897 		return (ENOMEM);
1898 
1899 	/*
1900 	 * Throttle writes when the amount of dirty data in the cache
1901 	 * gets too large.  We try to keep the cache less than half full
1902 	 * of dirty blocks so that our sync times don't grow too large.
1903 	 * Note: if two requests come in concurrently, we might let them
1904 	 * both succeed, when one of them should fail.  Not a huge deal.
1905 	 *
1906 	 * XXX The limit should be adjusted dynamically to keep the time
1907 	 * to sync a dataset fixed (around 1-5 seconds?).
1908 	 */
1909 
1910 	if (tempreserve + arc_tempreserve + arc.anon->size > arc.c / 2 &&
1911 	    arc_tempreserve + arc.anon->size > arc.c / 4) {
1912 		dprintf("failing, arc_tempreserve=%lluK anon=%lluK "
1913 		    "tempreserve=%lluK arc.c=%lluK\n",
1914 		    arc_tempreserve>>10, arc.anon->lsize>>10,
1915 		    tempreserve>>10, arc.c>>10);
1916 		return (ERESTART);
1917 	}
1918 	atomic_add_64(&arc_tempreserve, tempreserve);
1919 	return (0);
1920 }
1921 
1922 void
1923 arc_init(void)
1924 {
1925 	mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
1926 	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
1927 	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
1928 
1929 	/* Start out with 1/8 of all memory */
1930 	arc.c = physmem * PAGESIZE / 8;
1931 
1932 #ifdef _KERNEL
1933 	/*
1934 	 * On architectures where the physical memory can be larger
1935 	 * than the addressable space (intel in 32-bit mode), we may
1936 	 * need to limit the cache to 1/8 of VM size.
1937 	 */
1938 	arc.c = MIN(arc.c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
1939 #endif
1940 
1941 	/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
1942 	arc.c_min = MAX(arc.c / 4, 64<<20);
1943 	/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
1944 	if (arc.c * 8 >= 1<<30)
1945 		arc.c_max = (arc.c * 8) - (1<<30);
1946 	else
1947 		arc.c_max = arc.c_min;
1948 	arc.c_max = MAX(arc.c * 6, arc.c_max);
1949 	arc.c = arc.c_max;
1950 	arc.p = (arc.c >> 1);
1951 
1952 	/* if kmem_flags are set, lets try to use less memory */
1953 	if (kmem_debugging())
1954 		arc.c = arc.c / 2;
1955 	if (arc.c < arc.c_min)
1956 		arc.c = arc.c_min;
1957 
1958 	arc.anon = &ARC_anon;
1959 	arc.mru_top = &ARC_mru_top;
1960 	arc.mru_bot = &ARC_mru_bot;
1961 	arc.mfu_top = &ARC_mfu_top;
1962 	arc.mfu_bot = &ARC_mfu_bot;
1963 
1964 	list_create(&arc.mru_top->list, sizeof (arc_buf_hdr_t),
1965 	    offsetof(arc_buf_hdr_t, b_arc_node));
1966 	list_create(&arc.mru_bot->list, sizeof (arc_buf_hdr_t),
1967 	    offsetof(arc_buf_hdr_t, b_arc_node));
1968 	list_create(&arc.mfu_top->list, sizeof (arc_buf_hdr_t),
1969 	    offsetof(arc_buf_hdr_t, b_arc_node));
1970 	list_create(&arc.mfu_bot->list, sizeof (arc_buf_hdr_t),
1971 	    offsetof(arc_buf_hdr_t, b_arc_node));
1972 
1973 	buf_init();
1974 
1975 	arc_thread_exit = 0;
1976 
1977 	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
1978 	    TS_RUN, minclsyspri);
1979 }
1980 
1981 void
1982 arc_fini(void)
1983 {
1984 	mutex_enter(&arc_reclaim_thr_lock);
1985 	arc_thread_exit = 1;
1986 	while (arc_thread_exit != 0)
1987 		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
1988 	mutex_exit(&arc_reclaim_thr_lock);
1989 
1990 	arc_flush();
1991 
1992 	arc_dead = TRUE;
1993 
1994 	mutex_destroy(&arc_reclaim_lock);
1995 	mutex_destroy(&arc_reclaim_thr_lock);
1996 	cv_destroy(&arc_reclaim_thr_cv);
1997 
1998 	list_destroy(&arc.mru_top->list);
1999 	list_destroy(&arc.mru_bot->list);
2000 	list_destroy(&arc.mfu_top->list);
2001 	list_destroy(&arc.mfu_bot->list);
2002 
2003 	buf_fini();
2004 }
2005