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