arc.c revision 286655
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
24 * Copyright (c) 2011, 2014 by Delphix. All rights reserved.
25 * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26 * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
27 */
28
29/*
30 * DVA-based Adjustable Replacement Cache
31 *
32 * While much of the theory of operation used here is
33 * 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 slows the flow of new data
52 * into the cache until we can make space available.
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 pressure 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 therefore 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 therefore 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() interface
80 * uses method 1, while the internal arc algorithms for
81 * adjusting the cache use method 2.  We therefore 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 active state mutex must be held before the ghost state mutex.
101 *
102 * Arc buffers may have an associated eviction callback function.
103 * This function will be invoked prior to removing the buffer (e.g.
104 * in arc_do_user_evicts()).  Note however that the data associated
105 * with the buffer may be evicted prior to the callback.  The callback
106 * must be made with *no locks held* (to prevent deadlock).  Additionally,
107 * the users of callbacks must ensure that their private data is
108 * protected from simultaneous callbacks from arc_clear_callback()
109 * and arc_do_user_evicts().
110 *
111 * Note that the majority of the performance stats are manipulated
112 * with atomic operations.
113 *
114 * The L2ARC uses the l2ad_mtx on each vdev for the following:
115 *
116 *	- L2ARC buflist creation
117 *	- L2ARC buflist eviction
118 *	- L2ARC write completion, which walks L2ARC buflists
119 *	- ARC header destruction, as it removes from L2ARC buflists
120 *	- ARC header release, as it removes from L2ARC buflists
121 */
122
123#include <sys/spa.h>
124#include <sys/zio.h>
125#include <sys/zio_compress.h>
126#include <sys/zfs_context.h>
127#include <sys/arc.h>
128#include <sys/refcount.h>
129#include <sys/vdev.h>
130#include <sys/vdev_impl.h>
131#include <sys/dsl_pool.h>
132#ifdef _KERNEL
133#include <sys/dnlc.h>
134#endif
135#include <sys/callb.h>
136#include <sys/kstat.h>
137#include <sys/trim_map.h>
138#include <zfs_fletcher.h>
139#include <sys/sdt.h>
140
141#include <vm/vm_pageout.h>
142#include <machine/vmparam.h>
143
144#ifdef illumos
145#ifndef _KERNEL
146/* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
147boolean_t arc_watch = B_FALSE;
148int arc_procfd;
149#endif
150#endif /* illumos */
151
152static kmutex_t		arc_reclaim_thr_lock;
153static kcondvar_t	arc_reclaim_thr_cv;	/* used to signal reclaim thr */
154static uint8_t		arc_thread_exit;
155
156uint_t arc_reduce_dnlc_percent = 3;
157
158/*
159 * The number of iterations through arc_evict_*() before we
160 * drop & reacquire the lock.
161 */
162int arc_evict_iterations = 100;
163
164/* number of seconds before growing cache again */
165static int		arc_grow_retry = 60;
166
167/* shift of arc_c for calculating both min and max arc_p */
168static int		arc_p_min_shift = 4;
169
170/* log2(fraction of arc to reclaim) */
171static int		arc_shrink_shift = 7;
172
173/*
174 * log2(fraction of ARC which must be free to allow growing).
175 * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
176 * when reading a new block into the ARC, we will evict an equal-sized block
177 * from the ARC.
178 *
179 * This must be less than arc_shrink_shift, so that when we shrink the ARC,
180 * we will still not allow it to grow.
181 */
182int			arc_no_grow_shift = 5;
183
184
185/*
186 * minimum lifespan of a prefetch block in clock ticks
187 * (initialized in arc_init())
188 */
189static int		arc_min_prefetch_lifespan;
190
191/*
192 * If this percent of memory is free, don't throttle.
193 */
194int arc_lotsfree_percent = 10;
195
196static int arc_dead;
197extern int zfs_prefetch_disable;
198
199/*
200 * The arc has filled available memory and has now warmed up.
201 */
202static boolean_t arc_warm;
203
204uint64_t zfs_arc_max;
205uint64_t zfs_arc_min;
206uint64_t zfs_arc_meta_limit = 0;
207uint64_t zfs_arc_meta_min = 0;
208int zfs_arc_grow_retry = 0;
209int zfs_arc_shrink_shift = 0;
210int zfs_arc_p_min_shift = 0;
211int zfs_disable_dup_eviction = 0;
212uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
213u_int zfs_arc_free_target = 0;
214
215static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
216static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
217
218#ifdef _KERNEL
219static void
220arc_free_target_init(void *unused __unused)
221{
222
223	zfs_arc_free_target = vm_pageout_wakeup_thresh;
224}
225SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
226    arc_free_target_init, NULL);
227
228TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
229TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
230TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
231SYSCTL_DECL(_vfs_zfs);
232SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_max, CTLFLAG_RDTUN, &zfs_arc_max, 0,
233    "Maximum ARC size");
234SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_min, CTLFLAG_RDTUN, &zfs_arc_min, 0,
235    "Minimum ARC size");
236SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
237    &zfs_arc_average_blocksize, 0,
238    "ARC average blocksize");
239SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
240    &arc_shrink_shift, 0,
241    "log2(fraction of arc to reclaim)");
242
243/*
244 * We don't have a tunable for arc_free_target due to the dependency on
245 * pagedaemon initialisation.
246 */
247SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
248    CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
249    sysctl_vfs_zfs_arc_free_target, "IU",
250    "Desired number of free pages below which ARC triggers reclaim");
251
252static int
253sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
254{
255	u_int val;
256	int err;
257
258	val = zfs_arc_free_target;
259	err = sysctl_handle_int(oidp, &val, 0, req);
260	if (err != 0 || req->newptr == NULL)
261		return (err);
262
263	if (val < minfree)
264		return (EINVAL);
265	if (val > vm_cnt.v_page_count)
266		return (EINVAL);
267
268	zfs_arc_free_target = val;
269
270	return (0);
271}
272
273/*
274 * Must be declared here, before the definition of corresponding kstat
275 * macro which uses the same names will confuse the compiler.
276 */
277SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
278    CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
279    sysctl_vfs_zfs_arc_meta_limit, "QU",
280    "ARC metadata limit");
281#endif
282
283/*
284 * Note that buffers can be in one of 6 states:
285 *	ARC_anon	- anonymous (discussed below)
286 *	ARC_mru		- recently used, currently cached
287 *	ARC_mru_ghost	- recentely used, no longer in cache
288 *	ARC_mfu		- frequently used, currently cached
289 *	ARC_mfu_ghost	- frequently used, no longer in cache
290 *	ARC_l2c_only	- exists in L2ARC but not other states
291 * When there are no active references to the buffer, they are
292 * are linked onto a list in one of these arc states.  These are
293 * the only buffers that can be evicted or deleted.  Within each
294 * state there are multiple lists, one for meta-data and one for
295 * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
296 * etc.) is tracked separately so that it can be managed more
297 * explicitly: favored over data, limited explicitly.
298 *
299 * Anonymous buffers are buffers that are not associated with
300 * a DVA.  These are buffers that hold dirty block copies
301 * before they are written to stable storage.  By definition,
302 * they are "ref'd" and are considered part of arc_mru
303 * that cannot be freed.  Generally, they will aquire a DVA
304 * as they are written and migrate onto the arc_mru list.
305 *
306 * The ARC_l2c_only state is for buffers that are in the second
307 * level ARC but no longer in any of the ARC_m* lists.  The second
308 * level ARC itself may also contain buffers that are in any of
309 * the ARC_m* states - meaning that a buffer can exist in two
310 * places.  The reason for the ARC_l2c_only state is to keep the
311 * buffer header in the hash table, so that reads that hit the
312 * second level ARC benefit from these fast lookups.
313 */
314
315#define	ARCS_LOCK_PAD		CACHE_LINE_SIZE
316struct arcs_lock {
317	kmutex_t	arcs_lock;
318#ifdef _KERNEL
319	unsigned char	pad[(ARCS_LOCK_PAD - sizeof (kmutex_t))];
320#endif
321};
322
323/*
324 * must be power of two for mask use to work
325 *
326 */
327#define ARC_BUFC_NUMDATALISTS		16
328#define ARC_BUFC_NUMMETADATALISTS	16
329#define ARC_BUFC_NUMLISTS	(ARC_BUFC_NUMMETADATALISTS + ARC_BUFC_NUMDATALISTS)
330
331typedef struct arc_state {
332	uint64_t arcs_lsize[ARC_BUFC_NUMTYPES];	/* amount of evictable data */
333	uint64_t arcs_size;	/* total amount of data in this state */
334	list_t	arcs_lists[ARC_BUFC_NUMLISTS]; /* list of evictable buffers */
335	struct arcs_lock arcs_locks[ARC_BUFC_NUMLISTS] __aligned(CACHE_LINE_SIZE);
336} arc_state_t;
337
338#define ARCS_LOCK(s, i)	(&((s)->arcs_locks[(i)].arcs_lock))
339
340/* The 6 states: */
341static arc_state_t ARC_anon;
342static arc_state_t ARC_mru;
343static arc_state_t ARC_mru_ghost;
344static arc_state_t ARC_mfu;
345static arc_state_t ARC_mfu_ghost;
346static arc_state_t ARC_l2c_only;
347
348typedef struct arc_stats {
349	kstat_named_t arcstat_hits;
350	kstat_named_t arcstat_misses;
351	kstat_named_t arcstat_demand_data_hits;
352	kstat_named_t arcstat_demand_data_misses;
353	kstat_named_t arcstat_demand_metadata_hits;
354	kstat_named_t arcstat_demand_metadata_misses;
355	kstat_named_t arcstat_prefetch_data_hits;
356	kstat_named_t arcstat_prefetch_data_misses;
357	kstat_named_t arcstat_prefetch_metadata_hits;
358	kstat_named_t arcstat_prefetch_metadata_misses;
359	kstat_named_t arcstat_mru_hits;
360	kstat_named_t arcstat_mru_ghost_hits;
361	kstat_named_t arcstat_mfu_hits;
362	kstat_named_t arcstat_mfu_ghost_hits;
363	kstat_named_t arcstat_allocated;
364	kstat_named_t arcstat_deleted;
365	kstat_named_t arcstat_stolen;
366	kstat_named_t arcstat_recycle_miss;
367	/*
368	 * Number of buffers that could not be evicted because the hash lock
369	 * was held by another thread.  The lock may not necessarily be held
370	 * by something using the same buffer, since hash locks are shared
371	 * by multiple buffers.
372	 */
373	kstat_named_t arcstat_mutex_miss;
374	/*
375	 * Number of buffers skipped because they have I/O in progress, are
376	 * indrect prefetch buffers that have not lived long enough, or are
377	 * not from the spa we're trying to evict from.
378	 */
379	kstat_named_t arcstat_evict_skip;
380	kstat_named_t arcstat_evict_l2_cached;
381	kstat_named_t arcstat_evict_l2_eligible;
382	kstat_named_t arcstat_evict_l2_ineligible;
383	kstat_named_t arcstat_hash_elements;
384	kstat_named_t arcstat_hash_elements_max;
385	kstat_named_t arcstat_hash_collisions;
386	kstat_named_t arcstat_hash_chains;
387	kstat_named_t arcstat_hash_chain_max;
388	kstat_named_t arcstat_p;
389	kstat_named_t arcstat_c;
390	kstat_named_t arcstat_c_min;
391	kstat_named_t arcstat_c_max;
392	kstat_named_t arcstat_size;
393	/*
394	 * Number of bytes consumed by internal ARC structures necessary
395	 * for tracking purposes; these structures are not actually
396	 * backed by ARC buffers. This includes arc_buf_hdr_t structures
397	 * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
398	 * caches), and arc_buf_t structures (allocated via arc_buf_t
399	 * cache).
400	 */
401	kstat_named_t arcstat_hdr_size;
402	/*
403	 * Number of bytes consumed by ARC buffers of type equal to
404	 * ARC_BUFC_DATA. This is generally consumed by buffers backing
405	 * on disk user data (e.g. plain file contents).
406	 */
407	kstat_named_t arcstat_data_size;
408	/*
409	 * Number of bytes consumed by ARC buffers of type equal to
410	 * ARC_BUFC_METADATA. This is generally consumed by buffers
411	 * backing on disk data that is used for internal ZFS
412	 * structures (e.g. ZAP, dnode, indirect blocks, etc).
413	 */
414	kstat_named_t arcstat_metadata_size;
415	/*
416	 * Number of bytes consumed by various buffers and structures
417	 * not actually backed with ARC buffers. This includes bonus
418	 * buffers (allocated directly via zio_buf_* functions),
419	 * dmu_buf_impl_t structures (allocated via dmu_buf_impl_t
420	 * cache), and dnode_t structures (allocated via dnode_t cache).
421	 */
422	kstat_named_t arcstat_other_size;
423	/*
424	 * Total number of bytes consumed by ARC buffers residing in the
425	 * arc_anon state. This includes *all* buffers in the arc_anon
426	 * state; e.g. data, metadata, evictable, and unevictable buffers
427	 * are all included in this value.
428	 */
429	kstat_named_t arcstat_anon_size;
430	/*
431	 * Number of bytes consumed by ARC buffers that meet the
432	 * following criteria: backing buffers of type ARC_BUFC_DATA,
433	 * residing in the arc_anon state, and are eligible for eviction
434	 * (e.g. have no outstanding holds on the buffer).
435	 */
436	kstat_named_t arcstat_anon_evictable_data;
437	/*
438	 * Number of bytes consumed by ARC buffers that meet the
439	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
440	 * residing in the arc_anon state, and are eligible for eviction
441	 * (e.g. have no outstanding holds on the buffer).
442	 */
443	kstat_named_t arcstat_anon_evictable_metadata;
444	/*
445	 * Total number of bytes consumed by ARC buffers residing in the
446	 * arc_mru state. This includes *all* buffers in the arc_mru
447	 * state; e.g. data, metadata, evictable, and unevictable buffers
448	 * are all included in this value.
449	 */
450	kstat_named_t arcstat_mru_size;
451	/*
452	 * Number of bytes consumed by ARC buffers that meet the
453	 * following criteria: backing buffers of type ARC_BUFC_DATA,
454	 * residing in the arc_mru state, and are eligible for eviction
455	 * (e.g. have no outstanding holds on the buffer).
456	 */
457	kstat_named_t arcstat_mru_evictable_data;
458	/*
459	 * Number of bytes consumed by ARC buffers that meet the
460	 * following criteria: backing buffers of type ARC_BUFC_METADATA,
461	 * residing in the arc_mru state, and are eligible for eviction
462	 * (e.g. have no outstanding holds on the buffer).
463	 */
464	kstat_named_t arcstat_mru_evictable_metadata;
465	/*
466	 * Total number of bytes that *would have been* consumed by ARC
467	 * buffers in the arc_mru_ghost state. The key thing to note
468	 * here, is the fact that this size doesn't actually indicate
469	 * RAM consumption. The ghost lists only consist of headers and
470	 * don't actually have ARC buffers linked off of these headers.
471	 * Thus, *if* the headers had associated ARC buffers, these
472	 * buffers *would have* consumed this number of bytes.
473	 */
474	kstat_named_t arcstat_mru_ghost_size;
475	/*
476	 * Number of bytes that *would have been* consumed by ARC
477	 * buffers that are eligible for eviction, of type
478	 * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
479	 */
480	kstat_named_t arcstat_mru_ghost_evictable_data;
481	/*
482	 * Number of bytes that *would have been* consumed by ARC
483	 * buffers that are eligible for eviction, of type
484	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
485	 */
486	kstat_named_t arcstat_mru_ghost_evictable_metadata;
487	/*
488	 * Total number of bytes consumed by ARC buffers residing in the
489	 * arc_mfu state. This includes *all* buffers in the arc_mfu
490	 * state; e.g. data, metadata, evictable, and unevictable buffers
491	 * are all included in this value.
492	 */
493	kstat_named_t arcstat_mfu_size;
494	/*
495	 * Number of bytes consumed by ARC buffers that are eligible for
496	 * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
497	 * state.
498	 */
499	kstat_named_t arcstat_mfu_evictable_data;
500	/*
501	 * Number of bytes consumed by ARC buffers that are eligible for
502	 * eviction, of type ARC_BUFC_METADATA, and reside in the
503	 * arc_mfu state.
504	 */
505	kstat_named_t arcstat_mfu_evictable_metadata;
506	/*
507	 * Total number of bytes that *would have been* consumed by ARC
508	 * buffers in the arc_mfu_ghost state. See the comment above
509	 * arcstat_mru_ghost_size for more details.
510	 */
511	kstat_named_t arcstat_mfu_ghost_size;
512	/*
513	 * Number of bytes that *would have been* consumed by ARC
514	 * buffers that are eligible for eviction, of type
515	 * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
516	 */
517	kstat_named_t arcstat_mfu_ghost_evictable_data;
518	/*
519	 * Number of bytes that *would have been* consumed by ARC
520	 * buffers that are eligible for eviction, of type
521	 * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
522	 */
523	kstat_named_t arcstat_mfu_ghost_evictable_metadata;
524	kstat_named_t arcstat_l2_hits;
525	kstat_named_t arcstat_l2_misses;
526	kstat_named_t arcstat_l2_feeds;
527	kstat_named_t arcstat_l2_rw_clash;
528	kstat_named_t arcstat_l2_read_bytes;
529	kstat_named_t arcstat_l2_write_bytes;
530	kstat_named_t arcstat_l2_writes_sent;
531	kstat_named_t arcstat_l2_writes_done;
532	kstat_named_t arcstat_l2_writes_error;
533	kstat_named_t arcstat_l2_writes_hdr_miss;
534	kstat_named_t arcstat_l2_evict_lock_retry;
535	kstat_named_t arcstat_l2_evict_reading;
536	kstat_named_t arcstat_l2_evict_l1cached;
537	kstat_named_t arcstat_l2_free_on_write;
538	kstat_named_t arcstat_l2_cdata_free_on_write;
539	kstat_named_t arcstat_l2_abort_lowmem;
540	kstat_named_t arcstat_l2_cksum_bad;
541	kstat_named_t arcstat_l2_io_error;
542	kstat_named_t arcstat_l2_size;
543	kstat_named_t arcstat_l2_asize;
544	kstat_named_t arcstat_l2_hdr_size;
545	kstat_named_t arcstat_l2_compress_successes;
546	kstat_named_t arcstat_l2_compress_zeros;
547	kstat_named_t arcstat_l2_compress_failures;
548	kstat_named_t arcstat_l2_write_trylock_fail;
549	kstat_named_t arcstat_l2_write_passed_headroom;
550	kstat_named_t arcstat_l2_write_spa_mismatch;
551	kstat_named_t arcstat_l2_write_in_l2;
552	kstat_named_t arcstat_l2_write_hdr_io_in_progress;
553	kstat_named_t arcstat_l2_write_not_cacheable;
554	kstat_named_t arcstat_l2_write_full;
555	kstat_named_t arcstat_l2_write_buffer_iter;
556	kstat_named_t arcstat_l2_write_pios;
557	kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
558	kstat_named_t arcstat_l2_write_buffer_list_iter;
559	kstat_named_t arcstat_l2_write_buffer_list_null_iter;
560	kstat_named_t arcstat_memory_throttle_count;
561	kstat_named_t arcstat_duplicate_buffers;
562	kstat_named_t arcstat_duplicate_buffers_size;
563	kstat_named_t arcstat_duplicate_reads;
564	kstat_named_t arcstat_meta_used;
565	kstat_named_t arcstat_meta_limit;
566	kstat_named_t arcstat_meta_max;
567	kstat_named_t arcstat_meta_min;
568} arc_stats_t;
569
570static arc_stats_t arc_stats = {
571	{ "hits",			KSTAT_DATA_UINT64 },
572	{ "misses",			KSTAT_DATA_UINT64 },
573	{ "demand_data_hits",		KSTAT_DATA_UINT64 },
574	{ "demand_data_misses",		KSTAT_DATA_UINT64 },
575	{ "demand_metadata_hits",	KSTAT_DATA_UINT64 },
576	{ "demand_metadata_misses",	KSTAT_DATA_UINT64 },
577	{ "prefetch_data_hits",		KSTAT_DATA_UINT64 },
578	{ "prefetch_data_misses",	KSTAT_DATA_UINT64 },
579	{ "prefetch_metadata_hits",	KSTAT_DATA_UINT64 },
580	{ "prefetch_metadata_misses",	KSTAT_DATA_UINT64 },
581	{ "mru_hits",			KSTAT_DATA_UINT64 },
582	{ "mru_ghost_hits",		KSTAT_DATA_UINT64 },
583	{ "mfu_hits",			KSTAT_DATA_UINT64 },
584	{ "mfu_ghost_hits",		KSTAT_DATA_UINT64 },
585	{ "allocated",			KSTAT_DATA_UINT64 },
586	{ "deleted",			KSTAT_DATA_UINT64 },
587	{ "stolen",			KSTAT_DATA_UINT64 },
588	{ "recycle_miss",		KSTAT_DATA_UINT64 },
589	{ "mutex_miss",			KSTAT_DATA_UINT64 },
590	{ "evict_skip",			KSTAT_DATA_UINT64 },
591	{ "evict_l2_cached",		KSTAT_DATA_UINT64 },
592	{ "evict_l2_eligible",		KSTAT_DATA_UINT64 },
593	{ "evict_l2_ineligible",	KSTAT_DATA_UINT64 },
594	{ "hash_elements",		KSTAT_DATA_UINT64 },
595	{ "hash_elements_max",		KSTAT_DATA_UINT64 },
596	{ "hash_collisions",		KSTAT_DATA_UINT64 },
597	{ "hash_chains",		KSTAT_DATA_UINT64 },
598	{ "hash_chain_max",		KSTAT_DATA_UINT64 },
599	{ "p",				KSTAT_DATA_UINT64 },
600	{ "c",				KSTAT_DATA_UINT64 },
601	{ "c_min",			KSTAT_DATA_UINT64 },
602	{ "c_max",			KSTAT_DATA_UINT64 },
603	{ "size",			KSTAT_DATA_UINT64 },
604	{ "hdr_size",			KSTAT_DATA_UINT64 },
605	{ "data_size",			KSTAT_DATA_UINT64 },
606	{ "metadata_size",		KSTAT_DATA_UINT64 },
607	{ "other_size",			KSTAT_DATA_UINT64 },
608	{ "anon_size",			KSTAT_DATA_UINT64 },
609	{ "anon_evictable_data",	KSTAT_DATA_UINT64 },
610	{ "anon_evictable_metadata",	KSTAT_DATA_UINT64 },
611	{ "mru_size",			KSTAT_DATA_UINT64 },
612	{ "mru_evictable_data",		KSTAT_DATA_UINT64 },
613	{ "mru_evictable_metadata",	KSTAT_DATA_UINT64 },
614	{ "mru_ghost_size",		KSTAT_DATA_UINT64 },
615	{ "mru_ghost_evictable_data",	KSTAT_DATA_UINT64 },
616	{ "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
617	{ "mfu_size",			KSTAT_DATA_UINT64 },
618	{ "mfu_evictable_data",		KSTAT_DATA_UINT64 },
619	{ "mfu_evictable_metadata",	KSTAT_DATA_UINT64 },
620	{ "mfu_ghost_size",		KSTAT_DATA_UINT64 },
621	{ "mfu_ghost_evictable_data",	KSTAT_DATA_UINT64 },
622	{ "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
623	{ "l2_hits",			KSTAT_DATA_UINT64 },
624	{ "l2_misses",			KSTAT_DATA_UINT64 },
625	{ "l2_feeds",			KSTAT_DATA_UINT64 },
626	{ "l2_rw_clash",		KSTAT_DATA_UINT64 },
627	{ "l2_read_bytes",		KSTAT_DATA_UINT64 },
628	{ "l2_write_bytes",		KSTAT_DATA_UINT64 },
629	{ "l2_writes_sent",		KSTAT_DATA_UINT64 },
630	{ "l2_writes_done",		KSTAT_DATA_UINT64 },
631	{ "l2_writes_error",		KSTAT_DATA_UINT64 },
632	{ "l2_writes_hdr_miss",		KSTAT_DATA_UINT64 },
633	{ "l2_evict_lock_retry",	KSTAT_DATA_UINT64 },
634	{ "l2_evict_reading",		KSTAT_DATA_UINT64 },
635	{ "l2_evict_l1cached",		KSTAT_DATA_UINT64 },
636	{ "l2_free_on_write",		KSTAT_DATA_UINT64 },
637	{ "l2_cdata_free_on_write",	KSTAT_DATA_UINT64 },
638	{ "l2_abort_lowmem",		KSTAT_DATA_UINT64 },
639	{ "l2_cksum_bad",		KSTAT_DATA_UINT64 },
640	{ "l2_io_error",		KSTAT_DATA_UINT64 },
641	{ "l2_size",			KSTAT_DATA_UINT64 },
642	{ "l2_asize",			KSTAT_DATA_UINT64 },
643	{ "l2_hdr_size",		KSTAT_DATA_UINT64 },
644	{ "l2_compress_successes",	KSTAT_DATA_UINT64 },
645	{ "l2_compress_zeros",		KSTAT_DATA_UINT64 },
646	{ "l2_compress_failures",	KSTAT_DATA_UINT64 },
647	{ "l2_write_trylock_fail",	KSTAT_DATA_UINT64 },
648	{ "l2_write_passed_headroom",	KSTAT_DATA_UINT64 },
649	{ "l2_write_spa_mismatch",	KSTAT_DATA_UINT64 },
650	{ "l2_write_in_l2",		KSTAT_DATA_UINT64 },
651	{ "l2_write_io_in_progress",	KSTAT_DATA_UINT64 },
652	{ "l2_write_not_cacheable",	KSTAT_DATA_UINT64 },
653	{ "l2_write_full",		KSTAT_DATA_UINT64 },
654	{ "l2_write_buffer_iter",	KSTAT_DATA_UINT64 },
655	{ "l2_write_pios",		KSTAT_DATA_UINT64 },
656	{ "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
657	{ "l2_write_buffer_list_iter",	KSTAT_DATA_UINT64 },
658	{ "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
659	{ "memory_throttle_count",	KSTAT_DATA_UINT64 },
660	{ "duplicate_buffers",		KSTAT_DATA_UINT64 },
661	{ "duplicate_buffers_size",	KSTAT_DATA_UINT64 },
662	{ "duplicate_reads",		KSTAT_DATA_UINT64 },
663	{ "arc_meta_used",		KSTAT_DATA_UINT64 },
664	{ "arc_meta_limit",		KSTAT_DATA_UINT64 },
665	{ "arc_meta_max",		KSTAT_DATA_UINT64 },
666	{ "arc_meta_min",		KSTAT_DATA_UINT64 }
667};
668
669#define	ARCSTAT(stat)	(arc_stats.stat.value.ui64)
670
671#define	ARCSTAT_INCR(stat, val) \
672	atomic_add_64(&arc_stats.stat.value.ui64, (val))
673
674#define	ARCSTAT_BUMP(stat)	ARCSTAT_INCR(stat, 1)
675#define	ARCSTAT_BUMPDOWN(stat)	ARCSTAT_INCR(stat, -1)
676
677#define	ARCSTAT_MAX(stat, val) {					\
678	uint64_t m;							\
679	while ((val) > (m = arc_stats.stat.value.ui64) &&		\
680	    (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val))))	\
681		continue;						\
682}
683
684#define	ARCSTAT_MAXSTAT(stat) \
685	ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
686
687/*
688 * We define a macro to allow ARC hits/misses to be easily broken down by
689 * two separate conditions, giving a total of four different subtypes for
690 * each of hits and misses (so eight statistics total).
691 */
692#define	ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
693	if (cond1) {							\
694		if (cond2) {						\
695			ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
696		} else {						\
697			ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
698		}							\
699	} else {							\
700		if (cond2) {						\
701			ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
702		} else {						\
703			ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
704		}							\
705	}
706
707kstat_t			*arc_ksp;
708static arc_state_t	*arc_anon;
709static arc_state_t	*arc_mru;
710static arc_state_t	*arc_mru_ghost;
711static arc_state_t	*arc_mfu;
712static arc_state_t	*arc_mfu_ghost;
713static arc_state_t	*arc_l2c_only;
714
715/*
716 * There are several ARC variables that are critical to export as kstats --
717 * but we don't want to have to grovel around in the kstat whenever we wish to
718 * manipulate them.  For these variables, we therefore define them to be in
719 * terms of the statistic variable.  This assures that we are not introducing
720 * the possibility of inconsistency by having shadow copies of the variables,
721 * while still allowing the code to be readable.
722 */
723#define	arc_size	ARCSTAT(arcstat_size)	/* actual total arc size */
724#define	arc_p		ARCSTAT(arcstat_p)	/* target size of MRU */
725#define	arc_c		ARCSTAT(arcstat_c)	/* target size of cache */
726#define	arc_c_min	ARCSTAT(arcstat_c_min)	/* min target cache size */
727#define	arc_c_max	ARCSTAT(arcstat_c_max)	/* max target cache size */
728#define	arc_meta_limit	ARCSTAT(arcstat_meta_limit) /* max size for metadata */
729#define	arc_meta_min	ARCSTAT(arcstat_meta_min) /* min size for metadata */
730#define	arc_meta_used	ARCSTAT(arcstat_meta_used) /* size of metadata */
731#define	arc_meta_max	ARCSTAT(arcstat_meta_max) /* max size of metadata */
732
733#define	L2ARC_IS_VALID_COMPRESS(_c_) \
734	((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
735
736static int		arc_no_grow;	/* Don't try to grow cache size */
737static uint64_t		arc_tempreserve;
738static uint64_t		arc_loaned_bytes;
739
740typedef struct arc_callback arc_callback_t;
741
742struct arc_callback {
743	void			*acb_private;
744	arc_done_func_t		*acb_done;
745	arc_buf_t		*acb_buf;
746	zio_t			*acb_zio_dummy;
747	arc_callback_t		*acb_next;
748};
749
750typedef struct arc_write_callback arc_write_callback_t;
751
752struct arc_write_callback {
753	void		*awcb_private;
754	arc_done_func_t	*awcb_ready;
755	arc_done_func_t	*awcb_physdone;
756	arc_done_func_t	*awcb_done;
757	arc_buf_t	*awcb_buf;
758};
759
760/*
761 * ARC buffers are separated into multiple structs as a memory saving measure:
762 *   - Common fields struct, always defined, and embedded within it:
763 *       - L2-only fields, always allocated but undefined when not in L2ARC
764 *       - L1-only fields, only allocated when in L1ARC
765 *
766 *           Buffer in L1                     Buffer only in L2
767 *    +------------------------+          +------------------------+
768 *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
769 *    |                        |          |                        |
770 *    |                        |          |                        |
771 *    |                        |          |                        |
772 *    +------------------------+          +------------------------+
773 *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
774 *    | (undefined if L1-only) |          |                        |
775 *    +------------------------+          +------------------------+
776 *    | l1arc_buf_hdr_t        |
777 *    |                        |
778 *    |                        |
779 *    |                        |
780 *    |                        |
781 *    +------------------------+
782 *
783 * Because it's possible for the L2ARC to become extremely large, we can wind
784 * up eating a lot of memory in L2ARC buffer headers, so the size of a header
785 * is minimized by only allocating the fields necessary for an L1-cached buffer
786 * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
787 * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
788 * words in pointers. arc_hdr_realloc() is used to switch a header between
789 * these two allocation states.
790 */
791typedef struct l1arc_buf_hdr {
792	kmutex_t		b_freeze_lock;
793#ifdef ZFS_DEBUG
794	/*
795	 * used for debugging wtih kmem_flags - by allocating and freeing
796	 * b_thawed when the buffer is thawed, we get a record of the stack
797	 * trace that thawed it.
798	 */
799	void			*b_thawed;
800#endif
801
802	arc_buf_t		*b_buf;
803	uint32_t		b_datacnt;
804	/* for waiting on writes to complete */
805	kcondvar_t		b_cv;
806
807	/* protected by arc state mutex */
808	arc_state_t		*b_state;
809	list_node_t		b_arc_node;
810
811	/* updated atomically */
812	clock_t			b_arc_access;
813
814	/* self protecting */
815	refcount_t		b_refcnt;
816
817	arc_callback_t		*b_acb;
818	/* temporary buffer holder for in-flight compressed data */
819	void			*b_tmp_cdata;
820} l1arc_buf_hdr_t;
821
822typedef struct l2arc_dev l2arc_dev_t;
823
824typedef struct l2arc_buf_hdr {
825	/* protected by arc_buf_hdr mutex */
826	l2arc_dev_t		*b_dev;		/* L2ARC device */
827	uint64_t		b_daddr;	/* disk address, offset byte */
828	/* real alloc'd buffer size depending on b_compress applied */
829	int32_t			b_asize;
830
831	list_node_t		b_l2node;
832} l2arc_buf_hdr_t;
833
834struct arc_buf_hdr {
835	/* protected by hash lock */
836	dva_t			b_dva;
837	uint64_t		b_birth;
838	/*
839	 * Even though this checksum is only set/verified when a buffer is in
840	 * the L1 cache, it needs to be in the set of common fields because it
841	 * must be preserved from the time before a buffer is written out to
842	 * L2ARC until after it is read back in.
843	 */
844	zio_cksum_t		*b_freeze_cksum;
845
846	arc_buf_hdr_t		*b_hash_next;
847	arc_flags_t		b_flags;
848
849	/* immutable */
850	int32_t			b_size;
851	uint64_t		b_spa;
852
853	/* L2ARC fields. Undefined when not in L2ARC. */
854	l2arc_buf_hdr_t		b_l2hdr;
855	/* L1ARC fields. Undefined when in l2arc_only state */
856	l1arc_buf_hdr_t		b_l1hdr;
857};
858
859#ifdef _KERNEL
860static int
861sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
862{
863	uint64_t val;
864	int err;
865
866	val = arc_meta_limit;
867	err = sysctl_handle_64(oidp, &val, 0, req);
868	if (err != 0 || req->newptr == NULL)
869		return (err);
870
871        if (val <= 0 || val > arc_c_max)
872		return (EINVAL);
873
874	arc_meta_limit = val;
875	return (0);
876}
877#endif
878
879static arc_buf_t *arc_eviction_list;
880static kmutex_t arc_eviction_mtx;
881static arc_buf_hdr_t arc_eviction_hdr;
882
883#define	GHOST_STATE(state)	\
884	((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||	\
885	(state) == arc_l2c_only)
886
887#define	HDR_IN_HASH_TABLE(hdr)	((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
888#define	HDR_IO_IN_PROGRESS(hdr)	((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
889#define	HDR_IO_ERROR(hdr)	((hdr)->b_flags & ARC_FLAG_IO_ERROR)
890#define	HDR_PREFETCH(hdr)	((hdr)->b_flags & ARC_FLAG_PREFETCH)
891#define	HDR_FREED_IN_READ(hdr)	((hdr)->b_flags & ARC_FLAG_FREED_IN_READ)
892#define	HDR_BUF_AVAILABLE(hdr)	((hdr)->b_flags & ARC_FLAG_BUF_AVAILABLE)
893
894#define	HDR_L2CACHE(hdr)	((hdr)->b_flags & ARC_FLAG_L2CACHE)
895#define	HDR_L2COMPRESS(hdr)	((hdr)->b_flags & ARC_FLAG_L2COMPRESS)
896#define	HDR_L2_READING(hdr)	\
897	    (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&	\
898	    ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
899#define	HDR_L2_WRITING(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITING)
900#define	HDR_L2_EVICTED(hdr)	((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
901#define	HDR_L2_WRITE_HEAD(hdr)	((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
902
903#define	HDR_ISTYPE_METADATA(hdr)	\
904	    ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
905#define	HDR_ISTYPE_DATA(hdr)	(!HDR_ISTYPE_METADATA(hdr))
906
907#define	HDR_HAS_L1HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
908#define	HDR_HAS_L2HDR(hdr)	((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
909
910/* For storing compression mode in b_flags */
911#define	HDR_COMPRESS_OFFSET	24
912#define	HDR_COMPRESS_NBITS	7
913
914#define	HDR_GET_COMPRESS(hdr)	((enum zio_compress)BF32_GET(hdr->b_flags, \
915	    HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS))
916#define	HDR_SET_COMPRESS(hdr, cmp) BF32_SET(hdr->b_flags, \
917	    HDR_COMPRESS_OFFSET, HDR_COMPRESS_NBITS, (cmp))
918
919/*
920 * Other sizes
921 */
922
923#define	HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
924#define	HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
925
926/*
927 * Hash table routines
928 */
929
930#define	HT_LOCK_PAD	CACHE_LINE_SIZE
931
932struct ht_lock {
933	kmutex_t	ht_lock;
934#ifdef _KERNEL
935	unsigned char	pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
936#endif
937};
938
939#define	BUF_LOCKS 256
940typedef struct buf_hash_table {
941	uint64_t ht_mask;
942	arc_buf_hdr_t **ht_table;
943	struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
944} buf_hash_table_t;
945
946static buf_hash_table_t buf_hash_table;
947
948#define	BUF_HASH_INDEX(spa, dva, birth) \
949	(buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
950#define	BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
951#define	BUF_HASH_LOCK(idx)	(&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
952#define	HDR_LOCK(hdr) \
953	(BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
954
955uint64_t zfs_crc64_table[256];
956
957/*
958 * Level 2 ARC
959 */
960
961#define	L2ARC_WRITE_SIZE	(8 * 1024 * 1024)	/* initial write max */
962#define	L2ARC_HEADROOM		2			/* num of writes */
963/*
964 * If we discover during ARC scan any buffers to be compressed, we boost
965 * our headroom for the next scanning cycle by this percentage multiple.
966 */
967#define	L2ARC_HEADROOM_BOOST	200
968#define	L2ARC_FEED_SECS		1		/* caching interval secs */
969#define	L2ARC_FEED_MIN_MS	200		/* min caching interval ms */
970
971/*
972 * Used to distinguish headers that are being process by
973 * l2arc_write_buffers(), but have yet to be assigned to a l2arc disk
974 * address. This can happen when the header is added to the l2arc's list
975 * of buffers to write in the first stage of l2arc_write_buffers(), but
976 * has not yet been written out which happens in the second stage of
977 * l2arc_write_buffers().
978 */
979#define	L2ARC_ADDR_UNSET	((uint64_t)(-1))
980
981#define	l2arc_writes_sent	ARCSTAT(arcstat_l2_writes_sent)
982#define	l2arc_writes_done	ARCSTAT(arcstat_l2_writes_done)
983
984/* L2ARC Performance Tunables */
985uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;	/* default max write size */
986uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;	/* extra write during warmup */
987uint64_t l2arc_headroom = L2ARC_HEADROOM;	/* number of dev writes */
988uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
989uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;	/* interval seconds */
990uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS;	/* min interval milliseconds */
991boolean_t l2arc_noprefetch = B_TRUE;		/* don't cache prefetch bufs */
992boolean_t l2arc_feed_again = B_TRUE;		/* turbo warmup */
993boolean_t l2arc_norw = B_TRUE;			/* no reads during writes */
994
995SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
996    &l2arc_write_max, 0, "max write size");
997SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
998    &l2arc_write_boost, 0, "extra write during warmup");
999SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1000    &l2arc_headroom, 0, "number of dev writes");
1001SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1002    &l2arc_feed_secs, 0, "interval seconds");
1003SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1004    &l2arc_feed_min_ms, 0, "min interval milliseconds");
1005
1006SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1007    &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1008SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1009    &l2arc_feed_again, 0, "turbo warmup");
1010SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1011    &l2arc_norw, 0, "no reads during writes");
1012
1013SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1014    &ARC_anon.arcs_size, 0, "size of anonymous state");
1015SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_lsize, CTLFLAG_RD,
1016    &ARC_anon.arcs_lsize[ARC_BUFC_METADATA], 0, "size of anonymous state");
1017SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_lsize, CTLFLAG_RD,
1018    &ARC_anon.arcs_lsize[ARC_BUFC_DATA], 0, "size of anonymous state");
1019
1020SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1021    &ARC_mru.arcs_size, 0, "size of mru state");
1022SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_lsize, CTLFLAG_RD,
1023    &ARC_mru.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mru state");
1024SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_lsize, CTLFLAG_RD,
1025    &ARC_mru.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mru state");
1026
1027SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1028    &ARC_mru_ghost.arcs_size, 0, "size of mru ghost state");
1029SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_lsize, CTLFLAG_RD,
1030    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1031    "size of metadata in mru ghost state");
1032SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_lsize, CTLFLAG_RD,
1033    &ARC_mru_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1034    "size of data in mru ghost state");
1035
1036SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1037    &ARC_mfu.arcs_size, 0, "size of mfu state");
1038SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_lsize, CTLFLAG_RD,
1039    &ARC_mfu.arcs_lsize[ARC_BUFC_METADATA], 0, "size of metadata in mfu state");
1040SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_lsize, CTLFLAG_RD,
1041    &ARC_mfu.arcs_lsize[ARC_BUFC_DATA], 0, "size of data in mfu state");
1042
1043SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1044    &ARC_mfu_ghost.arcs_size, 0, "size of mfu ghost state");
1045SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_lsize, CTLFLAG_RD,
1046    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_METADATA], 0,
1047    "size of metadata in mfu ghost state");
1048SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_lsize, CTLFLAG_RD,
1049    &ARC_mfu_ghost.arcs_lsize[ARC_BUFC_DATA], 0,
1050    "size of data in mfu ghost state");
1051
1052SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1053    &ARC_l2c_only.arcs_size, 0, "size of mru state");
1054
1055/*
1056 * L2ARC Internals
1057 */
1058struct l2arc_dev {
1059	vdev_t			*l2ad_vdev;	/* vdev */
1060	spa_t			*l2ad_spa;	/* spa */
1061	uint64_t		l2ad_hand;	/* next write location */
1062	uint64_t		l2ad_start;	/* first addr on device */
1063	uint64_t		l2ad_end;	/* last addr on device */
1064	boolean_t		l2ad_first;	/* first sweep through */
1065	boolean_t		l2ad_writing;	/* currently writing */
1066	kmutex_t		l2ad_mtx;	/* lock for buffer list */
1067	list_t			l2ad_buflist;	/* buffer list */
1068	list_node_t		l2ad_node;	/* device list node */
1069	refcount_t		l2ad_alloc;	/* allocated bytes */
1070};
1071
1072static list_t L2ARC_dev_list;			/* device list */
1073static list_t *l2arc_dev_list;			/* device list pointer */
1074static kmutex_t l2arc_dev_mtx;			/* device list mutex */
1075static l2arc_dev_t *l2arc_dev_last;		/* last device used */
1076static list_t L2ARC_free_on_write;		/* free after write buf list */
1077static list_t *l2arc_free_on_write;		/* free after write list ptr */
1078static kmutex_t l2arc_free_on_write_mtx;	/* mutex for list */
1079static uint64_t l2arc_ndev;			/* number of devices */
1080
1081typedef struct l2arc_read_callback {
1082	arc_buf_t		*l2rcb_buf;		/* read buffer */
1083	spa_t			*l2rcb_spa;		/* spa */
1084	blkptr_t		l2rcb_bp;		/* original blkptr */
1085	zbookmark_phys_t	l2rcb_zb;		/* original bookmark */
1086	int			l2rcb_flags;		/* original flags */
1087	enum zio_compress	l2rcb_compress;		/* applied compress */
1088} l2arc_read_callback_t;
1089
1090typedef struct l2arc_write_callback {
1091	l2arc_dev_t	*l2wcb_dev;		/* device info */
1092	arc_buf_hdr_t	*l2wcb_head;		/* head of write buflist */
1093} l2arc_write_callback_t;
1094
1095typedef struct l2arc_data_free {
1096	/* protected by l2arc_free_on_write_mtx */
1097	void		*l2df_data;
1098	size_t		l2df_size;
1099	void		(*l2df_func)(void *, size_t);
1100	list_node_t	l2df_list_node;
1101} l2arc_data_free_t;
1102
1103static kmutex_t l2arc_feed_thr_lock;
1104static kcondvar_t l2arc_feed_thr_cv;
1105static uint8_t l2arc_thread_exit;
1106
1107static void arc_get_data_buf(arc_buf_t *);
1108static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1109static int arc_evict_needed(arc_buf_contents_t);
1110static void arc_evict_ghost(arc_state_t *, uint64_t, int64_t);
1111static void arc_buf_watch(arc_buf_t *);
1112
1113static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1114static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1115
1116static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1117static void l2arc_read_done(zio_t *);
1118
1119static boolean_t l2arc_compress_buf(arc_buf_hdr_t *);
1120static void l2arc_decompress_zio(zio_t *, arc_buf_hdr_t *, enum zio_compress);
1121static void l2arc_release_cdata_buf(arc_buf_hdr_t *);
1122
1123static uint64_t
1124buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1125{
1126	uint8_t *vdva = (uint8_t *)dva;
1127	uint64_t crc = -1ULL;
1128	int i;
1129
1130	ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
1131
1132	for (i = 0; i < sizeof (dva_t); i++)
1133		crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
1134
1135	crc ^= (spa>>8) ^ birth;
1136
1137	return (crc);
1138}
1139
1140#define	BUF_EMPTY(buf)						\
1141	((buf)->b_dva.dva_word[0] == 0 &&			\
1142	(buf)->b_dva.dva_word[1] == 0)
1143
1144#define	BUF_EQUAL(spa, dva, birth, buf)				\
1145	((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&	\
1146	((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&	\
1147	((buf)->b_birth == birth) && ((buf)->b_spa == spa)
1148
1149static void
1150buf_discard_identity(arc_buf_hdr_t *hdr)
1151{
1152	hdr->b_dva.dva_word[0] = 0;
1153	hdr->b_dva.dva_word[1] = 0;
1154	hdr->b_birth = 0;
1155}
1156
1157static arc_buf_hdr_t *
1158buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1159{
1160	const dva_t *dva = BP_IDENTITY(bp);
1161	uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1162	uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1163	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1164	arc_buf_hdr_t *hdr;
1165
1166	mutex_enter(hash_lock);
1167	for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1168	    hdr = hdr->b_hash_next) {
1169		if (BUF_EQUAL(spa, dva, birth, hdr)) {
1170			*lockp = hash_lock;
1171			return (hdr);
1172		}
1173	}
1174	mutex_exit(hash_lock);
1175	*lockp = NULL;
1176	return (NULL);
1177}
1178
1179/*
1180 * Insert an entry into the hash table.  If there is already an element
1181 * equal to elem in the hash table, then the already existing element
1182 * will be returned and the new element will not be inserted.
1183 * Otherwise returns NULL.
1184 * If lockp == NULL, the caller is assumed to already hold the hash lock.
1185 */
1186static arc_buf_hdr_t *
1187buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1188{
1189	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1190	kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1191	arc_buf_hdr_t *fhdr;
1192	uint32_t i;
1193
1194	ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1195	ASSERT(hdr->b_birth != 0);
1196	ASSERT(!HDR_IN_HASH_TABLE(hdr));
1197
1198	if (lockp != NULL) {
1199		*lockp = hash_lock;
1200		mutex_enter(hash_lock);
1201	} else {
1202		ASSERT(MUTEX_HELD(hash_lock));
1203	}
1204
1205	for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1206	    fhdr = fhdr->b_hash_next, i++) {
1207		if (BUF_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1208			return (fhdr);
1209	}
1210
1211	hdr->b_hash_next = buf_hash_table.ht_table[idx];
1212	buf_hash_table.ht_table[idx] = hdr;
1213	hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
1214
1215	/* collect some hash table performance data */
1216	if (i > 0) {
1217		ARCSTAT_BUMP(arcstat_hash_collisions);
1218		if (i == 1)
1219			ARCSTAT_BUMP(arcstat_hash_chains);
1220
1221		ARCSTAT_MAX(arcstat_hash_chain_max, i);
1222	}
1223
1224	ARCSTAT_BUMP(arcstat_hash_elements);
1225	ARCSTAT_MAXSTAT(arcstat_hash_elements);
1226
1227	return (NULL);
1228}
1229
1230static void
1231buf_hash_remove(arc_buf_hdr_t *hdr)
1232{
1233	arc_buf_hdr_t *fhdr, **hdrp;
1234	uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1235
1236	ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1237	ASSERT(HDR_IN_HASH_TABLE(hdr));
1238
1239	hdrp = &buf_hash_table.ht_table[idx];
1240	while ((fhdr = *hdrp) != hdr) {
1241		ASSERT(fhdr != NULL);
1242		hdrp = &fhdr->b_hash_next;
1243	}
1244	*hdrp = hdr->b_hash_next;
1245	hdr->b_hash_next = NULL;
1246	hdr->b_flags &= ~ARC_FLAG_IN_HASH_TABLE;
1247
1248	/* collect some hash table performance data */
1249	ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1250
1251	if (buf_hash_table.ht_table[idx] &&
1252	    buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1253		ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1254}
1255
1256/*
1257 * Global data structures and functions for the buf kmem cache.
1258 */
1259static kmem_cache_t *hdr_full_cache;
1260static kmem_cache_t *hdr_l2only_cache;
1261static kmem_cache_t *buf_cache;
1262
1263static void
1264buf_fini(void)
1265{
1266	int i;
1267
1268	kmem_free(buf_hash_table.ht_table,
1269	    (buf_hash_table.ht_mask + 1) * sizeof (void *));
1270	for (i = 0; i < BUF_LOCKS; i++)
1271		mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1272	kmem_cache_destroy(hdr_full_cache);
1273	kmem_cache_destroy(hdr_l2only_cache);
1274	kmem_cache_destroy(buf_cache);
1275}
1276
1277/*
1278 * Constructor callback - called when the cache is empty
1279 * and a new buf is requested.
1280 */
1281/* ARGSUSED */
1282static int
1283hdr_full_cons(void *vbuf, void *unused, int kmflag)
1284{
1285	arc_buf_hdr_t *hdr = vbuf;
1286
1287	bzero(hdr, HDR_FULL_SIZE);
1288	cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1289	refcount_create(&hdr->b_l1hdr.b_refcnt);
1290	mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1291	arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1292
1293	return (0);
1294}
1295
1296/* ARGSUSED */
1297static int
1298hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1299{
1300	arc_buf_hdr_t *hdr = vbuf;
1301
1302	bzero(hdr, HDR_L2ONLY_SIZE);
1303	arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1304
1305	return (0);
1306}
1307
1308/* ARGSUSED */
1309static int
1310buf_cons(void *vbuf, void *unused, int kmflag)
1311{
1312	arc_buf_t *buf = vbuf;
1313
1314	bzero(buf, sizeof (arc_buf_t));
1315	mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1316	arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1317
1318	return (0);
1319}
1320
1321/*
1322 * Destructor callback - called when a cached buf is
1323 * no longer required.
1324 */
1325/* ARGSUSED */
1326static void
1327hdr_full_dest(void *vbuf, void *unused)
1328{
1329	arc_buf_hdr_t *hdr = vbuf;
1330
1331	ASSERT(BUF_EMPTY(hdr));
1332	cv_destroy(&hdr->b_l1hdr.b_cv);
1333	refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1334	mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1335	arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1336}
1337
1338/* ARGSUSED */
1339static void
1340hdr_l2only_dest(void *vbuf, void *unused)
1341{
1342	arc_buf_hdr_t *hdr = vbuf;
1343
1344	ASSERT(BUF_EMPTY(hdr));
1345	arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1346}
1347
1348/* ARGSUSED */
1349static void
1350buf_dest(void *vbuf, void *unused)
1351{
1352	arc_buf_t *buf = vbuf;
1353
1354	mutex_destroy(&buf->b_evict_lock);
1355	arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1356}
1357
1358/*
1359 * Reclaim callback -- invoked when memory is low.
1360 */
1361/* ARGSUSED */
1362static void
1363hdr_recl(void *unused)
1364{
1365	dprintf("hdr_recl called\n");
1366	/*
1367	 * umem calls the reclaim func when we destroy the buf cache,
1368	 * which is after we do arc_fini().
1369	 */
1370	if (!arc_dead)
1371		cv_signal(&arc_reclaim_thr_cv);
1372}
1373
1374static void
1375buf_init(void)
1376{
1377	uint64_t *ct;
1378	uint64_t hsize = 1ULL << 12;
1379	int i, j;
1380
1381	/*
1382	 * The hash table is big enough to fill all of physical memory
1383	 * with an average block size of zfs_arc_average_blocksize (default 8K).
1384	 * By default, the table will take up
1385	 * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1386	 */
1387	while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1388		hsize <<= 1;
1389retry:
1390	buf_hash_table.ht_mask = hsize - 1;
1391	buf_hash_table.ht_table =
1392	    kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1393	if (buf_hash_table.ht_table == NULL) {
1394		ASSERT(hsize > (1ULL << 8));
1395		hsize >>= 1;
1396		goto retry;
1397	}
1398
1399	hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1400	    0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1401	hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1402	    HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1403	    NULL, NULL, 0);
1404	buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1405	    0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1406
1407	for (i = 0; i < 256; i++)
1408		for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1409			*ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1410
1411	for (i = 0; i < BUF_LOCKS; i++) {
1412		mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1413		    NULL, MUTEX_DEFAULT, NULL);
1414	}
1415}
1416
1417/*
1418 * Transition between the two allocation states for the arc_buf_hdr struct.
1419 * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
1420 * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
1421 * version is used when a cache buffer is only in the L2ARC in order to reduce
1422 * memory usage.
1423 */
1424static arc_buf_hdr_t *
1425arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
1426{
1427	ASSERT(HDR_HAS_L2HDR(hdr));
1428
1429	arc_buf_hdr_t *nhdr;
1430	l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1431
1432	ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
1433	    (old == hdr_l2only_cache && new == hdr_full_cache));
1434
1435	nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
1436
1437	ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
1438	buf_hash_remove(hdr);
1439
1440	bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
1441
1442	if (new == hdr_full_cache) {
1443		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1444		/*
1445		 * arc_access and arc_change_state need to be aware that a
1446		 * header has just come out of L2ARC, so we set its state to
1447		 * l2c_only even though it's about to change.
1448		 */
1449		nhdr->b_l1hdr.b_state = arc_l2c_only;
1450	} else {
1451		ASSERT(hdr->b_l1hdr.b_buf == NULL);
1452		ASSERT0(hdr->b_l1hdr.b_datacnt);
1453		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
1454		/*
1455		 * We might be removing the L1hdr of a buffer which was just
1456		 * written out to L2ARC. If such a buffer is compressed then we
1457		 * need to free its b_tmp_cdata before destroying the header.
1458		 */
1459		if (hdr->b_l1hdr.b_tmp_cdata != NULL &&
1460		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
1461			l2arc_release_cdata_buf(hdr);
1462		nhdr->b_flags &= ~ARC_FLAG_HAS_L1HDR;
1463	}
1464	/*
1465	 * The header has been reallocated so we need to re-insert it into any
1466	 * lists it was on.
1467	 */
1468	(void) buf_hash_insert(nhdr, NULL);
1469
1470	ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
1471
1472	mutex_enter(&dev->l2ad_mtx);
1473
1474	/*
1475	 * We must place the realloc'ed header back into the list at
1476	 * the same spot. Otherwise, if it's placed earlier in the list,
1477	 * l2arc_write_buffers() could find it during the function's
1478	 * write phase, and try to write it out to the l2arc.
1479	 */
1480	list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
1481	list_remove(&dev->l2ad_buflist, hdr);
1482
1483	mutex_exit(&dev->l2ad_mtx);
1484
1485	/*
1486	 * Since we're using the pointer address as the tag when
1487	 * incrementing and decrementing the l2ad_alloc refcount, we
1488	 * must remove the old pointer (that we're about to destroy) and
1489	 * add the new pointer to the refcount. Otherwise we'd remove
1490	 * the wrong pointer address when calling arc_hdr_destroy() later.
1491	 */
1492
1493	(void) refcount_remove_many(&dev->l2ad_alloc,
1494	    hdr->b_l2hdr.b_asize, hdr);
1495
1496	(void) refcount_add_many(&dev->l2ad_alloc,
1497	    nhdr->b_l2hdr.b_asize, nhdr);
1498
1499	buf_discard_identity(hdr);
1500	hdr->b_freeze_cksum = NULL;
1501	kmem_cache_free(old, hdr);
1502
1503	return (nhdr);
1504}
1505
1506
1507#define	ARC_MINTIME	(hz>>4) /* 62 ms */
1508
1509static void
1510arc_cksum_verify(arc_buf_t *buf)
1511{
1512	zio_cksum_t zc;
1513
1514	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1515		return;
1516
1517	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1518	if (buf->b_hdr->b_freeze_cksum == NULL || HDR_IO_ERROR(buf->b_hdr)) {
1519		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1520		return;
1521	}
1522	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1523	if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1524		panic("buffer modified while frozen!");
1525	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1526}
1527
1528static int
1529arc_cksum_equal(arc_buf_t *buf)
1530{
1531	zio_cksum_t zc;
1532	int equal;
1533
1534	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1535	fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1536	equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1537	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1538
1539	return (equal);
1540}
1541
1542static void
1543arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1544{
1545	if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1546		return;
1547
1548	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1549	if (buf->b_hdr->b_freeze_cksum != NULL) {
1550		mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1551		return;
1552	}
1553	buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t), KM_SLEEP);
1554	fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1555	    buf->b_hdr->b_freeze_cksum);
1556	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1557#ifdef illumos
1558	arc_buf_watch(buf);
1559#endif
1560}
1561
1562#ifdef illumos
1563#ifndef _KERNEL
1564typedef struct procctl {
1565	long cmd;
1566	prwatch_t prwatch;
1567} procctl_t;
1568#endif
1569
1570/* ARGSUSED */
1571static void
1572arc_buf_unwatch(arc_buf_t *buf)
1573{
1574#ifndef _KERNEL
1575	if (arc_watch) {
1576		int result;
1577		procctl_t ctl;
1578		ctl.cmd = PCWATCH;
1579		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1580		ctl.prwatch.pr_size = 0;
1581		ctl.prwatch.pr_wflags = 0;
1582		result = write(arc_procfd, &ctl, sizeof (ctl));
1583		ASSERT3U(result, ==, sizeof (ctl));
1584	}
1585#endif
1586}
1587
1588/* ARGSUSED */
1589static void
1590arc_buf_watch(arc_buf_t *buf)
1591{
1592#ifndef _KERNEL
1593	if (arc_watch) {
1594		int result;
1595		procctl_t ctl;
1596		ctl.cmd = PCWATCH;
1597		ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
1598		ctl.prwatch.pr_size = buf->b_hdr->b_size;
1599		ctl.prwatch.pr_wflags = WA_WRITE;
1600		result = write(arc_procfd, &ctl, sizeof (ctl));
1601		ASSERT3U(result, ==, sizeof (ctl));
1602	}
1603#endif
1604}
1605#endif /* illumos */
1606
1607static arc_buf_contents_t
1608arc_buf_type(arc_buf_hdr_t *hdr)
1609{
1610	if (HDR_ISTYPE_METADATA(hdr)) {
1611		return (ARC_BUFC_METADATA);
1612	} else {
1613		return (ARC_BUFC_DATA);
1614	}
1615}
1616
1617static uint32_t
1618arc_bufc_to_flags(arc_buf_contents_t type)
1619{
1620	switch (type) {
1621	case ARC_BUFC_DATA:
1622		/* metadata field is 0 if buffer contains normal data */
1623		return (0);
1624	case ARC_BUFC_METADATA:
1625		return (ARC_FLAG_BUFC_METADATA);
1626	default:
1627		break;
1628	}
1629	panic("undefined ARC buffer type!");
1630	return ((uint32_t)-1);
1631}
1632
1633void
1634arc_buf_thaw(arc_buf_t *buf)
1635{
1636	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1637		if (buf->b_hdr->b_l1hdr.b_state != arc_anon)
1638			panic("modifying non-anon buffer!");
1639		if (HDR_IO_IN_PROGRESS(buf->b_hdr))
1640			panic("modifying buffer while i/o in progress!");
1641		arc_cksum_verify(buf);
1642	}
1643
1644	mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1645	if (buf->b_hdr->b_freeze_cksum != NULL) {
1646		kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1647		buf->b_hdr->b_freeze_cksum = NULL;
1648	}
1649
1650#ifdef ZFS_DEBUG
1651	if (zfs_flags & ZFS_DEBUG_MODIFY) {
1652		if (buf->b_hdr->b_l1hdr.b_thawed != NULL)
1653			kmem_free(buf->b_hdr->b_l1hdr.b_thawed, 1);
1654		buf->b_hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
1655	}
1656#endif
1657
1658	mutex_exit(&buf->b_hdr->b_l1hdr.b_freeze_lock);
1659
1660#ifdef illumos
1661	arc_buf_unwatch(buf);
1662#endif
1663}
1664
1665void
1666arc_buf_freeze(arc_buf_t *buf)
1667{
1668	kmutex_t *hash_lock;
1669
1670	if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1671		return;
1672
1673	hash_lock = HDR_LOCK(buf->b_hdr);
1674	mutex_enter(hash_lock);
1675
1676	ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1677	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
1678	arc_cksum_compute(buf, B_FALSE);
1679	mutex_exit(hash_lock);
1680
1681}
1682
1683static void
1684get_buf_info(arc_buf_hdr_t *hdr, arc_state_t *state, list_t **list, kmutex_t **lock)
1685{
1686	uint64_t buf_hashid = buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1687
1688	if (arc_buf_type(hdr) == ARC_BUFC_METADATA)
1689		buf_hashid &= (ARC_BUFC_NUMMETADATALISTS - 1);
1690	else {
1691		buf_hashid &= (ARC_BUFC_NUMDATALISTS - 1);
1692		buf_hashid += ARC_BUFC_NUMMETADATALISTS;
1693	}
1694
1695	*list = &state->arcs_lists[buf_hashid];
1696	*lock = ARCS_LOCK(state, buf_hashid);
1697}
1698
1699
1700static void
1701add_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1702{
1703	ASSERT(HDR_HAS_L1HDR(hdr));
1704	ASSERT(MUTEX_HELD(hash_lock));
1705	arc_state_t *state = hdr->b_l1hdr.b_state;
1706
1707	if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
1708	    (state != arc_anon)) {
1709		/* We don't use the L2-only state list. */
1710		if (state != arc_l2c_only) {
1711			uint64_t delta = hdr->b_size * hdr->b_l1hdr.b_datacnt;
1712			uint64_t *size = &state->arcs_lsize[arc_buf_type(hdr)];
1713			list_t *list;
1714			kmutex_t *lock;
1715
1716			get_buf_info(hdr, state, &list, &lock);
1717			ASSERT(!MUTEX_HELD(lock));
1718			mutex_enter(lock);
1719			ASSERT(list_link_active(&hdr->b_l1hdr.b_arc_node));
1720			list_remove(list, hdr);
1721			if (GHOST_STATE(state)) {
1722				ASSERT0(hdr->b_l1hdr.b_datacnt);
1723				ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
1724				delta = hdr->b_size;
1725			}
1726			ASSERT(delta > 0);
1727			ASSERT3U(*size, >=, delta);
1728			atomic_add_64(size, -delta);
1729			mutex_exit(lock);
1730		}
1731		/* remove the prefetch flag if we get a reference */
1732		hdr->b_flags &= ~ARC_FLAG_PREFETCH;
1733	}
1734}
1735
1736static int
1737remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
1738{
1739	int cnt;
1740	arc_state_t *state = hdr->b_l1hdr.b_state;
1741
1742	ASSERT(HDR_HAS_L1HDR(hdr));
1743	ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1744	ASSERT(!GHOST_STATE(state));
1745
1746	/*
1747	 * arc_l2c_only counts as a ghost state so we don't need to explicitly
1748	 * check to prevent usage of the arc_l2c_only list.
1749	 */
1750	if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
1751	    (state != arc_anon)) {
1752		uint64_t *size = &state->arcs_lsize[arc_buf_type(hdr)];
1753		list_t *list;
1754		kmutex_t *lock;
1755
1756		get_buf_info(hdr, state, &list, &lock);
1757		ASSERT(!MUTEX_HELD(lock));
1758		mutex_enter(lock);
1759		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
1760		list_insert_head(list, hdr);
1761		ASSERT(hdr->b_l1hdr.b_datacnt > 0);
1762		atomic_add_64(size, hdr->b_size *
1763		    hdr->b_l1hdr.b_datacnt);
1764		mutex_exit(lock);
1765	}
1766	return (cnt);
1767}
1768
1769/*
1770 * Move the supplied buffer to the indicated state.  The mutex
1771 * for the buffer must be held by the caller.
1772 */
1773static void
1774arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
1775    kmutex_t *hash_lock)
1776{
1777	arc_state_t *old_state;
1778	int64_t refcnt;
1779	uint32_t datacnt;
1780	uint64_t from_delta, to_delta;
1781	arc_buf_contents_t buftype = arc_buf_type(hdr);
1782	list_t *list;
1783	kmutex_t *lock;
1784
1785	/*
1786	 * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
1787	 * in arc_read() when bringing a buffer out of the L2ARC.  However, the
1788	 * L1 hdr doesn't always exist when we change state to arc_anon before
1789	 * destroying a header, in which case reallocating to add the L1 hdr is
1790	 * pointless.
1791	 */
1792	if (HDR_HAS_L1HDR(hdr)) {
1793		old_state = hdr->b_l1hdr.b_state;
1794		refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
1795		datacnt = hdr->b_l1hdr.b_datacnt;
1796	} else {
1797		old_state = arc_l2c_only;
1798		refcnt = 0;
1799		datacnt = 0;
1800	}
1801
1802	ASSERT(MUTEX_HELD(hash_lock));
1803	ASSERT3P(new_state, !=, old_state);
1804	ASSERT(refcnt == 0 || datacnt > 0);
1805	ASSERT(!GHOST_STATE(new_state) || datacnt == 0);
1806	ASSERT(old_state != arc_anon || datacnt <= 1);
1807
1808	from_delta = to_delta = datacnt * hdr->b_size;
1809
1810	/*
1811	 * If this buffer is evictable, transfer it from the
1812	 * old state list to the new state list.
1813	 */
1814	if (refcnt == 0) {
1815		if (old_state != arc_anon && old_state != arc_l2c_only) {
1816			int use_mutex;
1817			uint64_t *size = &old_state->arcs_lsize[buftype];
1818
1819			get_buf_info(hdr, old_state, &list, &lock);
1820			use_mutex = !MUTEX_HELD(lock);
1821			if (use_mutex)
1822				mutex_enter(lock);
1823
1824			ASSERT(HDR_HAS_L1HDR(hdr));
1825			ASSERT(list_link_active(&hdr->b_l1hdr.b_arc_node));
1826			list_remove(list, hdr);
1827
1828			/*
1829			 * If prefetching out of the ghost cache,
1830			 * we will have a non-zero datacnt.
1831			 */
1832			if (GHOST_STATE(old_state) && datacnt == 0) {
1833				/* ghost elements have a ghost size */
1834				ASSERT(hdr->b_l1hdr.b_buf == NULL);
1835				from_delta = hdr->b_size;
1836			}
1837			ASSERT3U(*size, >=, from_delta);
1838			atomic_add_64(size, -from_delta);
1839
1840			if (use_mutex)
1841				mutex_exit(lock);
1842		}
1843		if (new_state != arc_anon && new_state != arc_l2c_only) {
1844			int use_mutex;
1845			uint64_t *size = &new_state->arcs_lsize[buftype];
1846
1847			/*
1848			 * An L1 header always exists here, since if we're
1849			 * moving to some L1-cached state (i.e. not l2c_only or
1850			 * anonymous), we realloc the header to add an L1hdr
1851			 * beforehand.
1852			 */
1853			ASSERT(HDR_HAS_L1HDR(hdr));
1854			get_buf_info(hdr, new_state, &list, &lock);
1855			use_mutex = !MUTEX_HELD(lock);
1856			if (use_mutex)
1857				mutex_enter(lock);
1858
1859			list_insert_head(list, hdr);
1860
1861			/* ghost elements have a ghost size */
1862			if (GHOST_STATE(new_state)) {
1863				ASSERT(datacnt == 0);
1864				ASSERT(hdr->b_l1hdr.b_buf == NULL);
1865				to_delta = hdr->b_size;
1866			}
1867			atomic_add_64(size, to_delta);
1868
1869			if (use_mutex)
1870				mutex_exit(lock);
1871		}
1872	}
1873
1874	ASSERT(!BUF_EMPTY(hdr));
1875	if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
1876		buf_hash_remove(hdr);
1877
1878	/* adjust state sizes (ignore arc_l2c_only) */
1879	if (to_delta && new_state != arc_l2c_only)
1880		atomic_add_64(&new_state->arcs_size, to_delta);
1881	if (from_delta && old_state != arc_l2c_only) {
1882		ASSERT3U(old_state->arcs_size, >=, from_delta);
1883		atomic_add_64(&old_state->arcs_size, -from_delta);
1884	}
1885	if (HDR_HAS_L1HDR(hdr))
1886		hdr->b_l1hdr.b_state = new_state;
1887
1888	/*
1889	 * L2 headers should never be on the L2 state list since they don't
1890	 * have L1 headers allocated.
1891	 */
1892#ifdef illumos
1893	ASSERT(list_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
1894	    list_is_empty(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
1895#endif
1896}
1897
1898void
1899arc_space_consume(uint64_t space, arc_space_type_t type)
1900{
1901	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1902
1903	switch (type) {
1904	case ARC_SPACE_DATA:
1905		ARCSTAT_INCR(arcstat_data_size, space);
1906		break;
1907	case ARC_SPACE_META:
1908		ARCSTAT_INCR(arcstat_metadata_size, space);
1909		break;
1910	case ARC_SPACE_OTHER:
1911		ARCSTAT_INCR(arcstat_other_size, space);
1912		break;
1913	case ARC_SPACE_HDRS:
1914		ARCSTAT_INCR(arcstat_hdr_size, space);
1915		break;
1916	case ARC_SPACE_L2HDRS:
1917		ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1918		break;
1919	}
1920
1921	if (type != ARC_SPACE_DATA)
1922		ARCSTAT_INCR(arcstat_meta_used, space);
1923
1924	atomic_add_64(&arc_size, space);
1925}
1926
1927void
1928arc_space_return(uint64_t space, arc_space_type_t type)
1929{
1930	ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1931
1932	switch (type) {
1933	case ARC_SPACE_DATA:
1934		ARCSTAT_INCR(arcstat_data_size, -space);
1935		break;
1936	case ARC_SPACE_META:
1937		ARCSTAT_INCR(arcstat_metadata_size, -space);
1938		break;
1939	case ARC_SPACE_OTHER:
1940		ARCSTAT_INCR(arcstat_other_size, -space);
1941		break;
1942	case ARC_SPACE_HDRS:
1943		ARCSTAT_INCR(arcstat_hdr_size, -space);
1944		break;
1945	case ARC_SPACE_L2HDRS:
1946		ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1947		break;
1948	}
1949
1950	if (type != ARC_SPACE_DATA) {
1951		ASSERT(arc_meta_used >= space);
1952		if (arc_meta_max < arc_meta_used)
1953			arc_meta_max = arc_meta_used;
1954		ARCSTAT_INCR(arcstat_meta_used, -space);
1955	}
1956
1957	ASSERT(arc_size >= space);
1958	atomic_add_64(&arc_size, -space);
1959}
1960
1961arc_buf_t *
1962arc_buf_alloc(spa_t *spa, int32_t size, void *tag, arc_buf_contents_t type)
1963{
1964	arc_buf_hdr_t *hdr;
1965	arc_buf_t *buf;
1966
1967	ASSERT3U(size, >, 0);
1968	hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
1969	ASSERT(BUF_EMPTY(hdr));
1970	ASSERT3P(hdr->b_freeze_cksum, ==, NULL);
1971	hdr->b_size = size;
1972	hdr->b_spa = spa_load_guid(spa);
1973
1974	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1975	buf->b_hdr = hdr;
1976	buf->b_data = NULL;
1977	buf->b_efunc = NULL;
1978	buf->b_private = NULL;
1979	buf->b_next = NULL;
1980
1981	hdr->b_flags = arc_bufc_to_flags(type);
1982	hdr->b_flags |= ARC_FLAG_HAS_L1HDR;
1983
1984	hdr->b_l1hdr.b_buf = buf;
1985	hdr->b_l1hdr.b_state = arc_anon;
1986	hdr->b_l1hdr.b_arc_access = 0;
1987	hdr->b_l1hdr.b_datacnt = 1;
1988
1989	arc_get_data_buf(buf);
1990	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
1991	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
1992
1993	return (buf);
1994}
1995
1996static char *arc_onloan_tag = "onloan";
1997
1998/*
1999 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
2000 * flight data by arc_tempreserve_space() until they are "returned". Loaned
2001 * buffers must be returned to the arc before they can be used by the DMU or
2002 * freed.
2003 */
2004arc_buf_t *
2005arc_loan_buf(spa_t *spa, int size)
2006{
2007	arc_buf_t *buf;
2008
2009	buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
2010
2011	atomic_add_64(&arc_loaned_bytes, size);
2012	return (buf);
2013}
2014
2015/*
2016 * Return a loaned arc buffer to the arc.
2017 */
2018void
2019arc_return_buf(arc_buf_t *buf, void *tag)
2020{
2021	arc_buf_hdr_t *hdr = buf->b_hdr;
2022
2023	ASSERT(buf->b_data != NULL);
2024	ASSERT(HDR_HAS_L1HDR(hdr));
2025	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
2026	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2027
2028	atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
2029}
2030
2031/* Detach an arc_buf from a dbuf (tag) */
2032void
2033arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
2034{
2035	arc_buf_hdr_t *hdr = buf->b_hdr;
2036
2037	ASSERT(buf->b_data != NULL);
2038	ASSERT(HDR_HAS_L1HDR(hdr));
2039	(void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
2040	(void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
2041	buf->b_efunc = NULL;
2042	buf->b_private = NULL;
2043
2044	atomic_add_64(&arc_loaned_bytes, hdr->b_size);
2045}
2046
2047static arc_buf_t *
2048arc_buf_clone(arc_buf_t *from)
2049{
2050	arc_buf_t *buf;
2051	arc_buf_hdr_t *hdr = from->b_hdr;
2052	uint64_t size = hdr->b_size;
2053
2054	ASSERT(HDR_HAS_L1HDR(hdr));
2055	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2056
2057	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2058	buf->b_hdr = hdr;
2059	buf->b_data = NULL;
2060	buf->b_efunc = NULL;
2061	buf->b_private = NULL;
2062	buf->b_next = hdr->b_l1hdr.b_buf;
2063	hdr->b_l1hdr.b_buf = buf;
2064	arc_get_data_buf(buf);
2065	bcopy(from->b_data, buf->b_data, size);
2066
2067	/*
2068	 * This buffer already exists in the arc so create a duplicate
2069	 * copy for the caller.  If the buffer is associated with user data
2070	 * then track the size and number of duplicates.  These stats will be
2071	 * updated as duplicate buffers are created and destroyed.
2072	 */
2073	if (HDR_ISTYPE_DATA(hdr)) {
2074		ARCSTAT_BUMP(arcstat_duplicate_buffers);
2075		ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
2076	}
2077	hdr->b_l1hdr.b_datacnt += 1;
2078	return (buf);
2079}
2080
2081void
2082arc_buf_add_ref(arc_buf_t *buf, void* tag)
2083{
2084	arc_buf_hdr_t *hdr;
2085	kmutex_t *hash_lock;
2086
2087	/*
2088	 * Check to see if this buffer is evicted.  Callers
2089	 * must verify b_data != NULL to know if the add_ref
2090	 * was successful.
2091	 */
2092	mutex_enter(&buf->b_evict_lock);
2093	if (buf->b_data == NULL) {
2094		mutex_exit(&buf->b_evict_lock);
2095		return;
2096	}
2097	hash_lock = HDR_LOCK(buf->b_hdr);
2098	mutex_enter(hash_lock);
2099	hdr = buf->b_hdr;
2100	ASSERT(HDR_HAS_L1HDR(hdr));
2101	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2102	mutex_exit(&buf->b_evict_lock);
2103
2104	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
2105	    hdr->b_l1hdr.b_state == arc_mfu);
2106
2107	add_reference(hdr, hash_lock, tag);
2108	DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
2109	arc_access(hdr, hash_lock);
2110	mutex_exit(hash_lock);
2111	ARCSTAT_BUMP(arcstat_hits);
2112	ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
2113	    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
2114	    data, metadata, hits);
2115}
2116
2117static void
2118arc_buf_free_on_write(void *data, size_t size,
2119    void (*free_func)(void *, size_t))
2120{
2121	l2arc_data_free_t *df;
2122
2123	df = kmem_alloc(sizeof (l2arc_data_free_t), KM_SLEEP);
2124	df->l2df_data = data;
2125	df->l2df_size = size;
2126	df->l2df_func = free_func;
2127	mutex_enter(&l2arc_free_on_write_mtx);
2128	list_insert_head(l2arc_free_on_write, df);
2129	mutex_exit(&l2arc_free_on_write_mtx);
2130}
2131
2132/*
2133 * Free the arc data buffer.  If it is an l2arc write in progress,
2134 * the buffer is placed on l2arc_free_on_write to be freed later.
2135 */
2136static void
2137arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
2138{
2139	arc_buf_hdr_t *hdr = buf->b_hdr;
2140
2141	if (HDR_L2_WRITING(hdr)) {
2142		arc_buf_free_on_write(buf->b_data, hdr->b_size, free_func);
2143		ARCSTAT_BUMP(arcstat_l2_free_on_write);
2144	} else {
2145		free_func(buf->b_data, hdr->b_size);
2146	}
2147}
2148
2149/*
2150 * Free up buf->b_data and if 'remove' is set, then pull the
2151 * arc_buf_t off of the the arc_buf_hdr_t's list and free it.
2152 */
2153static void
2154arc_buf_l2_cdata_free(arc_buf_hdr_t *hdr)
2155{
2156	ASSERT(HDR_HAS_L2HDR(hdr));
2157	ASSERT(MUTEX_HELD(&hdr->b_l2hdr.b_dev->l2ad_mtx));
2158
2159	/*
2160	 * The b_tmp_cdata field is linked off of the b_l1hdr, so if
2161	 * that doesn't exist, the header is in the arc_l2c_only state,
2162	 * and there isn't anything to free (it's already been freed).
2163	 */
2164	if (!HDR_HAS_L1HDR(hdr))
2165		return;
2166
2167	if (hdr->b_l1hdr.b_tmp_cdata == NULL)
2168		return;
2169
2170	ASSERT(HDR_L2_WRITING(hdr));
2171	arc_buf_free_on_write(hdr->b_l1hdr.b_tmp_cdata, hdr->b_size,
2172	    zio_data_buf_free);
2173
2174	ARCSTAT_BUMP(arcstat_l2_cdata_free_on_write);
2175	hdr->b_l1hdr.b_tmp_cdata = NULL;
2176}
2177
2178static void
2179arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t remove)
2180{
2181	arc_buf_t **bufp;
2182
2183	/* free up data associated with the buf */
2184	if (buf->b_data != NULL) {
2185		arc_state_t *state = buf->b_hdr->b_l1hdr.b_state;
2186		uint64_t size = buf->b_hdr->b_size;
2187		arc_buf_contents_t type = arc_buf_type(buf->b_hdr);
2188
2189		arc_cksum_verify(buf);
2190#ifdef illumos
2191		arc_buf_unwatch(buf);
2192#endif
2193
2194		if (!recycle) {
2195			if (type == ARC_BUFC_METADATA) {
2196				arc_buf_data_free(buf, zio_buf_free);
2197				arc_space_return(size, ARC_SPACE_META);
2198			} else {
2199				ASSERT(type == ARC_BUFC_DATA);
2200				arc_buf_data_free(buf, zio_data_buf_free);
2201				arc_space_return(size, ARC_SPACE_DATA);
2202			}
2203		}
2204		if (list_link_active(&buf->b_hdr->b_l1hdr.b_arc_node)) {
2205			uint64_t *cnt = &state->arcs_lsize[type];
2206
2207			ASSERT(refcount_is_zero(
2208			    &buf->b_hdr->b_l1hdr.b_refcnt));
2209			ASSERT(state != arc_anon && state != arc_l2c_only);
2210
2211			ASSERT3U(*cnt, >=, size);
2212			atomic_add_64(cnt, -size);
2213		}
2214		ASSERT3U(state->arcs_size, >=, size);
2215		atomic_add_64(&state->arcs_size, -size);
2216		buf->b_data = NULL;
2217
2218		/*
2219		 * If we're destroying a duplicate buffer make sure
2220		 * that the appropriate statistics are updated.
2221		 */
2222		if (buf->b_hdr->b_l1hdr.b_datacnt > 1 &&
2223		    HDR_ISTYPE_DATA(buf->b_hdr)) {
2224			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
2225			ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
2226		}
2227		ASSERT(buf->b_hdr->b_l1hdr.b_datacnt > 0);
2228		buf->b_hdr->b_l1hdr.b_datacnt -= 1;
2229	}
2230
2231	/* only remove the buf if requested */
2232	if (!remove)
2233		return;
2234
2235	/* remove the buf from the hdr list */
2236	for (bufp = &buf->b_hdr->b_l1hdr.b_buf; *bufp != buf;
2237	    bufp = &(*bufp)->b_next)
2238		continue;
2239	*bufp = buf->b_next;
2240	buf->b_next = NULL;
2241
2242	ASSERT(buf->b_efunc == NULL);
2243
2244	/* clean up the buf */
2245	buf->b_hdr = NULL;
2246	kmem_cache_free(buf_cache, buf);
2247}
2248
2249static void
2250arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
2251{
2252	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
2253	l2arc_dev_t *dev = l2hdr->b_dev;
2254
2255	ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
2256	ASSERT(HDR_HAS_L2HDR(hdr));
2257
2258	list_remove(&dev->l2ad_buflist, hdr);
2259
2260	/*
2261	 * We don't want to leak the b_tmp_cdata buffer that was
2262	 * allocated in l2arc_write_buffers()
2263	 */
2264	arc_buf_l2_cdata_free(hdr);
2265
2266	/*
2267	 * If the l2hdr's b_daddr is equal to L2ARC_ADDR_UNSET, then
2268	 * this header is being processed by l2arc_write_buffers() (i.e.
2269	 * it's in the first stage of l2arc_write_buffers()).
2270	 * Re-affirming that truth here, just to serve as a reminder. If
2271	 * b_daddr does not equal L2ARC_ADDR_UNSET, then the header may or
2272	 * may not have its HDR_L2_WRITING flag set. (the write may have
2273	 * completed, in which case HDR_L2_WRITING will be false and the
2274	 * b_daddr field will point to the address of the buffer on disk).
2275	 */
2276	IMPLY(l2hdr->b_daddr == L2ARC_ADDR_UNSET, HDR_L2_WRITING(hdr));
2277
2278	/*
2279	 * If b_daddr is equal to L2ARC_ADDR_UNSET, we're racing with
2280	 * l2arc_write_buffers(). Since we've just removed this header
2281	 * from the l2arc buffer list, this header will never reach the
2282	 * second stage of l2arc_write_buffers(), which increments the
2283	 * accounting stats for this header. Thus, we must be careful
2284	 * not to decrement them for this header either.
2285	 */
2286	if (l2hdr->b_daddr != L2ARC_ADDR_UNSET) {
2287		ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
2288		ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
2289
2290		vdev_space_update(dev->l2ad_vdev,
2291		    -l2hdr->b_asize, 0, 0);
2292
2293		(void) refcount_remove_many(&dev->l2ad_alloc,
2294		    l2hdr->b_asize, hdr);
2295	}
2296
2297	hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
2298}
2299
2300static void
2301arc_hdr_destroy(arc_buf_hdr_t *hdr)
2302{
2303	if (HDR_HAS_L1HDR(hdr)) {
2304		ASSERT(hdr->b_l1hdr.b_buf == NULL ||
2305		    hdr->b_l1hdr.b_datacnt > 0);
2306		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2307		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2308	}
2309	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2310	ASSERT(!HDR_IN_HASH_TABLE(hdr));
2311
2312	if (HDR_HAS_L2HDR(hdr)) {
2313		l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
2314		boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
2315
2316		if (!buflist_held)
2317			mutex_enter(&dev->l2ad_mtx);
2318
2319		/*
2320		 * Even though we checked this conditional above, we
2321		 * need to check this again now that we have the
2322		 * l2ad_mtx. This is because we could be racing with
2323		 * another thread calling l2arc_evict() which might have
2324		 * destroyed this header's L2 portion as we were waiting
2325		 * to acquire the l2ad_mtx. If that happens, we don't
2326		 * want to re-destroy the header's L2 portion.
2327		 */
2328		if (HDR_HAS_L2HDR(hdr)) {
2329			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
2330				trim_map_free(dev->l2ad_vdev,
2331				    hdr->b_l2hdr.b_daddr,
2332				    hdr->b_l2hdr.b_asize, 0);
2333			arc_hdr_l2hdr_destroy(hdr);
2334		}
2335
2336		if (!buflist_held)
2337			mutex_exit(&dev->l2ad_mtx);
2338	}
2339
2340	if (!BUF_EMPTY(hdr))
2341		buf_discard_identity(hdr);
2342	if (hdr->b_freeze_cksum != NULL) {
2343		kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
2344		hdr->b_freeze_cksum = NULL;
2345	}
2346
2347	if (HDR_HAS_L1HDR(hdr)) {
2348		while (hdr->b_l1hdr.b_buf) {
2349			arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2350
2351			if (buf->b_efunc != NULL) {
2352				mutex_enter(&arc_eviction_mtx);
2353				mutex_enter(&buf->b_evict_lock);
2354				ASSERT(buf->b_hdr != NULL);
2355				arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE,
2356				    FALSE);
2357				hdr->b_l1hdr.b_buf = buf->b_next;
2358				buf->b_hdr = &arc_eviction_hdr;
2359				buf->b_next = arc_eviction_list;
2360				arc_eviction_list = buf;
2361				mutex_exit(&buf->b_evict_lock);
2362				mutex_exit(&arc_eviction_mtx);
2363			} else {
2364				arc_buf_destroy(hdr->b_l1hdr.b_buf, FALSE,
2365				    TRUE);
2366			}
2367		}
2368#ifdef ZFS_DEBUG
2369		if (hdr->b_l1hdr.b_thawed != NULL) {
2370			kmem_free(hdr->b_l1hdr.b_thawed, 1);
2371			hdr->b_l1hdr.b_thawed = NULL;
2372		}
2373#endif
2374	}
2375
2376	ASSERT3P(hdr->b_hash_next, ==, NULL);
2377	if (HDR_HAS_L1HDR(hdr)) {
2378		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
2379		ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
2380		kmem_cache_free(hdr_full_cache, hdr);
2381	} else {
2382		kmem_cache_free(hdr_l2only_cache, hdr);
2383	}
2384}
2385
2386void
2387arc_buf_free(arc_buf_t *buf, void *tag)
2388{
2389	arc_buf_hdr_t *hdr = buf->b_hdr;
2390	int hashed = hdr->b_l1hdr.b_state != arc_anon;
2391
2392	ASSERT(buf->b_efunc == NULL);
2393	ASSERT(buf->b_data != NULL);
2394
2395	if (hashed) {
2396		kmutex_t *hash_lock = HDR_LOCK(hdr);
2397
2398		mutex_enter(hash_lock);
2399		hdr = buf->b_hdr;
2400		ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2401
2402		(void) remove_reference(hdr, hash_lock, tag);
2403		if (hdr->b_l1hdr.b_datacnt > 1) {
2404			arc_buf_destroy(buf, FALSE, TRUE);
2405		} else {
2406			ASSERT(buf == hdr->b_l1hdr.b_buf);
2407			ASSERT(buf->b_efunc == NULL);
2408			hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2409		}
2410		mutex_exit(hash_lock);
2411	} else if (HDR_IO_IN_PROGRESS(hdr)) {
2412		int destroy_hdr;
2413		/*
2414		 * We are in the middle of an async write.  Don't destroy
2415		 * this buffer unless the write completes before we finish
2416		 * decrementing the reference count.
2417		 */
2418		mutex_enter(&arc_eviction_mtx);
2419		(void) remove_reference(hdr, NULL, tag);
2420		ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2421		destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
2422		mutex_exit(&arc_eviction_mtx);
2423		if (destroy_hdr)
2424			arc_hdr_destroy(hdr);
2425	} else {
2426		if (remove_reference(hdr, NULL, tag) > 0)
2427			arc_buf_destroy(buf, FALSE, TRUE);
2428		else
2429			arc_hdr_destroy(hdr);
2430	}
2431}
2432
2433boolean_t
2434arc_buf_remove_ref(arc_buf_t *buf, void* tag)
2435{
2436	arc_buf_hdr_t *hdr = buf->b_hdr;
2437	kmutex_t *hash_lock = HDR_LOCK(hdr);
2438	boolean_t no_callback = (buf->b_efunc == NULL);
2439
2440	if (hdr->b_l1hdr.b_state == arc_anon) {
2441		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
2442		arc_buf_free(buf, tag);
2443		return (no_callback);
2444	}
2445
2446	mutex_enter(hash_lock);
2447	hdr = buf->b_hdr;
2448	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
2449	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
2450	ASSERT(hdr->b_l1hdr.b_state != arc_anon);
2451	ASSERT(buf->b_data != NULL);
2452
2453	(void) remove_reference(hdr, hash_lock, tag);
2454	if (hdr->b_l1hdr.b_datacnt > 1) {
2455		if (no_callback)
2456			arc_buf_destroy(buf, FALSE, TRUE);
2457	} else if (no_callback) {
2458		ASSERT(hdr->b_l1hdr.b_buf == buf && buf->b_next == NULL);
2459		ASSERT(buf->b_efunc == NULL);
2460		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
2461	}
2462	ASSERT(no_callback || hdr->b_l1hdr.b_datacnt > 1 ||
2463	    refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2464	mutex_exit(hash_lock);
2465	return (no_callback);
2466}
2467
2468int32_t
2469arc_buf_size(arc_buf_t *buf)
2470{
2471	return (buf->b_hdr->b_size);
2472}
2473
2474/*
2475 * Called from the DMU to determine if the current buffer should be
2476 * evicted. In order to ensure proper locking, the eviction must be initiated
2477 * from the DMU. Return true if the buffer is associated with user data and
2478 * duplicate buffers still exist.
2479 */
2480boolean_t
2481arc_buf_eviction_needed(arc_buf_t *buf)
2482{
2483	arc_buf_hdr_t *hdr;
2484	boolean_t evict_needed = B_FALSE;
2485
2486	if (zfs_disable_dup_eviction)
2487		return (B_FALSE);
2488
2489	mutex_enter(&buf->b_evict_lock);
2490	hdr = buf->b_hdr;
2491	if (hdr == NULL) {
2492		/*
2493		 * We are in arc_do_user_evicts(); let that function
2494		 * perform the eviction.
2495		 */
2496		ASSERT(buf->b_data == NULL);
2497		mutex_exit(&buf->b_evict_lock);
2498		return (B_FALSE);
2499	} else if (buf->b_data == NULL) {
2500		/*
2501		 * We have already been added to the arc eviction list;
2502		 * recommend eviction.
2503		 */
2504		ASSERT3P(hdr, ==, &arc_eviction_hdr);
2505		mutex_exit(&buf->b_evict_lock);
2506		return (B_TRUE);
2507	}
2508
2509	if (hdr->b_l1hdr.b_datacnt > 1 && HDR_ISTYPE_DATA(hdr))
2510		evict_needed = B_TRUE;
2511
2512	mutex_exit(&buf->b_evict_lock);
2513	return (evict_needed);
2514}
2515
2516/*
2517 * Evict buffers from list until we've removed the specified number of
2518 * bytes.  Move the removed buffers to the appropriate evict state.
2519 * If the recycle flag is set, then attempt to "recycle" a buffer:
2520 * - look for a buffer to evict that is `bytes' long.
2521 * - return the data block from this buffer rather than freeing it.
2522 * This flag is used by callers that are trying to make space for a
2523 * new buffer in a full arc cache.
2524 *
2525 * This function makes a "best effort".  It skips over any buffers
2526 * it can't get a hash_lock on, and so may not catch all candidates.
2527 * It may also return without evicting as much space as requested.
2528 */
2529static void *
2530arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
2531    arc_buf_contents_t type)
2532{
2533	arc_state_t *evicted_state;
2534	uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
2535	int64_t bytes_remaining;
2536	arc_buf_hdr_t *hdr, *hdr_prev = NULL;
2537	list_t *evicted_list, *list, *evicted_list_start, *list_start;
2538	kmutex_t *lock, *evicted_lock;
2539	kmutex_t *hash_lock;
2540	boolean_t have_lock;
2541	void *stolen = NULL;
2542	arc_buf_hdr_t marker = { 0 };
2543	int count = 0;
2544	static int evict_metadata_offset, evict_data_offset;
2545	int i, idx, offset, list_count, lists;
2546
2547	ASSERT(state == arc_mru || state == arc_mfu);
2548
2549	evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
2550
2551	/*
2552	 * Decide which "type" (data vs metadata) to recycle from.
2553	 *
2554	 * If we are over the metadata limit, recycle from metadata.
2555	 * If we are under the metadata minimum, recycle from data.
2556	 * Otherwise, recycle from whichever type has the oldest (least
2557	 * recently accessed) header.  This is not yet implemented.
2558	 */
2559	if (recycle) {
2560		arc_buf_contents_t realtype;
2561		if (state->arcs_lsize[ARC_BUFC_DATA] == 0) {
2562			realtype = ARC_BUFC_METADATA;
2563		} else if (state->arcs_lsize[ARC_BUFC_METADATA] == 0) {
2564			realtype = ARC_BUFC_DATA;
2565		} else if (arc_meta_used >= arc_meta_limit) {
2566			realtype = ARC_BUFC_METADATA;
2567		} else if (arc_meta_used <= arc_meta_min) {
2568			realtype = ARC_BUFC_DATA;
2569#ifdef illumos
2570		} else if (HDR_HAS_L1HDR(data_hdr) &&
2571		    HDR_HAS_L1HDR(metadata_hdr) &&
2572		    data_hdr->b_l1hdr.b_arc_access <
2573		    metadata_hdr->b_l1hdr.b_arc_access) {
2574			realtype = ARC_BUFC_DATA;
2575		} else {
2576			realtype = ARC_BUFC_METADATA;
2577#else
2578		} else {
2579			/* TODO */
2580			realtype = type;
2581#endif
2582		}
2583		if (realtype != type) {
2584			/*
2585			 * If we want to evict from a different list,
2586			 * we can not recycle, because DATA vs METADATA
2587			 * buffers are segregated into different kmem
2588			 * caches (and vmem arenas).
2589			 */
2590			type = realtype;
2591			recycle = B_FALSE;
2592		}
2593	}
2594
2595	if (type == ARC_BUFC_METADATA) {
2596		offset = 0;
2597		list_count = ARC_BUFC_NUMMETADATALISTS;
2598		list_start = &state->arcs_lists[0];
2599		evicted_list_start = &evicted_state->arcs_lists[0];
2600		idx = evict_metadata_offset;
2601	} else {
2602		offset = ARC_BUFC_NUMMETADATALISTS;
2603		list_start = &state->arcs_lists[offset];
2604		evicted_list_start = &evicted_state->arcs_lists[offset];
2605		list_count = ARC_BUFC_NUMDATALISTS;
2606		idx = evict_data_offset;
2607	}
2608	bytes_remaining = evicted_state->arcs_lsize[type];
2609	lists = 0;
2610
2611evict_start:
2612	list = &list_start[idx];
2613	evicted_list = &evicted_list_start[idx];
2614	lock = ARCS_LOCK(state, (offset + idx));
2615	evicted_lock = ARCS_LOCK(evicted_state, (offset + idx));
2616
2617	/*
2618	 * The ghost list lock must be acquired first in order to prevent
2619	 * a 3 party deadlock:
2620	 *
2621	 *  - arc_evict_ghost acquires arc_*_ghost->arcs_mtx, followed by
2622	 *    l2ad_mtx in arc_hdr_realloc
2623	 *  - l2arc_write_buffers acquires l2ad_mtx, followed by arc_*->arcs_mtx
2624	 *  - arc_evict acquires arc_*_ghost->arcs_mtx, followed by
2625	 *    arc_*_ghost->arcs_mtx and forms a deadlock cycle.
2626	 *
2627	 * This situation is avoided by acquiring the ghost list lock first.
2628	 */
2629	mutex_enter(evicted_lock);
2630	mutex_enter(lock);
2631
2632	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2633		hdr_prev = list_prev(list, hdr);
2634		if (HDR_HAS_L1HDR(hdr)) {
2635			bytes_remaining -=
2636			    (hdr->b_size * hdr->b_l1hdr.b_datacnt);
2637		}
2638		/* prefetch buffers have a minimum lifespan */
2639		if (HDR_IO_IN_PROGRESS(hdr) ||
2640		    (spa && hdr->b_spa != spa) ||
2641		    ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
2642		    ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access <
2643		    arc_min_prefetch_lifespan)) {
2644			skipped++;
2645			continue;
2646		}
2647		/* "lookahead" for better eviction candidate */
2648		if (recycle && hdr->b_size != bytes &&
2649		    hdr_prev && hdr_prev->b_size == bytes)
2650			continue;
2651
2652		/* ignore markers */
2653		if (hdr->b_spa == 0)
2654			continue;
2655
2656		/*
2657		 * It may take a long time to evict all the bufs requested.
2658		 * To avoid blocking all arc activity, periodically drop
2659		 * the arcs_mtx and give other threads a chance to run
2660		 * before reacquiring the lock.
2661		 *
2662		 * If we are looking for a buffer to recycle, we are in
2663		 * the hot code path, so don't sleep.
2664		 */
2665		if (!recycle && count++ > arc_evict_iterations) {
2666			list_insert_after(list, hdr, &marker);
2667			mutex_exit(lock);
2668			mutex_exit(evicted_lock);
2669			kpreempt(KPREEMPT_SYNC);
2670			mutex_enter(evicted_lock);
2671			mutex_enter(lock);
2672			hdr_prev = list_prev(list, &marker);
2673			list_remove(list, &marker);
2674			count = 0;
2675			continue;
2676		}
2677
2678		hash_lock = HDR_LOCK(hdr);
2679		have_lock = MUTEX_HELD(hash_lock);
2680		if (have_lock || mutex_tryenter(hash_lock)) {
2681			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
2682			ASSERT3U(hdr->b_l1hdr.b_datacnt, >, 0);
2683			while (hdr->b_l1hdr.b_buf) {
2684				arc_buf_t *buf = hdr->b_l1hdr.b_buf;
2685				if (!mutex_tryenter(&buf->b_evict_lock)) {
2686					missed += 1;
2687					break;
2688				}
2689				if (buf->b_data != NULL) {
2690					bytes_evicted += hdr->b_size;
2691					if (recycle &&
2692					    arc_buf_type(hdr) == type &&
2693					    hdr->b_size == bytes &&
2694					    !HDR_L2_WRITING(hdr)) {
2695						stolen = buf->b_data;
2696						recycle = FALSE;
2697					}
2698				}
2699				if (buf->b_efunc != NULL) {
2700					mutex_enter(&arc_eviction_mtx);
2701					arc_buf_destroy(buf,
2702					    buf->b_data == stolen, FALSE);
2703					hdr->b_l1hdr.b_buf = buf->b_next;
2704					buf->b_hdr = &arc_eviction_hdr;
2705					buf->b_next = arc_eviction_list;
2706					arc_eviction_list = buf;
2707					mutex_exit(&arc_eviction_mtx);
2708					mutex_exit(&buf->b_evict_lock);
2709				} else {
2710					mutex_exit(&buf->b_evict_lock);
2711					arc_buf_destroy(buf,
2712					    buf->b_data == stolen, TRUE);
2713				}
2714			}
2715
2716			if (HDR_HAS_L2HDR(hdr)) {
2717				ARCSTAT_INCR(arcstat_evict_l2_cached,
2718				    hdr->b_size);
2719			} else {
2720				if (l2arc_write_eligible(hdr->b_spa, hdr)) {
2721					ARCSTAT_INCR(arcstat_evict_l2_eligible,
2722					    hdr->b_size);
2723				} else {
2724					ARCSTAT_INCR(
2725					    arcstat_evict_l2_ineligible,
2726					    hdr->b_size);
2727				}
2728			}
2729
2730			if (hdr->b_l1hdr.b_datacnt == 0) {
2731				arc_change_state(evicted_state, hdr, hash_lock);
2732				ASSERT(HDR_IN_HASH_TABLE(hdr));
2733				hdr->b_flags |= ARC_FLAG_IN_HASH_TABLE;
2734				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
2735				DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
2736			}
2737			if (!have_lock)
2738				mutex_exit(hash_lock);
2739			if (bytes >= 0 && bytes_evicted >= bytes)
2740				break;
2741			if (bytes_remaining > 0) {
2742				mutex_exit(evicted_lock);
2743				mutex_exit(lock);
2744				idx  = ((idx + 1) & (list_count - 1));
2745				lists++;
2746				goto evict_start;
2747			}
2748		} else {
2749			missed += 1;
2750		}
2751	}
2752
2753	mutex_exit(lock);
2754	mutex_exit(evicted_lock);
2755
2756	idx  = ((idx + 1) & (list_count - 1));
2757	lists++;
2758
2759	if (bytes_evicted < bytes) {
2760		if (lists < list_count)
2761			goto evict_start;
2762		else
2763			dprintf("only evicted %lld bytes from %x",
2764			    (longlong_t)bytes_evicted, state);
2765	}
2766	if (type == ARC_BUFC_METADATA)
2767		evict_metadata_offset = idx;
2768	else
2769		evict_data_offset = idx;
2770
2771	if (skipped)
2772		ARCSTAT_INCR(arcstat_evict_skip, skipped);
2773
2774	if (missed)
2775		ARCSTAT_INCR(arcstat_mutex_miss, missed);
2776
2777	/*
2778	 * Note: we have just evicted some data into the ghost state,
2779	 * potentially putting the ghost size over the desired size.  Rather
2780	 * that evicting from the ghost list in this hot code path, leave
2781	 * this chore to the arc_reclaim_thread().
2782	 */
2783
2784	if (stolen)
2785		ARCSTAT_BUMP(arcstat_stolen);
2786	return (stolen);
2787}
2788
2789/*
2790 * Remove buffers from list until we've removed the specified number of
2791 * bytes.  Destroy the buffers that are removed.
2792 */
2793static void
2794arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes)
2795{
2796	arc_buf_hdr_t *hdr, *hdr_prev;
2797	arc_buf_hdr_t marker = { 0 };
2798	list_t *list, *list_start;
2799	kmutex_t *hash_lock, *lock;
2800	uint64_t bytes_deleted = 0;
2801	uint64_t bufs_skipped = 0;
2802	int count = 0;
2803	static int evict_offset;
2804	int list_count, idx = evict_offset;
2805	int offset, lists = 0;
2806
2807	ASSERT(GHOST_STATE(state));
2808
2809	/*
2810	 * data lists come after metadata lists
2811	 */
2812	list_start = &state->arcs_lists[ARC_BUFC_NUMMETADATALISTS];
2813	list_count = ARC_BUFC_NUMDATALISTS;
2814	offset = ARC_BUFC_NUMMETADATALISTS;
2815
2816evict_start:
2817	list = &list_start[idx];
2818	lock = ARCS_LOCK(state, idx + offset);
2819
2820	mutex_enter(lock);
2821	for (hdr = list_tail(list); hdr; hdr = hdr_prev) {
2822		hdr_prev = list_prev(list, hdr);
2823		if (arc_buf_type(hdr) >= ARC_BUFC_NUMTYPES)
2824			panic("invalid hdr=%p", (void *)hdr);
2825		if (spa && hdr->b_spa != spa)
2826			continue;
2827
2828		/* ignore markers */
2829		if (hdr->b_spa == 0)
2830			continue;
2831
2832		hash_lock = HDR_LOCK(hdr);
2833		/* caller may be trying to modify this buffer, skip it */
2834		if (MUTEX_HELD(hash_lock))
2835			continue;
2836
2837		/*
2838		 * It may take a long time to evict all the bufs requested.
2839		 * To avoid blocking all arc activity, periodically drop
2840		 * the arcs_mtx and give other threads a chance to run
2841		 * before reacquiring the lock.
2842		 */
2843		if (count++ > arc_evict_iterations) {
2844			list_insert_after(list, hdr, &marker);
2845			mutex_exit(lock);
2846			kpreempt(KPREEMPT_SYNC);
2847			mutex_enter(lock);
2848			hdr_prev = list_prev(list, &marker);
2849			list_remove(list, &marker);
2850			count = 0;
2851			continue;
2852		}
2853		if (mutex_tryenter(hash_lock)) {
2854			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2855			ASSERT(!HDR_HAS_L1HDR(hdr) ||
2856			    hdr->b_l1hdr.b_buf == NULL);
2857			ARCSTAT_BUMP(arcstat_deleted);
2858			bytes_deleted += hdr->b_size;
2859
2860			if (HDR_HAS_L2HDR(hdr)) {
2861				/*
2862				 * This buffer is cached on the 2nd Level ARC;
2863				 * don't destroy the header.
2864				 */
2865				arc_change_state(arc_l2c_only, hdr, hash_lock);
2866				/*
2867				 * dropping from L1+L2 cached to L2-only,
2868				 * realloc to remove the L1 header.
2869				 */
2870				hdr = arc_hdr_realloc(hdr, hdr_full_cache,
2871				    hdr_l2only_cache);
2872				mutex_exit(hash_lock);
2873			} else {
2874				arc_change_state(arc_anon, hdr, hash_lock);
2875				mutex_exit(hash_lock);
2876				arc_hdr_destroy(hdr);
2877			}
2878
2879			DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
2880			if (bytes >= 0 && bytes_deleted >= bytes)
2881				break;
2882		} else if (bytes < 0) {
2883			/*
2884			 * Insert a list marker and then wait for the
2885			 * hash lock to become available. Once its
2886			 * available, restart from where we left off.
2887			 */
2888			list_insert_after(list, hdr, &marker);
2889			mutex_exit(lock);
2890			mutex_enter(hash_lock);
2891			mutex_exit(hash_lock);
2892			mutex_enter(lock);
2893			hdr_prev = list_prev(list, &marker);
2894			list_remove(list, &marker);
2895		} else {
2896			bufs_skipped += 1;
2897		}
2898
2899	}
2900	mutex_exit(lock);
2901	idx  = ((idx + 1) & (ARC_BUFC_NUMDATALISTS - 1));
2902	lists++;
2903
2904	if (lists < list_count)
2905		goto evict_start;
2906
2907	evict_offset = idx;
2908	if ((uintptr_t)list > (uintptr_t)&state->arcs_lists[ARC_BUFC_NUMMETADATALISTS] &&
2909	    (bytes < 0 || bytes_deleted < bytes)) {
2910		list_start = &state->arcs_lists[0];
2911		list_count = ARC_BUFC_NUMMETADATALISTS;
2912		offset = lists = 0;
2913		goto evict_start;
2914	}
2915
2916	if (bufs_skipped) {
2917		ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2918		ASSERT(bytes >= 0);
2919	}
2920
2921	if (bytes_deleted < bytes)
2922		dprintf("only deleted %lld bytes from %p",
2923		    (longlong_t)bytes_deleted, state);
2924}
2925
2926static void
2927arc_adjust(void)
2928{
2929	int64_t adjustment, delta;
2930
2931	/*
2932	 * Adjust MRU size
2933	 */
2934
2935	adjustment = MIN((int64_t)(arc_size - arc_c),
2936	    (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2937	    arc_p));
2938
2939	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2940		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2941		(void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2942		adjustment -= delta;
2943	}
2944
2945	if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2946		delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2947		(void) arc_evict(arc_mru, 0, delta, FALSE,
2948		    ARC_BUFC_METADATA);
2949	}
2950
2951	/*
2952	 * Adjust MFU size
2953	 */
2954
2955	adjustment = arc_size - arc_c;
2956
2957	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2958		delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2959		(void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2960		adjustment -= delta;
2961	}
2962
2963	if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2964		int64_t delta = MIN(adjustment,
2965		    arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2966		(void) arc_evict(arc_mfu, 0, delta, FALSE,
2967		    ARC_BUFC_METADATA);
2968	}
2969
2970	/*
2971	 * Adjust ghost lists
2972	 */
2973
2974	adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2975
2976	if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2977		delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2978		arc_evict_ghost(arc_mru_ghost, 0, delta);
2979	}
2980
2981	adjustment =
2982	    arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2983
2984	if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2985		delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2986		arc_evict_ghost(arc_mfu_ghost, 0, delta);
2987	}
2988}
2989
2990static void
2991arc_do_user_evicts(void)
2992{
2993	static arc_buf_t *tmp_arc_eviction_list;
2994
2995	/*
2996	 * Move list over to avoid LOR
2997	 */
2998restart:
2999	mutex_enter(&arc_eviction_mtx);
3000	tmp_arc_eviction_list = arc_eviction_list;
3001	arc_eviction_list = NULL;
3002	mutex_exit(&arc_eviction_mtx);
3003
3004	while (tmp_arc_eviction_list != NULL) {
3005		arc_buf_t *buf = tmp_arc_eviction_list;
3006		tmp_arc_eviction_list = buf->b_next;
3007		mutex_enter(&buf->b_evict_lock);
3008		buf->b_hdr = NULL;
3009		mutex_exit(&buf->b_evict_lock);
3010
3011		if (buf->b_efunc != NULL)
3012			VERIFY0(buf->b_efunc(buf->b_private));
3013
3014		buf->b_efunc = NULL;
3015		buf->b_private = NULL;
3016		kmem_cache_free(buf_cache, buf);
3017	}
3018
3019	if (arc_eviction_list != NULL)
3020		goto restart;
3021}
3022
3023/*
3024 * Flush all *evictable* data from the cache for the given spa.
3025 * NOTE: this will not touch "active" (i.e. referenced) data.
3026 */
3027void
3028arc_flush(spa_t *spa)
3029{
3030	uint64_t guid = 0;
3031
3032	if (spa != NULL)
3033		guid = spa_load_guid(spa);
3034
3035	while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
3036		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
3037		if (spa != NULL)
3038			break;
3039	}
3040	while (arc_mru->arcs_lsize[ARC_BUFC_METADATA]) {
3041		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
3042		if (spa != NULL)
3043			break;
3044	}
3045	while (arc_mfu->arcs_lsize[ARC_BUFC_DATA]) {
3046		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
3047		if (spa != NULL)
3048			break;
3049	}
3050	while (arc_mfu->arcs_lsize[ARC_BUFC_METADATA]) {
3051		(void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
3052		if (spa != NULL)
3053			break;
3054	}
3055
3056	arc_evict_ghost(arc_mru_ghost, guid, -1);
3057	arc_evict_ghost(arc_mfu_ghost, guid, -1);
3058
3059	mutex_enter(&arc_reclaim_thr_lock);
3060	arc_do_user_evicts();
3061	mutex_exit(&arc_reclaim_thr_lock);
3062	ASSERT(spa || arc_eviction_list == NULL);
3063}
3064
3065void
3066arc_shrink(int64_t to_free)
3067{
3068
3069	if (arc_c > arc_c_min) {
3070		DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
3071			arc_c_min, uint64_t, arc_p, uint64_t, to_free);
3072		if (arc_c > arc_c_min + to_free)
3073			atomic_add_64(&arc_c, -to_free);
3074		else
3075			arc_c = arc_c_min;
3076
3077		atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
3078		if (arc_c > arc_size)
3079			arc_c = MAX(arc_size, arc_c_min);
3080		if (arc_p > arc_c)
3081			arc_p = (arc_c >> 1);
3082
3083		DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
3084			arc_p);
3085
3086		ASSERT(arc_c >= arc_c_min);
3087		ASSERT((int64_t)arc_p >= 0);
3088	}
3089
3090	if (arc_size > arc_c) {
3091		DTRACE_PROBE2(arc__shrink_adjust, uint64_t, arc_size,
3092			uint64_t, arc_c);
3093		arc_adjust();
3094	}
3095}
3096
3097static long needfree = 0;
3098
3099typedef enum free_memory_reason_t {
3100	FMR_UNKNOWN,
3101	FMR_NEEDFREE,
3102	FMR_LOTSFREE,
3103	FMR_SWAPFS_MINFREE,
3104	FMR_PAGES_PP_MAXIMUM,
3105	FMR_HEAP_ARENA,
3106	FMR_ZIO_ARENA,
3107	FMR_ZIO_FRAG,
3108} free_memory_reason_t;
3109
3110int64_t last_free_memory;
3111free_memory_reason_t last_free_reason;
3112
3113/*
3114 * Additional reserve of pages for pp_reserve.
3115 */
3116int64_t arc_pages_pp_reserve = 64;
3117
3118/*
3119 * Additional reserve of pages for swapfs.
3120 */
3121int64_t arc_swapfs_reserve = 64;
3122
3123/*
3124 * Return the amount of memory that can be consumed before reclaim will be
3125 * needed.  Positive if there is sufficient free memory, negative indicates
3126 * the amount of memory that needs to be freed up.
3127 */
3128static int64_t
3129arc_available_memory(void)
3130{
3131	int64_t lowest = INT64_MAX;
3132	int64_t n;
3133	free_memory_reason_t r = FMR_UNKNOWN;
3134
3135#ifdef _KERNEL
3136	if (needfree > 0) {
3137		n = PAGESIZE * (-needfree);
3138		if (n < lowest) {
3139			lowest = n;
3140			r = FMR_NEEDFREE;
3141		}
3142	}
3143
3144	/*
3145	 * Cooperate with pagedaemon when it's time for it to scan
3146	 * and reclaim some pages.
3147	 */
3148	n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
3149	if (n < lowest) {
3150		lowest = n;
3151		r = FMR_LOTSFREE;
3152	}
3153
3154#ifdef illumos
3155	/*
3156	 * check that we're out of range of the pageout scanner.  It starts to
3157	 * schedule paging if freemem is less than lotsfree and needfree.
3158	 * lotsfree is the high-water mark for pageout, and needfree is the
3159	 * number of needed free pages.  We add extra pages here to make sure
3160	 * the scanner doesn't start up while we're freeing memory.
3161	 */
3162	n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
3163	if (n < lowest) {
3164		lowest = n;
3165		r = FMR_LOTSFREE;
3166	}
3167
3168	/*
3169	 * check to make sure that swapfs has enough space so that anon
3170	 * reservations can still succeed. anon_resvmem() checks that the
3171	 * availrmem is greater than swapfs_minfree, and the number of reserved
3172	 * swap pages.  We also add a bit of extra here just to prevent
3173	 * circumstances from getting really dire.
3174	 */
3175	n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
3176	    desfree - arc_swapfs_reserve);
3177	if (n < lowest) {
3178		lowest = n;
3179		r = FMR_SWAPFS_MINFREE;
3180	}
3181
3182
3183	/*
3184	 * Check that we have enough availrmem that memory locking (e.g., via
3185	 * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
3186	 * stores the number of pages that cannot be locked; when availrmem
3187	 * drops below pages_pp_maximum, page locking mechanisms such as
3188	 * page_pp_lock() will fail.)
3189	 */
3190	n = PAGESIZE * (availrmem - pages_pp_maximum -
3191	    arc_pages_pp_reserve);
3192	if (n < lowest) {
3193		lowest = n;
3194		r = FMR_PAGES_PP_MAXIMUM;
3195	}
3196
3197#endif	/* illumos */
3198#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
3199	/*
3200	 * If we're on an i386 platform, it's possible that we'll exhaust the
3201	 * kernel heap space before we ever run out of available physical
3202	 * memory.  Most checks of the size of the heap_area compare against
3203	 * tune.t_minarmem, which is the minimum available real memory that we
3204	 * can have in the system.  However, this is generally fixed at 25 pages
3205	 * which is so low that it's useless.  In this comparison, we seek to
3206	 * calculate the total heap-size, and reclaim if more than 3/4ths of the
3207	 * heap is allocated.  (Or, in the calculation, if less than 1/4th is
3208	 * free)
3209	 */
3210	n = (int64_t)vmem_size(heap_arena, VMEM_FREE) -
3211	    (vmem_size(heap_arena, VMEM_FREE | VMEM_ALLOC) >> 2);
3212	if (n < lowest) {
3213		lowest = n;
3214		r = FMR_HEAP_ARENA;
3215	}
3216#define	zio_arena	NULL
3217#else
3218#define	zio_arena	heap_arena
3219#endif
3220
3221	/*
3222	 * If zio data pages are being allocated out of a separate heap segment,
3223	 * then enforce that the size of available vmem for this arena remains
3224	 * above about 1/16th free.
3225	 *
3226	 * Note: The 1/16th arena free requirement was put in place
3227	 * to aggressively evict memory from the arc in order to avoid
3228	 * memory fragmentation issues.
3229	 */
3230	if (zio_arena != NULL) {
3231		n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
3232		    (vmem_size(zio_arena, VMEM_ALLOC) >> 4);
3233		if (n < lowest) {
3234			lowest = n;
3235			r = FMR_ZIO_ARENA;
3236		}
3237	}
3238
3239	/*
3240	 * Above limits know nothing about real level of KVA fragmentation.
3241	 * Start aggressive reclamation if too little sequential KVA left.
3242	 */
3243	if (lowest > 0) {
3244		n = (vmem_size(heap_arena, VMEM_MAXFREE) < zfs_max_recordsize) ?
3245		    -((int64_t)vmem_size(heap_arena, VMEM_ALLOC) >> 4) :
3246		    INT64_MAX;
3247		if (n < lowest) {
3248			lowest = n;
3249			r = FMR_ZIO_FRAG;
3250		}
3251	}
3252
3253#else	/* _KERNEL */
3254	/* Every 100 calls, free a small amount */
3255	if (spa_get_random(100) == 0)
3256		lowest = -1024;
3257#endif	/* _KERNEL */
3258
3259	last_free_memory = lowest;
3260	last_free_reason = r;
3261	DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
3262	return (lowest);
3263}
3264
3265
3266/*
3267 * Determine if the system is under memory pressure and is asking
3268 * to reclaim memory. A return value of TRUE indicates that the system
3269 * is under memory pressure and that the arc should adjust accordingly.
3270 */
3271static boolean_t
3272arc_reclaim_needed(void)
3273{
3274	return (arc_available_memory() < 0);
3275}
3276
3277extern kmem_cache_t	*zio_buf_cache[];
3278extern kmem_cache_t	*zio_data_buf_cache[];
3279extern kmem_cache_t	*range_seg_cache;
3280
3281static __noinline void
3282arc_kmem_reap_now(void)
3283{
3284	size_t			i;
3285	kmem_cache_t		*prev_cache = NULL;
3286	kmem_cache_t		*prev_data_cache = NULL;
3287
3288	DTRACE_PROBE(arc__kmem_reap_start);
3289#ifdef _KERNEL
3290	if (arc_meta_used >= arc_meta_limit) {
3291		/*
3292		 * We are exceeding our meta-data cache limit.
3293		 * Purge some DNLC entries to release holds on meta-data.
3294		 */
3295		dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
3296	}
3297#if defined(__i386)
3298	/*
3299	 * Reclaim unused memory from all kmem caches.
3300	 */
3301	kmem_reap();
3302#endif
3303#endif
3304
3305	for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
3306		if (zio_buf_cache[i] != prev_cache) {
3307			prev_cache = zio_buf_cache[i];
3308			kmem_cache_reap_now(zio_buf_cache[i]);
3309		}
3310		if (zio_data_buf_cache[i] != prev_data_cache) {
3311			prev_data_cache = zio_data_buf_cache[i];
3312			kmem_cache_reap_now(zio_data_buf_cache[i]);
3313		}
3314	}
3315	kmem_cache_reap_now(buf_cache);
3316	kmem_cache_reap_now(hdr_full_cache);
3317	kmem_cache_reap_now(hdr_l2only_cache);
3318	kmem_cache_reap_now(range_seg_cache);
3319
3320#ifdef illumos
3321	if (zio_arena != NULL) {
3322		/*
3323		 * Ask the vmem arena to reclaim unused memory from its
3324		 * quantum caches.
3325		 */
3326		vmem_qcache_reap(zio_arena);
3327	}
3328#endif
3329	DTRACE_PROBE(arc__kmem_reap_end);
3330}
3331
3332static void
3333arc_reclaim_thread(void *dummy __unused)
3334{
3335	clock_t			growtime = 0;
3336	callb_cpr_t		cpr;
3337
3338	CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
3339
3340	mutex_enter(&arc_reclaim_thr_lock);
3341	while (arc_thread_exit == 0) {
3342		int64_t free_memory = arc_available_memory();
3343		if (free_memory < 0) {
3344
3345			arc_no_grow = B_TRUE;
3346			arc_warm = B_TRUE;
3347
3348			/*
3349			 * Wait at least zfs_grow_retry (default 60) seconds
3350			 * before considering growing.
3351			 */
3352			growtime = ddi_get_lbolt() + (arc_grow_retry * hz);
3353
3354			arc_kmem_reap_now();
3355
3356			/*
3357			 * If we are still low on memory, shrink the ARC
3358			 * so that we have arc_shrink_min free space.
3359			 */
3360			free_memory = arc_available_memory();
3361
3362			int64_t to_free =
3363			    (arc_c >> arc_shrink_shift) - free_memory;
3364			if (to_free > 0) {
3365#ifdef _KERNEL
3366				to_free = MAX(to_free, ptob(needfree));
3367#endif
3368				arc_shrink(to_free);
3369			}
3370		} else if (free_memory < arc_c >> arc_no_grow_shift) {
3371			arc_no_grow = B_TRUE;
3372		} else if (ddi_get_lbolt() >= growtime) {
3373			arc_no_grow = B_FALSE;
3374		}
3375
3376		arc_adjust();
3377
3378		if (arc_eviction_list != NULL)
3379			arc_do_user_evicts();
3380
3381#ifdef _KERNEL
3382		if (needfree) {
3383			needfree = 0;
3384			wakeup(&needfree);
3385		}
3386#endif
3387
3388		/*
3389		 * This is necessary in order for the mdb ::arc dcmd to
3390		 * show up to date information. Since the ::arc command
3391		 * does not call the kstat's update function, without
3392		 * this call, the command may show stale stats for the
3393		 * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
3394		 * with this change, the data might be up to 1 second
3395		 * out of date; but that should suffice. The arc_state_t
3396		 * structures can be queried directly if more accurate
3397		 * information is needed.
3398		 */
3399		if (arc_ksp != NULL)
3400			arc_ksp->ks_update(arc_ksp, KSTAT_READ);
3401
3402		/* block until needed, or one second, whichever is shorter */
3403		CALLB_CPR_SAFE_BEGIN(&cpr);
3404		(void) cv_timedwait(&arc_reclaim_thr_cv,
3405		    &arc_reclaim_thr_lock, hz);
3406		CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
3407	}
3408
3409	arc_thread_exit = 0;
3410	cv_broadcast(&arc_reclaim_thr_cv);
3411	CALLB_CPR_EXIT(&cpr);		/* drops arc_reclaim_thr_lock */
3412	thread_exit();
3413}
3414
3415/*
3416 * Adapt arc info given the number of bytes we are trying to add and
3417 * the state that we are comming from.  This function is only called
3418 * when we are adding new content to the cache.
3419 */
3420static void
3421arc_adapt(int bytes, arc_state_t *state)
3422{
3423	int mult;
3424	uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
3425
3426	if (state == arc_l2c_only)
3427		return;
3428
3429	ASSERT(bytes > 0);
3430	/*
3431	 * Adapt the target size of the MRU list:
3432	 *	- if we just hit in the MRU ghost list, then increase
3433	 *	  the target size of the MRU list.
3434	 *	- if we just hit in the MFU ghost list, then increase
3435	 *	  the target size of the MFU list by decreasing the
3436	 *	  target size of the MRU list.
3437	 */
3438	if (state == arc_mru_ghost) {
3439		mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
3440		    1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
3441		mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
3442
3443		arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
3444	} else if (state == arc_mfu_ghost) {
3445		uint64_t delta;
3446
3447		mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
3448		    1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
3449		mult = MIN(mult, 10);
3450
3451		delta = MIN(bytes * mult, arc_p);
3452		arc_p = MAX(arc_p_min, arc_p - delta);
3453	}
3454	ASSERT((int64_t)arc_p >= 0);
3455
3456	if (arc_reclaim_needed()) {
3457		cv_signal(&arc_reclaim_thr_cv);
3458		return;
3459	}
3460
3461	if (arc_no_grow)
3462		return;
3463
3464	if (arc_c >= arc_c_max)
3465		return;
3466
3467	/*
3468	 * If we're within (2 * maxblocksize) bytes of the target
3469	 * cache size, increment the target cache size
3470	 */
3471	if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
3472		DTRACE_PROBE1(arc__inc_adapt, int, bytes);
3473		atomic_add_64(&arc_c, (int64_t)bytes);
3474		if (arc_c > arc_c_max)
3475			arc_c = arc_c_max;
3476		else if (state == arc_anon)
3477			atomic_add_64(&arc_p, (int64_t)bytes);
3478		if (arc_p > arc_c)
3479			arc_p = arc_c;
3480	}
3481	ASSERT((int64_t)arc_p >= 0);
3482}
3483
3484/*
3485 * Check if the cache has reached its limits and eviction is required
3486 * prior to insert.
3487 */
3488static int
3489arc_evict_needed(arc_buf_contents_t type)
3490{
3491	if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
3492		return (1);
3493
3494	if (arc_reclaim_needed())
3495		return (1);
3496
3497	return (arc_size > arc_c);
3498}
3499
3500/*
3501 * The buffer, supplied as the first argument, needs a data block.
3502 * So, if we are at cache max, determine which cache should be victimized.
3503 * We have the following cases:
3504 *
3505 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
3506 * In this situation if we're out of space, but the resident size of the MFU is
3507 * under the limit, victimize the MFU cache to satisfy this insertion request.
3508 *
3509 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
3510 * Here, we've used up all of the available space for the MRU, so we need to
3511 * evict from our own cache instead.  Evict from the set of resident MRU
3512 * entries.
3513 *
3514 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
3515 * c minus p represents the MFU space in the cache, since p is the size of the
3516 * cache that is dedicated to the MRU.  In this situation there's still space on
3517 * the MFU side, so the MRU side needs to be victimized.
3518 *
3519 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
3520 * MFU's resident set is consuming more space than it has been allotted.  In
3521 * this situation, we must victimize our own cache, the MFU, for this insertion.
3522 */
3523static void
3524arc_get_data_buf(arc_buf_t *buf)
3525{
3526	arc_state_t		*state = buf->b_hdr->b_l1hdr.b_state;
3527	uint64_t		size = buf->b_hdr->b_size;
3528	arc_buf_contents_t	type = arc_buf_type(buf->b_hdr);
3529
3530	arc_adapt(size, state);
3531
3532	/*
3533	 * We have not yet reached cache maximum size,
3534	 * just allocate a new buffer.
3535	 */
3536	if (!arc_evict_needed(type)) {
3537		if (type == ARC_BUFC_METADATA) {
3538			buf->b_data = zio_buf_alloc(size);
3539			arc_space_consume(size, ARC_SPACE_META);
3540		} else {
3541			ASSERT(type == ARC_BUFC_DATA);
3542			buf->b_data = zio_data_buf_alloc(size);
3543			arc_space_consume(size, ARC_SPACE_DATA);
3544		}
3545		goto out;
3546	}
3547
3548	/*
3549	 * If we are prefetching from the mfu ghost list, this buffer
3550	 * will end up on the mru list; so steal space from there.
3551	 */
3552	if (state == arc_mfu_ghost)
3553		state = HDR_PREFETCH(buf->b_hdr) ? arc_mru : arc_mfu;
3554	else if (state == arc_mru_ghost)
3555		state = arc_mru;
3556
3557	if (state == arc_mru || state == arc_anon) {
3558		uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
3559		state = (arc_mfu->arcs_lsize[type] >= size &&
3560		    arc_p > mru_used) ? arc_mfu : arc_mru;
3561	} else {
3562		/* MFU cases */
3563		uint64_t mfu_space = arc_c - arc_p;
3564		state =  (arc_mru->arcs_lsize[type] >= size &&
3565		    mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
3566	}
3567	if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
3568		if (type == ARC_BUFC_METADATA) {
3569			buf->b_data = zio_buf_alloc(size);
3570			arc_space_consume(size, ARC_SPACE_META);
3571		} else {
3572			ASSERT(type == ARC_BUFC_DATA);
3573			buf->b_data = zio_data_buf_alloc(size);
3574			arc_space_consume(size, ARC_SPACE_DATA);
3575		}
3576		ARCSTAT_BUMP(arcstat_recycle_miss);
3577	}
3578	ASSERT(buf->b_data != NULL);
3579out:
3580	/*
3581	 * Update the state size.  Note that ghost states have a
3582	 * "ghost size" and so don't need to be updated.
3583	 */
3584	if (!GHOST_STATE(buf->b_hdr->b_l1hdr.b_state)) {
3585		arc_buf_hdr_t *hdr = buf->b_hdr;
3586
3587		atomic_add_64(&hdr->b_l1hdr.b_state->arcs_size, size);
3588		if (list_link_active(&hdr->b_l1hdr.b_arc_node)) {
3589			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3590			atomic_add_64(&hdr->b_l1hdr.b_state->arcs_lsize[type],
3591			    size);
3592		}
3593		/*
3594		 * If we are growing the cache, and we are adding anonymous
3595		 * data, and we have outgrown arc_p, update arc_p
3596		 */
3597		if (arc_size < arc_c && hdr->b_l1hdr.b_state == arc_anon &&
3598		    arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
3599			arc_p = MIN(arc_c, arc_p + size);
3600	}
3601	ARCSTAT_BUMP(arcstat_allocated);
3602}
3603
3604/*
3605 * This routine is called whenever a buffer is accessed.
3606 * NOTE: the hash lock is dropped in this function.
3607 */
3608static void
3609arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3610{
3611	clock_t now;
3612
3613	ASSERT(MUTEX_HELD(hash_lock));
3614	ASSERT(HDR_HAS_L1HDR(hdr));
3615
3616	if (hdr->b_l1hdr.b_state == arc_anon) {
3617		/*
3618		 * This buffer is not in the cache, and does not
3619		 * appear in our "ghost" list.  Add the new buffer
3620		 * to the MRU state.
3621		 */
3622
3623		ASSERT0(hdr->b_l1hdr.b_arc_access);
3624		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3625		DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3626		arc_change_state(arc_mru, hdr, hash_lock);
3627
3628	} else if (hdr->b_l1hdr.b_state == arc_mru) {
3629		now = ddi_get_lbolt();
3630
3631		/*
3632		 * If this buffer is here because of a prefetch, then either:
3633		 * - clear the flag if this is a "referencing" read
3634		 *   (any subsequent access will bump this into the MFU state).
3635		 * or
3636		 * - move the buffer to the head of the list if this is
3637		 *   another prefetch (to make it less likely to be evicted).
3638		 */
3639		if (HDR_PREFETCH(hdr)) {
3640			if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
3641				ASSERT(list_link_active(
3642				    &hdr->b_l1hdr.b_arc_node));
3643			} else {
3644				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3645				ARCSTAT_BUMP(arcstat_mru_hits);
3646			}
3647			hdr->b_l1hdr.b_arc_access = now;
3648			return;
3649		}
3650
3651		/*
3652		 * This buffer has been "accessed" only once so far,
3653		 * but it is still in the cache. Move it to the MFU
3654		 * state.
3655		 */
3656		if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
3657			/*
3658			 * More than 125ms have passed since we
3659			 * instantiated this buffer.  Move it to the
3660			 * most frequently used state.
3661			 */
3662			hdr->b_l1hdr.b_arc_access = now;
3663			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3664			arc_change_state(arc_mfu, hdr, hash_lock);
3665		}
3666		ARCSTAT_BUMP(arcstat_mru_hits);
3667	} else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
3668		arc_state_t	*new_state;
3669		/*
3670		 * This buffer has been "accessed" recently, but
3671		 * was evicted from the cache.  Move it to the
3672		 * MFU state.
3673		 */
3674
3675		if (HDR_PREFETCH(hdr)) {
3676			new_state = arc_mru;
3677			if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0)
3678				hdr->b_flags &= ~ARC_FLAG_PREFETCH;
3679			DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
3680		} else {
3681			new_state = arc_mfu;
3682			DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3683		}
3684
3685		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3686		arc_change_state(new_state, hdr, hash_lock);
3687
3688		ARCSTAT_BUMP(arcstat_mru_ghost_hits);
3689	} else if (hdr->b_l1hdr.b_state == arc_mfu) {
3690		/*
3691		 * This buffer has been accessed more than once and is
3692		 * still in the cache.  Keep it in the MFU state.
3693		 *
3694		 * NOTE: an add_reference() that occurred when we did
3695		 * the arc_read() will have kicked this off the list.
3696		 * If it was a prefetch, we will explicitly move it to
3697		 * the head of the list now.
3698		 */
3699		if ((HDR_PREFETCH(hdr)) != 0) {
3700			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3701			ASSERT(list_link_active(&hdr->b_l1hdr.b_arc_node));
3702		}
3703		ARCSTAT_BUMP(arcstat_mfu_hits);
3704		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3705	} else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
3706		arc_state_t	*new_state = arc_mfu;
3707		/*
3708		 * This buffer has been accessed more than once but has
3709		 * been evicted from the cache.  Move it back to the
3710		 * MFU state.
3711		 */
3712
3713		if (HDR_PREFETCH(hdr)) {
3714			/*
3715			 * This is a prefetch access...
3716			 * move this block back to the MRU state.
3717			 */
3718			ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3719			new_state = arc_mru;
3720		}
3721
3722		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3723		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3724		arc_change_state(new_state, hdr, hash_lock);
3725
3726		ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
3727	} else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
3728		/*
3729		 * This buffer is on the 2nd Level ARC.
3730		 */
3731
3732		hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
3733		DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
3734		arc_change_state(arc_mfu, hdr, hash_lock);
3735	} else {
3736		ASSERT(!"invalid arc state");
3737	}
3738}
3739
3740/* a generic arc_done_func_t which you can use */
3741/* ARGSUSED */
3742void
3743arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
3744{
3745	if (zio == NULL || zio->io_error == 0)
3746		bcopy(buf->b_data, arg, buf->b_hdr->b_size);
3747	VERIFY(arc_buf_remove_ref(buf, arg));
3748}
3749
3750/* a generic arc_done_func_t */
3751void
3752arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
3753{
3754	arc_buf_t **bufp = arg;
3755	if (zio && zio->io_error) {
3756		VERIFY(arc_buf_remove_ref(buf, arg));
3757		*bufp = NULL;
3758	} else {
3759		*bufp = buf;
3760		ASSERT(buf->b_data);
3761	}
3762}
3763
3764static void
3765arc_read_done(zio_t *zio)
3766{
3767	arc_buf_hdr_t	*hdr;
3768	arc_buf_t	*buf;
3769	arc_buf_t	*abuf;	/* buffer we're assigning to callback */
3770	kmutex_t	*hash_lock = NULL;
3771	arc_callback_t	*callback_list, *acb;
3772	int		freeable = FALSE;
3773
3774	buf = zio->io_private;
3775	hdr = buf->b_hdr;
3776
3777	/*
3778	 * The hdr was inserted into hash-table and removed from lists
3779	 * prior to starting I/O.  We should find this header, since
3780	 * it's in the hash table, and it should be legit since it's
3781	 * not possible to evict it during the I/O.  The only possible
3782	 * reason for it not to be found is if we were freed during the
3783	 * read.
3784	 */
3785	if (HDR_IN_HASH_TABLE(hdr)) {
3786		ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
3787		ASSERT3U(hdr->b_dva.dva_word[0], ==,
3788		    BP_IDENTITY(zio->io_bp)->dva_word[0]);
3789		ASSERT3U(hdr->b_dva.dva_word[1], ==,
3790		    BP_IDENTITY(zio->io_bp)->dva_word[1]);
3791
3792		arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
3793		    &hash_lock);
3794
3795		ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) &&
3796		    hash_lock == NULL) ||
3797		    (found == hdr &&
3798		    DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
3799		    (found == hdr && HDR_L2_READING(hdr)));
3800	}
3801
3802	hdr->b_flags &= ~ARC_FLAG_L2_EVICTED;
3803	if (l2arc_noprefetch && HDR_PREFETCH(hdr))
3804		hdr->b_flags &= ~ARC_FLAG_L2CACHE;
3805
3806	/* byteswap if necessary */
3807	callback_list = hdr->b_l1hdr.b_acb;
3808	ASSERT(callback_list != NULL);
3809	if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
3810		dmu_object_byteswap_t bswap =
3811		    DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
3812		arc_byteswap_func_t *func = BP_GET_LEVEL(zio->io_bp) > 0 ?
3813		    byteswap_uint64_array :
3814		    dmu_ot_byteswap[bswap].ob_func;
3815		func(buf->b_data, hdr->b_size);
3816	}
3817
3818	arc_cksum_compute(buf, B_FALSE);
3819#ifdef illumos
3820	arc_buf_watch(buf);
3821#endif
3822
3823	if (hash_lock && zio->io_error == 0 &&
3824	    hdr->b_l1hdr.b_state == arc_anon) {
3825		/*
3826		 * Only call arc_access on anonymous buffers.  This is because
3827		 * if we've issued an I/O for an evicted buffer, we've already
3828		 * called arc_access (to prevent any simultaneous readers from
3829		 * getting confused).
3830		 */
3831		arc_access(hdr, hash_lock);
3832	}
3833
3834	/* create copies of the data buffer for the callers */
3835	abuf = buf;
3836	for (acb = callback_list; acb; acb = acb->acb_next) {
3837		if (acb->acb_done) {
3838			if (abuf == NULL) {
3839				ARCSTAT_BUMP(arcstat_duplicate_reads);
3840				abuf = arc_buf_clone(buf);
3841			}
3842			acb->acb_buf = abuf;
3843			abuf = NULL;
3844		}
3845	}
3846	hdr->b_l1hdr.b_acb = NULL;
3847	hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
3848	ASSERT(!HDR_BUF_AVAILABLE(hdr));
3849	if (abuf == buf) {
3850		ASSERT(buf->b_efunc == NULL);
3851		ASSERT(hdr->b_l1hdr.b_datacnt == 1);
3852		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
3853	}
3854
3855	ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
3856	    callback_list != NULL);
3857
3858	if (zio->io_error != 0) {
3859		hdr->b_flags |= ARC_FLAG_IO_ERROR;
3860		if (hdr->b_l1hdr.b_state != arc_anon)
3861			arc_change_state(arc_anon, hdr, hash_lock);
3862		if (HDR_IN_HASH_TABLE(hdr))
3863			buf_hash_remove(hdr);
3864		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
3865	}
3866
3867	/*
3868	 * Broadcast before we drop the hash_lock to avoid the possibility
3869	 * that the hdr (and hence the cv) might be freed before we get to
3870	 * the cv_broadcast().
3871	 */
3872	cv_broadcast(&hdr->b_l1hdr.b_cv);
3873
3874	if (hash_lock != NULL) {
3875		mutex_exit(hash_lock);
3876	} else {
3877		/*
3878		 * This block was freed while we waited for the read to
3879		 * complete.  It has been removed from the hash table and
3880		 * moved to the anonymous state (so that it won't show up
3881		 * in the cache).
3882		 */
3883		ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3884		freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
3885	}
3886
3887	/* execute each callback and free its structure */
3888	while ((acb = callback_list) != NULL) {
3889		if (acb->acb_done)
3890			acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3891
3892		if (acb->acb_zio_dummy != NULL) {
3893			acb->acb_zio_dummy->io_error = zio->io_error;
3894			zio_nowait(acb->acb_zio_dummy);
3895		}
3896
3897		callback_list = acb->acb_next;
3898		kmem_free(acb, sizeof (arc_callback_t));
3899	}
3900
3901	if (freeable)
3902		arc_hdr_destroy(hdr);
3903}
3904
3905/*
3906 * "Read" the block block at the specified DVA (in bp) via the
3907 * cache.  If the block is found in the cache, invoke the provided
3908 * callback immediately and return.  Note that the `zio' parameter
3909 * in the callback will be NULL in this case, since no IO was
3910 * required.  If the block is not in the cache pass the read request
3911 * on to the spa with a substitute callback function, so that the
3912 * requested block will be added to the cache.
3913 *
3914 * If a read request arrives for a block that has a read in-progress,
3915 * either wait for the in-progress read to complete (and return the
3916 * results); or, if this is a read with a "done" func, add a record
3917 * to the read to invoke the "done" func when the read completes,
3918 * and return; or just return.
3919 *
3920 * arc_read_done() will invoke all the requested "done" functions
3921 * for readers of this block.
3922 */
3923int
3924arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3925    void *private, zio_priority_t priority, int zio_flags,
3926    arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
3927{
3928	arc_buf_hdr_t *hdr = NULL;
3929	arc_buf_t *buf = NULL;
3930	kmutex_t *hash_lock = NULL;
3931	zio_t *rzio;
3932	uint64_t guid = spa_load_guid(spa);
3933
3934	ASSERT(!BP_IS_EMBEDDED(bp) ||
3935	    BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
3936
3937top:
3938	if (!BP_IS_EMBEDDED(bp)) {
3939		/*
3940		 * Embedded BP's have no DVA and require no I/O to "read".
3941		 * Create an anonymous arc buf to back it.
3942		 */
3943		hdr = buf_hash_find(guid, bp, &hash_lock);
3944	}
3945
3946	if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_datacnt > 0) {
3947
3948		*arc_flags |= ARC_FLAG_CACHED;
3949
3950		if (HDR_IO_IN_PROGRESS(hdr)) {
3951
3952			if (*arc_flags & ARC_FLAG_WAIT) {
3953				cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
3954				mutex_exit(hash_lock);
3955				goto top;
3956			}
3957			ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
3958
3959			if (done) {
3960				arc_callback_t	*acb = NULL;
3961
3962				acb = kmem_zalloc(sizeof (arc_callback_t),
3963				    KM_SLEEP);
3964				acb->acb_done = done;
3965				acb->acb_private = private;
3966				if (pio != NULL)
3967					acb->acb_zio_dummy = zio_null(pio,
3968					    spa, NULL, NULL, NULL, zio_flags);
3969
3970				ASSERT(acb->acb_done != NULL);
3971				acb->acb_next = hdr->b_l1hdr.b_acb;
3972				hdr->b_l1hdr.b_acb = acb;
3973				add_reference(hdr, hash_lock, private);
3974				mutex_exit(hash_lock);
3975				return (0);
3976			}
3977			mutex_exit(hash_lock);
3978			return (0);
3979		}
3980
3981		ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
3982		    hdr->b_l1hdr.b_state == arc_mfu);
3983
3984		if (done) {
3985			add_reference(hdr, hash_lock, private);
3986			/*
3987			 * If this block is already in use, create a new
3988			 * copy of the data so that we will be guaranteed
3989			 * that arc_release() will always succeed.
3990			 */
3991			buf = hdr->b_l1hdr.b_buf;
3992			ASSERT(buf);
3993			ASSERT(buf->b_data);
3994			if (HDR_BUF_AVAILABLE(hdr)) {
3995				ASSERT(buf->b_efunc == NULL);
3996				hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
3997			} else {
3998				buf = arc_buf_clone(buf);
3999			}
4000
4001		} else if (*arc_flags & ARC_FLAG_PREFETCH &&
4002		    refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
4003			hdr->b_flags |= ARC_FLAG_PREFETCH;
4004		}
4005		DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
4006		arc_access(hdr, hash_lock);
4007		if (*arc_flags & ARC_FLAG_L2CACHE)
4008			hdr->b_flags |= ARC_FLAG_L2CACHE;
4009		if (*arc_flags & ARC_FLAG_L2COMPRESS)
4010			hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4011		mutex_exit(hash_lock);
4012		ARCSTAT_BUMP(arcstat_hits);
4013		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4014		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4015		    data, metadata, hits);
4016
4017		if (done)
4018			done(NULL, buf, private);
4019	} else {
4020		uint64_t size = BP_GET_LSIZE(bp);
4021		arc_callback_t *acb;
4022		vdev_t *vd = NULL;
4023		uint64_t addr = 0;
4024		boolean_t devw = B_FALSE;
4025		enum zio_compress b_compress = ZIO_COMPRESS_OFF;
4026		int32_t b_asize = 0;
4027
4028		if (hdr == NULL) {
4029			/* this block is not in the cache */
4030			arc_buf_hdr_t *exists = NULL;
4031			arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
4032			buf = arc_buf_alloc(spa, size, private, type);
4033			hdr = buf->b_hdr;
4034			if (!BP_IS_EMBEDDED(bp)) {
4035				hdr->b_dva = *BP_IDENTITY(bp);
4036				hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
4037				exists = buf_hash_insert(hdr, &hash_lock);
4038			}
4039			if (exists != NULL) {
4040				/* somebody beat us to the hash insert */
4041				mutex_exit(hash_lock);
4042				buf_discard_identity(hdr);
4043				(void) arc_buf_remove_ref(buf, private);
4044				goto top; /* restart the IO request */
4045			}
4046
4047			/* if this is a prefetch, we don't have a reference */
4048			if (*arc_flags & ARC_FLAG_PREFETCH) {
4049				(void) remove_reference(hdr, hash_lock,
4050				    private);
4051				hdr->b_flags |= ARC_FLAG_PREFETCH;
4052			}
4053			if (*arc_flags & ARC_FLAG_L2CACHE)
4054				hdr->b_flags |= ARC_FLAG_L2CACHE;
4055			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4056				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4057			if (BP_GET_LEVEL(bp) > 0)
4058				hdr->b_flags |= ARC_FLAG_INDIRECT;
4059		} else {
4060			/*
4061			 * This block is in the ghost cache. If it was L2-only
4062			 * (and thus didn't have an L1 hdr), we realloc the
4063			 * header to add an L1 hdr.
4064			 */
4065			if (!HDR_HAS_L1HDR(hdr)) {
4066				hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
4067				    hdr_full_cache);
4068			}
4069
4070			ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
4071			ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4072			ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4073			ASSERT(hdr->b_l1hdr.b_buf == NULL);
4074
4075			/* if this is a prefetch, we don't have a reference */
4076			if (*arc_flags & ARC_FLAG_PREFETCH)
4077				hdr->b_flags |= ARC_FLAG_PREFETCH;
4078			else
4079				add_reference(hdr, hash_lock, private);
4080			if (*arc_flags & ARC_FLAG_L2CACHE)
4081				hdr->b_flags |= ARC_FLAG_L2CACHE;
4082			if (*arc_flags & ARC_FLAG_L2COMPRESS)
4083				hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4084			buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
4085			buf->b_hdr = hdr;
4086			buf->b_data = NULL;
4087			buf->b_efunc = NULL;
4088			buf->b_private = NULL;
4089			buf->b_next = NULL;
4090			hdr->b_l1hdr.b_buf = buf;
4091			ASSERT0(hdr->b_l1hdr.b_datacnt);
4092			hdr->b_l1hdr.b_datacnt = 1;
4093			arc_get_data_buf(buf);
4094			arc_access(hdr, hash_lock);
4095		}
4096
4097		ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
4098
4099		acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
4100		acb->acb_done = done;
4101		acb->acb_private = private;
4102
4103		ASSERT(hdr->b_l1hdr.b_acb == NULL);
4104		hdr->b_l1hdr.b_acb = acb;
4105		hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4106
4107		if (HDR_HAS_L2HDR(hdr) &&
4108		    (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
4109			devw = hdr->b_l2hdr.b_dev->l2ad_writing;
4110			addr = hdr->b_l2hdr.b_daddr;
4111			b_compress = HDR_GET_COMPRESS(hdr);
4112			b_asize = hdr->b_l2hdr.b_asize;
4113			/*
4114			 * Lock out device removal.
4115			 */
4116			if (vdev_is_dead(vd) ||
4117			    !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
4118				vd = NULL;
4119		}
4120
4121		if (hash_lock != NULL)
4122			mutex_exit(hash_lock);
4123
4124		/*
4125		 * At this point, we have a level 1 cache miss.  Try again in
4126		 * L2ARC if possible.
4127		 */
4128		ASSERT3U(hdr->b_size, ==, size);
4129		DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
4130		    uint64_t, size, zbookmark_phys_t *, zb);
4131		ARCSTAT_BUMP(arcstat_misses);
4132		ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
4133		    demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
4134		    data, metadata, misses);
4135#ifdef _KERNEL
4136		curthread->td_ru.ru_inblock++;
4137#endif
4138
4139		if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
4140			/*
4141			 * Read from the L2ARC if the following are true:
4142			 * 1. The L2ARC vdev was previously cached.
4143			 * 2. This buffer still has L2ARC metadata.
4144			 * 3. This buffer isn't currently writing to the L2ARC.
4145			 * 4. The L2ARC entry wasn't evicted, which may
4146			 *    also have invalidated the vdev.
4147			 * 5. This isn't prefetch and l2arc_noprefetch is set.
4148			 */
4149			if (HDR_HAS_L2HDR(hdr) &&
4150			    !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
4151			    !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
4152				l2arc_read_callback_t *cb;
4153
4154				DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
4155				ARCSTAT_BUMP(arcstat_l2_hits);
4156
4157				cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
4158				    KM_SLEEP);
4159				cb->l2rcb_buf = buf;
4160				cb->l2rcb_spa = spa;
4161				cb->l2rcb_bp = *bp;
4162				cb->l2rcb_zb = *zb;
4163				cb->l2rcb_flags = zio_flags;
4164				cb->l2rcb_compress = b_compress;
4165
4166				ASSERT(addr >= VDEV_LABEL_START_SIZE &&
4167				    addr + size < vd->vdev_psize -
4168				    VDEV_LABEL_END_SIZE);
4169
4170				/*
4171				 * l2arc read.  The SCL_L2ARC lock will be
4172				 * released by l2arc_read_done().
4173				 * Issue a null zio if the underlying buffer
4174				 * was squashed to zero size by compression.
4175				 */
4176				if (b_compress == ZIO_COMPRESS_EMPTY) {
4177					rzio = zio_null(pio, spa, vd,
4178					    l2arc_read_done, cb,
4179					    zio_flags | ZIO_FLAG_DONT_CACHE |
4180					    ZIO_FLAG_CANFAIL |
4181					    ZIO_FLAG_DONT_PROPAGATE |
4182					    ZIO_FLAG_DONT_RETRY);
4183				} else {
4184					rzio = zio_read_phys(pio, vd, addr,
4185					    b_asize, buf->b_data,
4186					    ZIO_CHECKSUM_OFF,
4187					    l2arc_read_done, cb, priority,
4188					    zio_flags | ZIO_FLAG_DONT_CACHE |
4189					    ZIO_FLAG_CANFAIL |
4190					    ZIO_FLAG_DONT_PROPAGATE |
4191					    ZIO_FLAG_DONT_RETRY, B_FALSE);
4192				}
4193				DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
4194				    zio_t *, rzio);
4195				ARCSTAT_INCR(arcstat_l2_read_bytes, b_asize);
4196
4197				if (*arc_flags & ARC_FLAG_NOWAIT) {
4198					zio_nowait(rzio);
4199					return (0);
4200				}
4201
4202				ASSERT(*arc_flags & ARC_FLAG_WAIT);
4203				if (zio_wait(rzio) == 0)
4204					return (0);
4205
4206				/* l2arc read error; goto zio_read() */
4207			} else {
4208				DTRACE_PROBE1(l2arc__miss,
4209				    arc_buf_hdr_t *, hdr);
4210				ARCSTAT_BUMP(arcstat_l2_misses);
4211				if (HDR_L2_WRITING(hdr))
4212					ARCSTAT_BUMP(arcstat_l2_rw_clash);
4213				spa_config_exit(spa, SCL_L2ARC, vd);
4214			}
4215		} else {
4216			if (vd != NULL)
4217				spa_config_exit(spa, SCL_L2ARC, vd);
4218			if (l2arc_ndev != 0) {
4219				DTRACE_PROBE1(l2arc__miss,
4220				    arc_buf_hdr_t *, hdr);
4221				ARCSTAT_BUMP(arcstat_l2_misses);
4222			}
4223		}
4224
4225		rzio = zio_read(pio, spa, bp, buf->b_data, size,
4226		    arc_read_done, buf, priority, zio_flags, zb);
4227
4228		if (*arc_flags & ARC_FLAG_WAIT)
4229			return (zio_wait(rzio));
4230
4231		ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
4232		zio_nowait(rzio);
4233	}
4234	return (0);
4235}
4236
4237void
4238arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
4239{
4240	ASSERT(buf->b_hdr != NULL);
4241	ASSERT(buf->b_hdr->b_l1hdr.b_state != arc_anon);
4242	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt) ||
4243	    func == NULL);
4244	ASSERT(buf->b_efunc == NULL);
4245	ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
4246
4247	buf->b_efunc = func;
4248	buf->b_private = private;
4249}
4250
4251/*
4252 * Notify the arc that a block was freed, and thus will never be used again.
4253 */
4254void
4255arc_freed(spa_t *spa, const blkptr_t *bp)
4256{
4257	arc_buf_hdr_t *hdr;
4258	kmutex_t *hash_lock;
4259	uint64_t guid = spa_load_guid(spa);
4260
4261	ASSERT(!BP_IS_EMBEDDED(bp));
4262
4263	hdr = buf_hash_find(guid, bp, &hash_lock);
4264	if (hdr == NULL)
4265		return;
4266	if (HDR_BUF_AVAILABLE(hdr)) {
4267		arc_buf_t *buf = hdr->b_l1hdr.b_buf;
4268		add_reference(hdr, hash_lock, FTAG);
4269		hdr->b_flags &= ~ARC_FLAG_BUF_AVAILABLE;
4270		mutex_exit(hash_lock);
4271
4272		arc_release(buf, FTAG);
4273		(void) arc_buf_remove_ref(buf, FTAG);
4274	} else {
4275		mutex_exit(hash_lock);
4276	}
4277
4278}
4279
4280/*
4281 * Clear the user eviction callback set by arc_set_callback(), first calling
4282 * it if it exists.  Because the presence of a callback keeps an arc_buf cached
4283 * clearing the callback may result in the arc_buf being destroyed.  However,
4284 * it will not result in the *last* arc_buf being destroyed, hence the data
4285 * will remain cached in the ARC. We make a copy of the arc buffer here so
4286 * that we can process the callback without holding any locks.
4287 *
4288 * It's possible that the callback is already in the process of being cleared
4289 * by another thread.  In this case we can not clear the callback.
4290 *
4291 * Returns B_TRUE if the callback was successfully called and cleared.
4292 */
4293boolean_t
4294arc_clear_callback(arc_buf_t *buf)
4295{
4296	arc_buf_hdr_t *hdr;
4297	kmutex_t *hash_lock;
4298	arc_evict_func_t *efunc = buf->b_efunc;
4299	void *private = buf->b_private;
4300	list_t *list, *evicted_list;
4301	kmutex_t *lock, *evicted_lock;
4302
4303	mutex_enter(&buf->b_evict_lock);
4304	hdr = buf->b_hdr;
4305	if (hdr == NULL) {
4306		/*
4307		 * We are in arc_do_user_evicts().
4308		 */
4309		ASSERT(buf->b_data == NULL);
4310		mutex_exit(&buf->b_evict_lock);
4311		return (B_FALSE);
4312	} else if (buf->b_data == NULL) {
4313		/*
4314		 * We are on the eviction list; process this buffer now
4315		 * but let arc_do_user_evicts() do the reaping.
4316		 */
4317		buf->b_efunc = NULL;
4318		mutex_exit(&buf->b_evict_lock);
4319		VERIFY0(efunc(private));
4320		return (B_TRUE);
4321	}
4322	hash_lock = HDR_LOCK(hdr);
4323	mutex_enter(hash_lock);
4324	hdr = buf->b_hdr;
4325	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4326
4327	ASSERT3U(refcount_count(&hdr->b_l1hdr.b_refcnt), <,
4328	    hdr->b_l1hdr.b_datacnt);
4329	ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
4330	    hdr->b_l1hdr.b_state == arc_mfu);
4331
4332	buf->b_efunc = NULL;
4333	buf->b_private = NULL;
4334
4335	if (hdr->b_l1hdr.b_datacnt > 1) {
4336		mutex_exit(&buf->b_evict_lock);
4337		arc_buf_destroy(buf, FALSE, TRUE);
4338	} else {
4339		ASSERT(buf == hdr->b_l1hdr.b_buf);
4340		hdr->b_flags |= ARC_FLAG_BUF_AVAILABLE;
4341		mutex_exit(&buf->b_evict_lock);
4342	}
4343
4344	mutex_exit(hash_lock);
4345	VERIFY0(efunc(private));
4346	return (B_TRUE);
4347}
4348
4349/*
4350 * Release this buffer from the cache, making it an anonymous buffer.  This
4351 * must be done after a read and prior to modifying the buffer contents.
4352 * If the buffer has more than one reference, we must make
4353 * a new hdr for the buffer.
4354 */
4355void
4356arc_release(arc_buf_t *buf, void *tag)
4357{
4358	arc_buf_hdr_t *hdr = buf->b_hdr;
4359
4360	/*
4361	 * It would be nice to assert that if it's DMU metadata (level >
4362	 * 0 || it's the dnode file), then it must be syncing context.
4363	 * But we don't know that information at this level.
4364	 */
4365
4366	mutex_enter(&buf->b_evict_lock);
4367	/*
4368	 * We don't grab the hash lock prior to this check, because if
4369	 * the buffer's header is in the arc_anon state, it won't be
4370	 * linked into the hash table.
4371	 */
4372	if (hdr->b_l1hdr.b_state == arc_anon) {
4373		mutex_exit(&buf->b_evict_lock);
4374		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4375		ASSERT(!HDR_IN_HASH_TABLE(hdr));
4376		ASSERT(!HDR_HAS_L2HDR(hdr));
4377		ASSERT(BUF_EMPTY(hdr));
4378		ASSERT3U(hdr->b_l1hdr.b_datacnt, ==, 1);
4379		ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
4380		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4381
4382		ASSERT3P(buf->b_efunc, ==, NULL);
4383		ASSERT3P(buf->b_private, ==, NULL);
4384
4385		hdr->b_l1hdr.b_arc_access = 0;
4386		arc_buf_thaw(buf);
4387
4388		return;
4389	}
4390
4391	kmutex_t *hash_lock = HDR_LOCK(hdr);
4392	mutex_enter(hash_lock);
4393
4394	/*
4395	 * This assignment is only valid as long as the hash_lock is
4396	 * held, we must be careful not to reference state or the
4397	 * b_state field after dropping the lock.
4398	 */
4399	arc_state_t *state = hdr->b_l1hdr.b_state;
4400	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4401	ASSERT3P(state, !=, arc_anon);
4402
4403	/* this buffer is not on any list */
4404	ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) > 0);
4405
4406	if (HDR_HAS_L2HDR(hdr)) {
4407		mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4408
4409		/*
4410		 * We have to recheck this conditional again now that
4411		 * we're holding the l2ad_mtx to prevent a race with
4412		 * another thread which might be concurrently calling
4413		 * l2arc_evict(). In that case, l2arc_evict() might have
4414		 * destroyed the header's L2 portion as we were waiting
4415		 * to acquire the l2ad_mtx.
4416		 */
4417		if (HDR_HAS_L2HDR(hdr)) {
4418			if (hdr->b_l2hdr.b_daddr != L2ARC_ADDR_UNSET)
4419				trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
4420				    hdr->b_l2hdr.b_daddr,
4421				    hdr->b_l2hdr.b_asize, 0);
4422			arc_hdr_l2hdr_destroy(hdr);
4423		}
4424
4425		mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
4426	}
4427
4428	/*
4429	 * Do we have more than one buf?
4430	 */
4431	if (hdr->b_l1hdr.b_datacnt > 1) {
4432		arc_buf_hdr_t *nhdr;
4433		arc_buf_t **bufp;
4434		uint64_t blksz = hdr->b_size;
4435		uint64_t spa = hdr->b_spa;
4436		arc_buf_contents_t type = arc_buf_type(hdr);
4437		uint32_t flags = hdr->b_flags;
4438
4439		ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
4440		/*
4441		 * Pull the data off of this hdr and attach it to
4442		 * a new anonymous hdr.
4443		 */
4444		(void) remove_reference(hdr, hash_lock, tag);
4445		bufp = &hdr->b_l1hdr.b_buf;
4446		while (*bufp != buf)
4447			bufp = &(*bufp)->b_next;
4448		*bufp = buf->b_next;
4449		buf->b_next = NULL;
4450
4451		ASSERT3P(state, !=, arc_l2c_only);
4452		ASSERT3U(state->arcs_size, >=, hdr->b_size);
4453		atomic_add_64(&state->arcs_size, -hdr->b_size);
4454		if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
4455			ASSERT3P(state, !=, arc_l2c_only);
4456			uint64_t *size = &state->arcs_lsize[type];
4457			ASSERT3U(*size, >=, hdr->b_size);
4458			atomic_add_64(size, -hdr->b_size);
4459		}
4460
4461		/*
4462		 * We're releasing a duplicate user data buffer, update
4463		 * our statistics accordingly.
4464		 */
4465		if (HDR_ISTYPE_DATA(hdr)) {
4466			ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
4467			ARCSTAT_INCR(arcstat_duplicate_buffers_size,
4468			    -hdr->b_size);
4469		}
4470		hdr->b_l1hdr.b_datacnt -= 1;
4471		arc_cksum_verify(buf);
4472#ifdef illumos
4473		arc_buf_unwatch(buf);
4474#endif
4475
4476		mutex_exit(hash_lock);
4477
4478		nhdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
4479		nhdr->b_size = blksz;
4480		nhdr->b_spa = spa;
4481
4482		nhdr->b_flags = flags & ARC_FLAG_L2_WRITING;
4483		nhdr->b_flags |= arc_bufc_to_flags(type);
4484		nhdr->b_flags |= ARC_FLAG_HAS_L1HDR;
4485
4486		nhdr->b_l1hdr.b_buf = buf;
4487		nhdr->b_l1hdr.b_datacnt = 1;
4488		nhdr->b_l1hdr.b_state = arc_anon;
4489		nhdr->b_l1hdr.b_arc_access = 0;
4490		nhdr->b_freeze_cksum = NULL;
4491
4492		(void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
4493		buf->b_hdr = nhdr;
4494		mutex_exit(&buf->b_evict_lock);
4495		atomic_add_64(&arc_anon->arcs_size, blksz);
4496	} else {
4497		mutex_exit(&buf->b_evict_lock);
4498		ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
4499		/* protected by hash lock */
4500		ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
4501		ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4502		arc_change_state(arc_anon, hdr, hash_lock);
4503		hdr->b_l1hdr.b_arc_access = 0;
4504		mutex_exit(hash_lock);
4505
4506		buf_discard_identity(hdr);
4507		arc_buf_thaw(buf);
4508	}
4509	buf->b_efunc = NULL;
4510	buf->b_private = NULL;
4511}
4512
4513int
4514arc_released(arc_buf_t *buf)
4515{
4516	int released;
4517
4518	mutex_enter(&buf->b_evict_lock);
4519	released = (buf->b_data != NULL &&
4520	    buf->b_hdr->b_l1hdr.b_state == arc_anon);
4521	mutex_exit(&buf->b_evict_lock);
4522	return (released);
4523}
4524
4525#ifdef ZFS_DEBUG
4526int
4527arc_referenced(arc_buf_t *buf)
4528{
4529	int referenced;
4530
4531	mutex_enter(&buf->b_evict_lock);
4532	referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
4533	mutex_exit(&buf->b_evict_lock);
4534	return (referenced);
4535}
4536#endif
4537
4538static void
4539arc_write_ready(zio_t *zio)
4540{
4541	arc_write_callback_t *callback = zio->io_private;
4542	arc_buf_t *buf = callback->awcb_buf;
4543	arc_buf_hdr_t *hdr = buf->b_hdr;
4544
4545	ASSERT(HDR_HAS_L1HDR(hdr));
4546	ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
4547	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4548	callback->awcb_ready(zio, buf, callback->awcb_private);
4549
4550	/*
4551	 * If the IO is already in progress, then this is a re-write
4552	 * attempt, so we need to thaw and re-compute the cksum.
4553	 * It is the responsibility of the callback to handle the
4554	 * accounting for any re-write attempt.
4555	 */
4556	if (HDR_IO_IN_PROGRESS(hdr)) {
4557		mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
4558		if (hdr->b_freeze_cksum != NULL) {
4559			kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
4560			hdr->b_freeze_cksum = NULL;
4561		}
4562		mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
4563	}
4564	arc_cksum_compute(buf, B_FALSE);
4565	hdr->b_flags |= ARC_FLAG_IO_IN_PROGRESS;
4566}
4567
4568/*
4569 * The SPA calls this callback for each physical write that happens on behalf
4570 * of a logical write.  See the comment in dbuf_write_physdone() for details.
4571 */
4572static void
4573arc_write_physdone(zio_t *zio)
4574{
4575	arc_write_callback_t *cb = zio->io_private;
4576	if (cb->awcb_physdone != NULL)
4577		cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
4578}
4579
4580static void
4581arc_write_done(zio_t *zio)
4582{
4583	arc_write_callback_t *callback = zio->io_private;
4584	arc_buf_t *buf = callback->awcb_buf;
4585	arc_buf_hdr_t *hdr = buf->b_hdr;
4586
4587	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4588
4589	if (zio->io_error == 0) {
4590		if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
4591			buf_discard_identity(hdr);
4592		} else {
4593			hdr->b_dva = *BP_IDENTITY(zio->io_bp);
4594			hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
4595		}
4596	} else {
4597		ASSERT(BUF_EMPTY(hdr));
4598	}
4599
4600	/*
4601	 * If the block to be written was all-zero or compressed enough to be
4602	 * embedded in the BP, no write was performed so there will be no
4603	 * dva/birth/checksum.  The buffer must therefore remain anonymous
4604	 * (and uncached).
4605	 */
4606	if (!BUF_EMPTY(hdr)) {
4607		arc_buf_hdr_t *exists;
4608		kmutex_t *hash_lock;
4609
4610		ASSERT(zio->io_error == 0);
4611
4612		arc_cksum_verify(buf);
4613
4614		exists = buf_hash_insert(hdr, &hash_lock);
4615		if (exists != NULL) {
4616			/*
4617			 * This can only happen if we overwrite for
4618			 * sync-to-convergence, because we remove
4619			 * buffers from the hash table when we arc_free().
4620			 */
4621			if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
4622				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4623					panic("bad overwrite, hdr=%p exists=%p",
4624					    (void *)hdr, (void *)exists);
4625				ASSERT(refcount_is_zero(
4626				    &exists->b_l1hdr.b_refcnt));
4627				arc_change_state(arc_anon, exists, hash_lock);
4628				mutex_exit(hash_lock);
4629				arc_hdr_destroy(exists);
4630				exists = buf_hash_insert(hdr, &hash_lock);
4631				ASSERT3P(exists, ==, NULL);
4632			} else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
4633				/* nopwrite */
4634				ASSERT(zio->io_prop.zp_nopwrite);
4635				if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
4636					panic("bad nopwrite, hdr=%p exists=%p",
4637					    (void *)hdr, (void *)exists);
4638			} else {
4639				/* Dedup */
4640				ASSERT(hdr->b_l1hdr.b_datacnt == 1);
4641				ASSERT(hdr->b_l1hdr.b_state == arc_anon);
4642				ASSERT(BP_GET_DEDUP(zio->io_bp));
4643				ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
4644			}
4645		}
4646		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4647		/* if it's not anon, we are doing a scrub */
4648		if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
4649			arc_access(hdr, hash_lock);
4650		mutex_exit(hash_lock);
4651	} else {
4652		hdr->b_flags &= ~ARC_FLAG_IO_IN_PROGRESS;
4653	}
4654
4655	ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
4656	callback->awcb_done(zio, buf, callback->awcb_private);
4657
4658	kmem_free(callback, sizeof (arc_write_callback_t));
4659}
4660
4661zio_t *
4662arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
4663    blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
4664    const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
4665    arc_done_func_t *done, void *private, zio_priority_t priority,
4666    int zio_flags, const zbookmark_phys_t *zb)
4667{
4668	arc_buf_hdr_t *hdr = buf->b_hdr;
4669	arc_write_callback_t *callback;
4670	zio_t *zio;
4671
4672	ASSERT(ready != NULL);
4673	ASSERT(done != NULL);
4674	ASSERT(!HDR_IO_ERROR(hdr));
4675	ASSERT(!HDR_IO_IN_PROGRESS(hdr));
4676	ASSERT(hdr->b_l1hdr.b_acb == NULL);
4677	ASSERT(hdr->b_l1hdr.b_datacnt > 0);
4678	if (l2arc)
4679		hdr->b_flags |= ARC_FLAG_L2CACHE;
4680	if (l2arc_compress)
4681		hdr->b_flags |= ARC_FLAG_L2COMPRESS;
4682	callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
4683	callback->awcb_ready = ready;
4684	callback->awcb_physdone = physdone;
4685	callback->awcb_done = done;
4686	callback->awcb_private = private;
4687	callback->awcb_buf = buf;
4688
4689	zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
4690	    arc_write_ready, arc_write_physdone, arc_write_done, callback,
4691	    priority, zio_flags, zb);
4692
4693	return (zio);
4694}
4695
4696static int
4697arc_memory_throttle(uint64_t reserve, uint64_t txg)
4698{
4699#ifdef _KERNEL
4700	uint64_t available_memory = ptob(freemem);
4701	static uint64_t page_load = 0;
4702	static uint64_t last_txg = 0;
4703
4704#if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4705	available_memory =
4706	    MIN(available_memory, ptob(vmem_size(heap_arena, VMEM_FREE)));
4707#endif
4708
4709	if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
4710		return (0);
4711
4712	if (txg > last_txg) {
4713		last_txg = txg;
4714		page_load = 0;
4715	}
4716	/*
4717	 * If we are in pageout, we know that memory is already tight,
4718	 * the arc is already going to be evicting, so we just want to
4719	 * continue to let page writes occur as quickly as possible.
4720	 */
4721	if (curproc == pageproc) {
4722		if (page_load > MAX(ptob(minfree), available_memory) / 4)
4723			return (SET_ERROR(ERESTART));
4724		/* Note: reserve is inflated, so we deflate */
4725		page_load += reserve / 8;
4726		return (0);
4727	} else if (page_load > 0 && arc_reclaim_needed()) {
4728		/* memory is low, delay before restarting */
4729		ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
4730		return (SET_ERROR(EAGAIN));
4731	}
4732	page_load = 0;
4733#endif
4734	return (0);
4735}
4736
4737void
4738arc_tempreserve_clear(uint64_t reserve)
4739{
4740	atomic_add_64(&arc_tempreserve, -reserve);
4741	ASSERT((int64_t)arc_tempreserve >= 0);
4742}
4743
4744int
4745arc_tempreserve_space(uint64_t reserve, uint64_t txg)
4746{
4747	int error;
4748	uint64_t anon_size;
4749
4750	if (reserve > arc_c/4 && !arc_no_grow) {
4751		arc_c = MIN(arc_c_max, reserve * 4);
4752		DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
4753	}
4754	if (reserve > arc_c)
4755		return (SET_ERROR(ENOMEM));
4756
4757	/*
4758	 * Don't count loaned bufs as in flight dirty data to prevent long
4759	 * network delays from blocking transactions that are ready to be
4760	 * assigned to a txg.
4761	 */
4762	anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
4763
4764	/*
4765	 * Writes will, almost always, require additional memory allocations
4766	 * in order to compress/encrypt/etc the data.  We therefore need to
4767	 * make sure that there is sufficient available memory for this.
4768	 */
4769	error = arc_memory_throttle(reserve, txg);
4770	if (error != 0)
4771		return (error);
4772
4773	/*
4774	 * Throttle writes when the amount of dirty data in the cache
4775	 * gets too large.  We try to keep the cache less than half full
4776	 * of dirty blocks so that our sync times don't grow too large.
4777	 * Note: if two requests come in concurrently, we might let them
4778	 * both succeed, when one of them should fail.  Not a huge deal.
4779	 */
4780
4781	if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
4782	    anon_size > arc_c / 4) {
4783		dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
4784		    "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
4785		    arc_tempreserve>>10,
4786		    arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
4787		    arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
4788		    reserve>>10, arc_c>>10);
4789		return (SET_ERROR(ERESTART));
4790	}
4791	atomic_add_64(&arc_tempreserve, reserve);
4792	return (0);
4793}
4794
4795static void
4796arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
4797    kstat_named_t *evict_data, kstat_named_t *evict_metadata)
4798{
4799	size->value.ui64 = state->arcs_size;
4800	evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
4801	evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
4802}
4803
4804static int
4805arc_kstat_update(kstat_t *ksp, int rw)
4806{
4807	arc_stats_t *as = ksp->ks_data;
4808
4809	if (rw == KSTAT_WRITE) {
4810		return (EACCES);
4811	} else {
4812		arc_kstat_update_state(arc_anon,
4813		    &as->arcstat_anon_size,
4814		    &as->arcstat_anon_evictable_data,
4815		    &as->arcstat_anon_evictable_metadata);
4816		arc_kstat_update_state(arc_mru,
4817		    &as->arcstat_mru_size,
4818		    &as->arcstat_mru_evictable_data,
4819		    &as->arcstat_mru_evictable_metadata);
4820		arc_kstat_update_state(arc_mru_ghost,
4821		    &as->arcstat_mru_ghost_size,
4822		    &as->arcstat_mru_ghost_evictable_data,
4823		    &as->arcstat_mru_ghost_evictable_metadata);
4824		arc_kstat_update_state(arc_mfu,
4825		    &as->arcstat_mfu_size,
4826		    &as->arcstat_mfu_evictable_data,
4827		    &as->arcstat_mfu_evictable_metadata);
4828		arc_kstat_update_state(arc_mfu_ghost,
4829		    &as->arcstat_mfu_ghost_size,
4830		    &as->arcstat_mfu_ghost_evictable_data,
4831		    &as->arcstat_mfu_ghost_evictable_metadata);
4832	}
4833
4834	return (0);
4835}
4836
4837#ifdef _KERNEL
4838static eventhandler_tag arc_event_lowmem = NULL;
4839
4840static void
4841arc_lowmem(void *arg __unused, int howto __unused)
4842{
4843
4844	mutex_enter(&arc_reclaim_thr_lock);
4845	/* XXX: Memory deficit should be passed as argument. */
4846	needfree = btoc(arc_c >> arc_shrink_shift);
4847	DTRACE_PROBE(arc__needfree);
4848	cv_signal(&arc_reclaim_thr_cv);
4849
4850	/*
4851	 * It is unsafe to block here in arbitrary threads, because we can come
4852	 * here from ARC itself and may hold ARC locks and thus risk a deadlock
4853	 * with ARC reclaim thread.
4854	 */
4855	if (curproc == pageproc)
4856		msleep(&needfree, &arc_reclaim_thr_lock, 0, "zfs:lowmem", 0);
4857	mutex_exit(&arc_reclaim_thr_lock);
4858}
4859#endif
4860
4861void
4862arc_init(void)
4863{
4864	int i, prefetch_tunable_set = 0;
4865
4866	mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4867	cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4868
4869	/* Convert seconds to clock ticks */
4870	arc_min_prefetch_lifespan = 1 * hz;
4871
4872	/* Start out with 1/8 of all memory */
4873	arc_c = kmem_size() / 8;
4874
4875#ifdef illumos
4876#ifdef _KERNEL
4877	/*
4878	 * On architectures where the physical memory can be larger
4879	 * than the addressable space (intel in 32-bit mode), we may
4880	 * need to limit the cache to 1/8 of VM size.
4881	 */
4882	arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4883#endif
4884#endif	/* illumos */
4885	/* set min cache to 1/32 of all memory, or 16MB, whichever is more */
4886	arc_c_min = MAX(arc_c / 4, 16 << 20);
4887	/* set max to 1/2 of all memory, or all but 1GB, whichever is more */
4888	if (arc_c * 8 >= 1 << 30)
4889		arc_c_max = (arc_c * 8) - (1 << 30);
4890	else
4891		arc_c_max = arc_c_min;
4892	arc_c_max = MAX(arc_c * 5, arc_c_max);
4893
4894#ifdef _KERNEL
4895	/*
4896	 * Allow the tunables to override our calculations if they are
4897	 * reasonable (ie. over 16MB)
4898	 */
4899	if (zfs_arc_max > 16 << 20 && zfs_arc_max < kmem_size())
4900		arc_c_max = zfs_arc_max;
4901	if (zfs_arc_min > 16 << 20 && zfs_arc_min <= arc_c_max)
4902		arc_c_min = zfs_arc_min;
4903#endif
4904
4905	arc_c = arc_c_max;
4906	arc_p = (arc_c >> 1);
4907
4908	/* limit meta-data to 1/4 of the arc capacity */
4909	arc_meta_limit = arc_c_max / 4;
4910
4911	/* Allow the tunable to override if it is reasonable */
4912	if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4913		arc_meta_limit = zfs_arc_meta_limit;
4914
4915	if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4916		arc_c_min = arc_meta_limit / 2;
4917
4918	if (zfs_arc_meta_min > 0) {
4919		arc_meta_min = zfs_arc_meta_min;
4920	} else {
4921		arc_meta_min = arc_c_min / 2;
4922	}
4923
4924	if (zfs_arc_grow_retry > 0)
4925		arc_grow_retry = zfs_arc_grow_retry;
4926
4927	if (zfs_arc_shrink_shift > 0)
4928		arc_shrink_shift = zfs_arc_shrink_shift;
4929
4930	/*
4931	 * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
4932	 */
4933	if (arc_no_grow_shift >= arc_shrink_shift)
4934		arc_no_grow_shift = arc_shrink_shift - 1;
4935
4936	if (zfs_arc_p_min_shift > 0)
4937		arc_p_min_shift = zfs_arc_p_min_shift;
4938
4939	/* if kmem_flags are set, lets try to use less memory */
4940	if (kmem_debugging())
4941		arc_c = arc_c / 2;
4942	if (arc_c < arc_c_min)
4943		arc_c = arc_c_min;
4944
4945	zfs_arc_min = arc_c_min;
4946	zfs_arc_max = arc_c_max;
4947
4948	arc_anon = &ARC_anon;
4949	arc_mru = &ARC_mru;
4950	arc_mru_ghost = &ARC_mru_ghost;
4951	arc_mfu = &ARC_mfu;
4952	arc_mfu_ghost = &ARC_mfu_ghost;
4953	arc_l2c_only = &ARC_l2c_only;
4954	arc_size = 0;
4955
4956	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
4957		mutex_init(&arc_anon->arcs_locks[i].arcs_lock,
4958		    NULL, MUTEX_DEFAULT, NULL);
4959		mutex_init(&arc_mru->arcs_locks[i].arcs_lock,
4960		    NULL, MUTEX_DEFAULT, NULL);
4961		mutex_init(&arc_mru_ghost->arcs_locks[i].arcs_lock,
4962		    NULL, MUTEX_DEFAULT, NULL);
4963		mutex_init(&arc_mfu->arcs_locks[i].arcs_lock,
4964		    NULL, MUTEX_DEFAULT, NULL);
4965		mutex_init(&arc_mfu_ghost->arcs_locks[i].arcs_lock,
4966		    NULL, MUTEX_DEFAULT, NULL);
4967		mutex_init(&arc_l2c_only->arcs_locks[i].arcs_lock,
4968		    NULL, MUTEX_DEFAULT, NULL);
4969
4970		list_create(&arc_mru->arcs_lists[i],
4971		    sizeof (arc_buf_hdr_t),
4972		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4973		list_create(&arc_mru_ghost->arcs_lists[i],
4974		    sizeof (arc_buf_hdr_t),
4975		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4976		list_create(&arc_mfu->arcs_lists[i],
4977		    sizeof (arc_buf_hdr_t),
4978		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4979		list_create(&arc_mfu_ghost->arcs_lists[i],
4980		    sizeof (arc_buf_hdr_t),
4981		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4982		list_create(&arc_mfu_ghost->arcs_lists[i],
4983		    sizeof (arc_buf_hdr_t),
4984		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4985		list_create(&arc_l2c_only->arcs_lists[i],
4986		    sizeof (arc_buf_hdr_t),
4987		    offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node));
4988	}
4989
4990	buf_init();
4991
4992	arc_thread_exit = 0;
4993	arc_eviction_list = NULL;
4994	mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4995	bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4996
4997	arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4998	    sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4999
5000	if (arc_ksp != NULL) {
5001		arc_ksp->ks_data = &arc_stats;
5002		arc_ksp->ks_update = arc_kstat_update;
5003		kstat_install(arc_ksp);
5004	}
5005
5006	(void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
5007	    TS_RUN, minclsyspri);
5008
5009#ifdef _KERNEL
5010	arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
5011	    EVENTHANDLER_PRI_FIRST);
5012#endif
5013
5014	arc_dead = FALSE;
5015	arc_warm = B_FALSE;
5016
5017	/*
5018	 * Calculate maximum amount of dirty data per pool.
5019	 *
5020	 * If it has been set by /etc/system, take that.
5021	 * Otherwise, use a percentage of physical memory defined by
5022	 * zfs_dirty_data_max_percent (default 10%) with a cap at
5023	 * zfs_dirty_data_max_max (default 4GB).
5024	 */
5025	if (zfs_dirty_data_max == 0) {
5026		zfs_dirty_data_max = ptob(physmem) *
5027		    zfs_dirty_data_max_percent / 100;
5028		zfs_dirty_data_max = MIN(zfs_dirty_data_max,
5029		    zfs_dirty_data_max_max);
5030	}
5031
5032#ifdef _KERNEL
5033	if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
5034		prefetch_tunable_set = 1;
5035
5036#ifdef __i386__
5037	if (prefetch_tunable_set == 0) {
5038		printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
5039		    "-- to enable,\n");
5040		printf("            add \"vfs.zfs.prefetch_disable=0\" "
5041		    "to /boot/loader.conf.\n");
5042		zfs_prefetch_disable = 1;
5043	}
5044#else
5045	if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
5046	    prefetch_tunable_set == 0) {
5047		printf("ZFS NOTICE: Prefetch is disabled by default if less "
5048		    "than 4GB of RAM is present;\n"
5049		    "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
5050		    "to /boot/loader.conf.\n");
5051		zfs_prefetch_disable = 1;
5052	}
5053#endif
5054	/* Warn about ZFS memory and address space requirements. */
5055	if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
5056		printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
5057		    "expect unstable behavior.\n");
5058	}
5059	if (kmem_size() < 512 * (1 << 20)) {
5060		printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
5061		    "expect unstable behavior.\n");
5062		printf("             Consider tuning vm.kmem_size and "
5063		    "vm.kmem_size_max\n");
5064		printf("             in /boot/loader.conf.\n");
5065	}
5066#endif
5067}
5068
5069void
5070arc_fini(void)
5071{
5072	int i;
5073
5074	mutex_enter(&arc_reclaim_thr_lock);
5075	arc_thread_exit = 1;
5076	cv_signal(&arc_reclaim_thr_cv);
5077	while (arc_thread_exit != 0)
5078		cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
5079	mutex_exit(&arc_reclaim_thr_lock);
5080
5081	arc_flush(NULL);
5082
5083	arc_dead = TRUE;
5084
5085	if (arc_ksp != NULL) {
5086		kstat_delete(arc_ksp);
5087		arc_ksp = NULL;
5088	}
5089
5090	mutex_destroy(&arc_eviction_mtx);
5091	mutex_destroy(&arc_reclaim_thr_lock);
5092	cv_destroy(&arc_reclaim_thr_cv);
5093
5094	for (i = 0; i < ARC_BUFC_NUMLISTS; i++) {
5095		list_destroy(&arc_mru->arcs_lists[i]);
5096		list_destroy(&arc_mru_ghost->arcs_lists[i]);
5097		list_destroy(&arc_mfu->arcs_lists[i]);
5098		list_destroy(&arc_mfu_ghost->arcs_lists[i]);
5099		list_destroy(&arc_l2c_only->arcs_lists[i]);
5100
5101		mutex_destroy(&arc_anon->arcs_locks[i].arcs_lock);
5102		mutex_destroy(&arc_mru->arcs_locks[i].arcs_lock);
5103		mutex_destroy(&arc_mru_ghost->arcs_locks[i].arcs_lock);
5104		mutex_destroy(&arc_mfu->arcs_locks[i].arcs_lock);
5105		mutex_destroy(&arc_mfu_ghost->arcs_locks[i].arcs_lock);
5106		mutex_destroy(&arc_l2c_only->arcs_locks[i].arcs_lock);
5107	}
5108
5109	buf_fini();
5110
5111	ASSERT0(arc_loaned_bytes);
5112
5113#ifdef _KERNEL
5114	if (arc_event_lowmem != NULL)
5115		EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
5116#endif
5117}
5118
5119/*
5120 * Level 2 ARC
5121 *
5122 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
5123 * It uses dedicated storage devices to hold cached data, which are populated
5124 * using large infrequent writes.  The main role of this cache is to boost
5125 * the performance of random read workloads.  The intended L2ARC devices
5126 * include short-stroked disks, solid state disks, and other media with
5127 * substantially faster read latency than disk.
5128 *
5129 *                 +-----------------------+
5130 *                 |         ARC           |
5131 *                 +-----------------------+
5132 *                    |         ^     ^
5133 *                    |         |     |
5134 *      l2arc_feed_thread()    arc_read()
5135 *                    |         |     |
5136 *                    |  l2arc read   |
5137 *                    V         |     |
5138 *               +---------------+    |
5139 *               |     L2ARC     |    |
5140 *               +---------------+    |
5141 *                   |    ^           |
5142 *          l2arc_write() |           |
5143 *                   |    |           |
5144 *                   V    |           |
5145 *                 +-------+      +-------+
5146 *                 | vdev  |      | vdev  |
5147 *                 | cache |      | cache |
5148 *                 +-------+      +-------+
5149 *                 +=========+     .-----.
5150 *                 :  L2ARC  :    |-_____-|
5151 *                 : devices :    | Disks |
5152 *                 +=========+    `-_____-'
5153 *
5154 * Read requests are satisfied from the following sources, in order:
5155 *
5156 *	1) ARC
5157 *	2) vdev cache of L2ARC devices
5158 *	3) L2ARC devices
5159 *	4) vdev cache of disks
5160 *	5) disks
5161 *
5162 * Some L2ARC device types exhibit extremely slow write performance.
5163 * To accommodate for this there are some significant differences between
5164 * the L2ARC and traditional cache design:
5165 *
5166 * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
5167 * the ARC behave as usual, freeing buffers and placing headers on ghost
5168 * lists.  The ARC does not send buffers to the L2ARC during eviction as
5169 * this would add inflated write latencies for all ARC memory pressure.
5170 *
5171 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
5172 * It does this by periodically scanning buffers from the eviction-end of
5173 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
5174 * not already there. It scans until a headroom of buffers is satisfied,
5175 * which itself is a buffer for ARC eviction. If a compressible buffer is
5176 * found during scanning and selected for writing to an L2ARC device, we
5177 * temporarily boost scanning headroom during the next scan cycle to make
5178 * sure we adapt to compression effects (which might significantly reduce
5179 * the data volume we write to L2ARC). The thread that does this is
5180 * l2arc_feed_thread(), illustrated below; example sizes are included to
5181 * provide a better sense of ratio than this diagram:
5182 *
5183 *	       head -->                        tail
5184 *	        +---------------------+----------+
5185 *	ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
5186 *	        +---------------------+----------+   |   o L2ARC eligible
5187 *	ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
5188 *	        +---------------------+----------+   |
5189 *	             15.9 Gbytes      ^ 32 Mbytes    |
5190 *	                           headroom          |
5191 *	                                      l2arc_feed_thread()
5192 *	                                             |
5193 *	                 l2arc write hand <--[oooo]--'
5194 *	                         |           8 Mbyte
5195 *	                         |          write max
5196 *	                         V
5197 *		  +==============================+
5198 *	L2ARC dev |####|#|###|###|    |####| ... |
5199 *	          +==============================+
5200 *	                     32 Gbytes
5201 *
5202 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
5203 * evicted, then the L2ARC has cached a buffer much sooner than it probably
5204 * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
5205 * safe to say that this is an uncommon case, since buffers at the end of
5206 * the ARC lists have moved there due to inactivity.
5207 *
5208 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
5209 * then the L2ARC simply misses copying some buffers.  This serves as a
5210 * pressure valve to prevent heavy read workloads from both stalling the ARC
5211 * with waits and clogging the L2ARC with writes.  This also helps prevent
5212 * the potential for the L2ARC to churn if it attempts to cache content too
5213 * quickly, such as during backups of the entire pool.
5214 *
5215 * 5. After system boot and before the ARC has filled main memory, there are
5216 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
5217 * lists can remain mostly static.  Instead of searching from tail of these
5218 * lists as pictured, the l2arc_feed_thread() will search from the list heads
5219 * for eligible buffers, greatly increasing its chance of finding them.
5220 *
5221 * The L2ARC device write speed is also boosted during this time so that
5222 * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
5223 * there are no L2ARC reads, and no fear of degrading read performance
5224 * through increased writes.
5225 *
5226 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
5227 * the vdev queue can aggregate them into larger and fewer writes.  Each
5228 * device is written to in a rotor fashion, sweeping writes through
5229 * available space then repeating.
5230 *
5231 * 7. The L2ARC does not store dirty content.  It never needs to flush
5232 * write buffers back to disk based storage.
5233 *
5234 * 8. If an ARC buffer is written (and dirtied) which also exists in the
5235 * L2ARC, the now stale L2ARC buffer is immediately dropped.
5236 *
5237 * The performance of the L2ARC can be tweaked by a number of tunables, which
5238 * may be necessary for different workloads:
5239 *
5240 *	l2arc_write_max		max write bytes per interval
5241 *	l2arc_write_boost	extra write bytes during device warmup
5242 *	l2arc_noprefetch	skip caching prefetched buffers
5243 *	l2arc_headroom		number of max device writes to precache
5244 *	l2arc_headroom_boost	when we find compressed buffers during ARC
5245 *				scanning, we multiply headroom by this
5246 *				percentage factor for the next scan cycle,
5247 *				since more compressed buffers are likely to
5248 *				be present
5249 *	l2arc_feed_secs		seconds between L2ARC writing
5250 *
5251 * Tunables may be removed or added as future performance improvements are
5252 * integrated, and also may become zpool properties.
5253 *
5254 * There are three key functions that control how the L2ARC warms up:
5255 *
5256 *	l2arc_write_eligible()	check if a buffer is eligible to cache
5257 *	l2arc_write_size()	calculate how much to write
5258 *	l2arc_write_interval()	calculate sleep delay between writes
5259 *
5260 * These three functions determine what to write, how much, and how quickly
5261 * to send writes.
5262 */
5263
5264static boolean_t
5265l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
5266{
5267	/*
5268	 * A buffer is *not* eligible for the L2ARC if it:
5269	 * 1. belongs to a different spa.
5270	 * 2. is already cached on the L2ARC.
5271	 * 3. has an I/O in progress (it may be an incomplete read).
5272	 * 4. is flagged not eligible (zfs property).
5273	 */
5274	if (hdr->b_spa != spa_guid) {
5275		ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
5276		return (B_FALSE);
5277	}
5278	if (HDR_HAS_L2HDR(hdr)) {
5279		ARCSTAT_BUMP(arcstat_l2_write_in_l2);
5280		return (B_FALSE);
5281	}
5282	if (HDR_IO_IN_PROGRESS(hdr)) {
5283		ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
5284		return (B_FALSE);
5285	}
5286	if (!HDR_L2CACHE(hdr)) {
5287		ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
5288		return (B_FALSE);
5289	}
5290
5291	return (B_TRUE);
5292}
5293
5294static uint64_t
5295l2arc_write_size(void)
5296{
5297	uint64_t size;
5298
5299	/*
5300	 * Make sure our globals have meaningful values in case the user
5301	 * altered them.
5302	 */
5303	size = l2arc_write_max;
5304	if (size == 0) {
5305		cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
5306		    "be greater than zero, resetting it to the default (%d)",
5307		    L2ARC_WRITE_SIZE);
5308		size = l2arc_write_max = L2ARC_WRITE_SIZE;
5309	}
5310
5311	if (arc_warm == B_FALSE)
5312		size += l2arc_write_boost;
5313
5314	return (size);
5315
5316}
5317
5318static clock_t
5319l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
5320{
5321	clock_t interval, next, now;
5322
5323	/*
5324	 * If the ARC lists are busy, increase our write rate; if the
5325	 * lists are stale, idle back.  This is achieved by checking
5326	 * how much we previously wrote - if it was more than half of
5327	 * what we wanted, schedule the next write much sooner.
5328	 */
5329	if (l2arc_feed_again && wrote > (wanted / 2))
5330		interval = (hz * l2arc_feed_min_ms) / 1000;
5331	else
5332		interval = hz * l2arc_feed_secs;
5333
5334	now = ddi_get_lbolt();
5335	next = MAX(now, MIN(now + interval, began + interval));
5336
5337	return (next);
5338}
5339
5340/*
5341 * Cycle through L2ARC devices.  This is how L2ARC load balances.
5342 * If a device is returned, this also returns holding the spa config lock.
5343 */
5344static l2arc_dev_t *
5345l2arc_dev_get_next(void)
5346{
5347	l2arc_dev_t *first, *next = NULL;
5348
5349	/*
5350	 * Lock out the removal of spas (spa_namespace_lock), then removal
5351	 * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
5352	 * both locks will be dropped and a spa config lock held instead.
5353	 */
5354	mutex_enter(&spa_namespace_lock);
5355	mutex_enter(&l2arc_dev_mtx);
5356
5357	/* if there are no vdevs, there is nothing to do */
5358	if (l2arc_ndev == 0)
5359		goto out;
5360
5361	first = NULL;
5362	next = l2arc_dev_last;
5363	do {
5364		/* loop around the list looking for a non-faulted vdev */
5365		if (next == NULL) {
5366			next = list_head(l2arc_dev_list);
5367		} else {
5368			next = list_next(l2arc_dev_list, next);
5369			if (next == NULL)
5370				next = list_head(l2arc_dev_list);
5371		}
5372
5373		/* if we have come back to the start, bail out */
5374		if (first == NULL)
5375			first = next;
5376		else if (next == first)
5377			break;
5378
5379	} while (vdev_is_dead(next->l2ad_vdev));
5380
5381	/* if we were unable to find any usable vdevs, return NULL */
5382	if (vdev_is_dead(next->l2ad_vdev))
5383		next = NULL;
5384
5385	l2arc_dev_last = next;
5386
5387out:
5388	mutex_exit(&l2arc_dev_mtx);
5389
5390	/*
5391	 * Grab the config lock to prevent the 'next' device from being
5392	 * removed while we are writing to it.
5393	 */
5394	if (next != NULL)
5395		spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
5396	mutex_exit(&spa_namespace_lock);
5397
5398	return (next);
5399}
5400
5401/*
5402 * Free buffers that were tagged for destruction.
5403 */
5404static void
5405l2arc_do_free_on_write()
5406{
5407	list_t *buflist;
5408	l2arc_data_free_t *df, *df_prev;
5409
5410	mutex_enter(&l2arc_free_on_write_mtx);
5411	buflist = l2arc_free_on_write;
5412
5413	for (df = list_tail(buflist); df; df = df_prev) {
5414		df_prev = list_prev(buflist, df);
5415		ASSERT(df->l2df_data != NULL);
5416		ASSERT(df->l2df_func != NULL);
5417		df->l2df_func(df->l2df_data, df->l2df_size);
5418		list_remove(buflist, df);
5419		kmem_free(df, sizeof (l2arc_data_free_t));
5420	}
5421
5422	mutex_exit(&l2arc_free_on_write_mtx);
5423}
5424
5425/*
5426 * A write to a cache device has completed.  Update all headers to allow
5427 * reads from these buffers to begin.
5428 */
5429static void
5430l2arc_write_done(zio_t *zio)
5431{
5432	l2arc_write_callback_t *cb;
5433	l2arc_dev_t *dev;
5434	list_t *buflist;
5435	arc_buf_hdr_t *head, *hdr, *hdr_prev;
5436	kmutex_t *hash_lock;
5437	int64_t bytes_dropped = 0;
5438
5439	cb = zio->io_private;
5440	ASSERT(cb != NULL);
5441	dev = cb->l2wcb_dev;
5442	ASSERT(dev != NULL);
5443	head = cb->l2wcb_head;
5444	ASSERT(head != NULL);
5445	buflist = &dev->l2ad_buflist;
5446	ASSERT(buflist != NULL);
5447	DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
5448	    l2arc_write_callback_t *, cb);
5449
5450	if (zio->io_error != 0)
5451		ARCSTAT_BUMP(arcstat_l2_writes_error);
5452
5453	mutex_enter(&dev->l2ad_mtx);
5454
5455	/*
5456	 * All writes completed, or an error was hit.
5457	 */
5458	for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
5459		hdr_prev = list_prev(buflist, hdr);
5460
5461		hash_lock = HDR_LOCK(hdr);
5462		if (!mutex_tryenter(hash_lock)) {
5463			/*
5464			 * This buffer misses out.  It may be in a stage
5465			 * of eviction.  Its ARC_FLAG_L2_WRITING flag will be
5466			 * left set, denying reads to this buffer.
5467			 */
5468			ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
5469			continue;
5470		}
5471
5472		/*
5473		 * It's possible that this buffer got evicted from the L1 cache
5474		 * before we grabbed the vdev + hash locks, in which case
5475		 * arc_hdr_realloc freed b_tmp_cdata for us if it was allocated.
5476		 * Only free the buffer if we still have an L1 hdr.
5477		 */
5478		if (HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_tmp_cdata != NULL &&
5479		    HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
5480			l2arc_release_cdata_buf(hdr);
5481
5482		if (zio->io_error != 0) {
5483			/*
5484			 * Error - drop L2ARC entry.
5485			 */
5486			trim_map_free(hdr->b_l2hdr.b_dev->l2ad_vdev,
5487			    hdr->b_l2hdr.b_daddr, hdr->b_l2hdr.b_asize, 0);
5488			hdr->b_flags &= ~ARC_FLAG_HAS_L2HDR;
5489
5490			ARCSTAT_INCR(arcstat_l2_asize, -hdr->b_l2hdr.b_asize);
5491			ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
5492
5493			bytes_dropped += hdr->b_l2hdr.b_asize;
5494			(void) refcount_remove_many(&dev->l2ad_alloc,
5495			    hdr->b_l2hdr.b_asize, hdr);
5496		}
5497
5498		/*
5499		 * Allow ARC to begin reads to this L2ARC entry.
5500		 */
5501		hdr->b_flags &= ~ARC_FLAG_L2_WRITING;
5502
5503		mutex_exit(hash_lock);
5504	}
5505
5506	atomic_inc_64(&l2arc_writes_done);
5507	list_remove(buflist, head);
5508	ASSERT(!HDR_HAS_L1HDR(head));
5509	kmem_cache_free(hdr_l2only_cache, head);
5510	mutex_exit(&dev->l2ad_mtx);
5511
5512	vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
5513
5514	l2arc_do_free_on_write();
5515
5516	kmem_free(cb, sizeof (l2arc_write_callback_t));
5517}
5518
5519/*
5520 * A read to a cache device completed.  Validate buffer contents before
5521 * handing over to the regular ARC routines.
5522 */
5523static void
5524l2arc_read_done(zio_t *zio)
5525{
5526	l2arc_read_callback_t *cb;
5527	arc_buf_hdr_t *hdr;
5528	arc_buf_t *buf;
5529	kmutex_t *hash_lock;
5530	int equal;
5531
5532	ASSERT(zio->io_vd != NULL);
5533	ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
5534
5535	spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
5536
5537	cb = zio->io_private;
5538	ASSERT(cb != NULL);
5539	buf = cb->l2rcb_buf;
5540	ASSERT(buf != NULL);
5541
5542	hash_lock = HDR_LOCK(buf->b_hdr);
5543	mutex_enter(hash_lock);
5544	hdr = buf->b_hdr;
5545	ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
5546
5547	/*
5548	 * If the buffer was compressed, decompress it first.
5549	 */
5550	if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
5551		l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
5552	ASSERT(zio->io_data != NULL);
5553
5554	/*
5555	 * Check this survived the L2ARC journey.
5556	 */
5557	equal = arc_cksum_equal(buf);
5558	if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
5559		mutex_exit(hash_lock);
5560		zio->io_private = buf;
5561		zio->io_bp_copy = cb->l2rcb_bp;	/* XXX fix in L2ARC 2.0	*/
5562		zio->io_bp = &zio->io_bp_copy;	/* XXX fix in L2ARC 2.0	*/
5563		arc_read_done(zio);
5564	} else {
5565		mutex_exit(hash_lock);
5566		/*
5567		 * Buffer didn't survive caching.  Increment stats and
5568		 * reissue to the original storage device.
5569		 */
5570		if (zio->io_error != 0) {
5571			ARCSTAT_BUMP(arcstat_l2_io_error);
5572		} else {
5573			zio->io_error = SET_ERROR(EIO);
5574		}
5575		if (!equal)
5576			ARCSTAT_BUMP(arcstat_l2_cksum_bad);
5577
5578		/*
5579		 * If there's no waiter, issue an async i/o to the primary
5580		 * storage now.  If there *is* a waiter, the caller must
5581		 * issue the i/o in a context where it's OK to block.
5582		 */
5583		if (zio->io_waiter == NULL) {
5584			zio_t *pio = zio_unique_parent(zio);
5585
5586			ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
5587
5588			zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
5589			    buf->b_data, zio->io_size, arc_read_done, buf,
5590			    zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
5591		}
5592	}
5593
5594	kmem_free(cb, sizeof (l2arc_read_callback_t));
5595}
5596
5597/*
5598 * This is the list priority from which the L2ARC will search for pages to
5599 * cache.  This is used within loops (0..3) to cycle through lists in the
5600 * desired order.  This order can have a significant effect on cache
5601 * performance.
5602 *
5603 * Currently the metadata lists are hit first, MFU then MRU, followed by
5604 * the data lists.  This function returns a locked list, and also returns
5605 * the lock pointer.
5606 */
5607static list_t *
5608l2arc_list_locked(int list_num, kmutex_t **lock)
5609{
5610	list_t *list = NULL;
5611	int idx;
5612
5613	ASSERT(list_num >= 0 && list_num < 2 * ARC_BUFC_NUMLISTS);
5614
5615	if (list_num < ARC_BUFC_NUMMETADATALISTS) {
5616		idx = list_num;
5617		list = &arc_mfu->arcs_lists[idx];
5618		*lock = ARCS_LOCK(arc_mfu, idx);
5619	} else if (list_num < ARC_BUFC_NUMMETADATALISTS * 2) {
5620		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
5621		list = &arc_mru->arcs_lists[idx];
5622		*lock = ARCS_LOCK(arc_mru, idx);
5623	} else if (list_num < (ARC_BUFC_NUMMETADATALISTS * 2 +
5624		ARC_BUFC_NUMDATALISTS)) {
5625		idx = list_num - ARC_BUFC_NUMMETADATALISTS;
5626		list = &arc_mfu->arcs_lists[idx];
5627		*lock = ARCS_LOCK(arc_mfu, idx);
5628	} else {
5629		idx = list_num - ARC_BUFC_NUMLISTS;
5630		list = &arc_mru->arcs_lists[idx];
5631		*lock = ARCS_LOCK(arc_mru, idx);
5632	}
5633
5634	ASSERT(!(MUTEX_HELD(*lock)));
5635	mutex_enter(*lock);
5636	return (list);
5637}
5638
5639/*
5640 * Evict buffers from the device write hand to the distance specified in
5641 * bytes.  This distance may span populated buffers, it may span nothing.
5642 * This is clearing a region on the L2ARC device ready for writing.
5643 * If the 'all' boolean is set, every buffer is evicted.
5644 */
5645static void
5646l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
5647{
5648	list_t *buflist;
5649	arc_buf_hdr_t *hdr, *hdr_prev;
5650	kmutex_t *hash_lock;
5651	uint64_t taddr;
5652
5653	buflist = &dev->l2ad_buflist;
5654
5655	if (!all && dev->l2ad_first) {
5656		/*
5657		 * This is the first sweep through the device.  There is
5658		 * nothing to evict.
5659		 */
5660		return;
5661	}
5662
5663	if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
5664		/*
5665		 * When nearing the end of the device, evict to the end
5666		 * before the device write hand jumps to the start.
5667		 */
5668		taddr = dev->l2ad_end;
5669	} else {
5670		taddr = dev->l2ad_hand + distance;
5671	}
5672	DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
5673	    uint64_t, taddr, boolean_t, all);
5674
5675top:
5676	mutex_enter(&dev->l2ad_mtx);
5677	for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
5678		hdr_prev = list_prev(buflist, hdr);
5679
5680		hash_lock = HDR_LOCK(hdr);
5681		if (!mutex_tryenter(hash_lock)) {
5682			/*
5683			 * Missed the hash lock.  Retry.
5684			 */
5685			ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
5686			mutex_exit(&dev->l2ad_mtx);
5687			mutex_enter(hash_lock);
5688			mutex_exit(hash_lock);
5689			goto top;
5690		}
5691
5692		if (HDR_L2_WRITE_HEAD(hdr)) {
5693			/*
5694			 * We hit a write head node.  Leave it for
5695			 * l2arc_write_done().
5696			 */
5697			list_remove(buflist, hdr);
5698			mutex_exit(hash_lock);
5699			continue;
5700		}
5701
5702		if (!all && HDR_HAS_L2HDR(hdr) &&
5703		    (hdr->b_l2hdr.b_daddr > taddr ||
5704		    hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
5705			/*
5706			 * We've evicted to the target address,
5707			 * or the end of the device.
5708			 */
5709			mutex_exit(hash_lock);
5710			break;
5711		}
5712
5713		ASSERT(HDR_HAS_L2HDR(hdr));
5714		if (!HDR_HAS_L1HDR(hdr)) {
5715			ASSERT(!HDR_L2_READING(hdr));
5716			/*
5717			 * This doesn't exist in the ARC.  Destroy.
5718			 * arc_hdr_destroy() will call list_remove()
5719			 * and decrement arcstat_l2_size.
5720			 */
5721			arc_change_state(arc_anon, hdr, hash_lock);
5722			arc_hdr_destroy(hdr);
5723		} else {
5724			ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
5725			ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
5726			/*
5727			 * Invalidate issued or about to be issued
5728			 * reads, since we may be about to write
5729			 * over this location.
5730			 */
5731			if (HDR_L2_READING(hdr)) {
5732				ARCSTAT_BUMP(arcstat_l2_evict_reading);
5733				hdr->b_flags |= ARC_FLAG_L2_EVICTED;
5734			}
5735
5736			arc_hdr_l2hdr_destroy(hdr);
5737		}
5738		mutex_exit(hash_lock);
5739	}
5740	mutex_exit(&dev->l2ad_mtx);
5741}
5742
5743/*
5744 * Find and write ARC buffers to the L2ARC device.
5745 *
5746 * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
5747 * for reading until they have completed writing.
5748 * The headroom_boost is an in-out parameter used to maintain headroom boost
5749 * state between calls to this function.
5750 *
5751 * Returns the number of bytes actually written (which may be smaller than
5752 * the delta by which the device hand has changed due to alignment).
5753 */
5754static uint64_t
5755l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
5756    boolean_t *headroom_boost)
5757{
5758	arc_buf_hdr_t *hdr, *hdr_prev, *head;
5759	list_t *list;
5760	uint64_t write_asize, write_psize, write_sz, headroom,
5761	    buf_compress_minsz;
5762	void *buf_data;
5763	kmutex_t *list_lock;
5764	boolean_t full;
5765	l2arc_write_callback_t *cb;
5766	zio_t *pio, *wzio;
5767	uint64_t guid = spa_load_guid(spa);
5768	const boolean_t do_headroom_boost = *headroom_boost;
5769	int try;
5770
5771	ASSERT(dev->l2ad_vdev != NULL);
5772
5773	/* Lower the flag now, we might want to raise it again later. */
5774	*headroom_boost = B_FALSE;
5775
5776	pio = NULL;
5777	write_sz = write_asize = write_psize = 0;
5778	full = B_FALSE;
5779	head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
5780	head->b_flags |= ARC_FLAG_L2_WRITE_HEAD;
5781	head->b_flags |= ARC_FLAG_HAS_L2HDR;
5782
5783	ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
5784	/*
5785	 * We will want to try to compress buffers that are at least 2x the
5786	 * device sector size.
5787	 */
5788	buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
5789
5790	/*
5791	 * Copy buffers for L2ARC writing.
5792	 */
5793	mutex_enter(&dev->l2ad_mtx);
5794	for (try = 0; try < 2 * ARC_BUFC_NUMLISTS; try++) {
5795		uint64_t passed_sz = 0;
5796
5797		list = l2arc_list_locked(try, &list_lock);
5798		ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
5799
5800		/*
5801		 * L2ARC fast warmup.
5802		 *
5803		 * Until the ARC is warm and starts to evict, read from the
5804		 * head of the ARC lists rather than the tail.
5805		 */
5806		if (arc_warm == B_FALSE)
5807			hdr = list_head(list);
5808		else
5809			hdr = list_tail(list);
5810		if (hdr == NULL)
5811			ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
5812
5813		headroom = target_sz * l2arc_headroom * 2 / ARC_BUFC_NUMLISTS;
5814		if (do_headroom_boost)
5815			headroom = (headroom * l2arc_headroom_boost) / 100;
5816
5817		for (; hdr; hdr = hdr_prev) {
5818			kmutex_t *hash_lock;
5819			uint64_t buf_sz;
5820
5821			if (arc_warm == B_FALSE)
5822				hdr_prev = list_next(list, hdr);
5823			else
5824				hdr_prev = list_prev(list, hdr);
5825			ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned, hdr->b_size);
5826
5827			hash_lock = HDR_LOCK(hdr);
5828			if (!mutex_tryenter(hash_lock)) {
5829				ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
5830				/*
5831				 * Skip this buffer rather than waiting.
5832				 */
5833				continue;
5834			}
5835
5836			passed_sz += hdr->b_size;
5837			if (passed_sz > headroom) {
5838				/*
5839				 * Searched too far.
5840				 */
5841				mutex_exit(hash_lock);
5842				ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
5843				break;
5844			}
5845
5846			if (!l2arc_write_eligible(guid, hdr)) {
5847				mutex_exit(hash_lock);
5848				continue;
5849			}
5850
5851			if ((write_sz + hdr->b_size) > target_sz) {
5852				full = B_TRUE;
5853				mutex_exit(hash_lock);
5854				ARCSTAT_BUMP(arcstat_l2_write_full);
5855				break;
5856			}
5857
5858			if (pio == NULL) {
5859				/*
5860				 * Insert a dummy header on the buflist so
5861				 * l2arc_write_done() can find where the
5862				 * write buffers begin without searching.
5863				 */
5864				list_insert_head(&dev->l2ad_buflist, head);
5865
5866				cb = kmem_alloc(
5867				    sizeof (l2arc_write_callback_t), KM_SLEEP);
5868				cb->l2wcb_dev = dev;
5869				cb->l2wcb_head = head;
5870				pio = zio_root(spa, l2arc_write_done, cb,
5871				    ZIO_FLAG_CANFAIL);
5872				ARCSTAT_BUMP(arcstat_l2_write_pios);
5873			}
5874
5875			/*
5876			 * Create and add a new L2ARC header.
5877			 */
5878			hdr->b_l2hdr.b_dev = dev;
5879			hdr->b_flags |= ARC_FLAG_L2_WRITING;
5880			/*
5881			 * Temporarily stash the data buffer in b_tmp_cdata.
5882			 * The subsequent write step will pick it up from
5883			 * there. This is because can't access b_l1hdr.b_buf
5884			 * without holding the hash_lock, which we in turn
5885			 * can't access without holding the ARC list locks
5886			 * (which we want to avoid during compression/writing).
5887			 */
5888			HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
5889			hdr->b_l2hdr.b_asize = hdr->b_size;
5890			hdr->b_l1hdr.b_tmp_cdata = hdr->b_l1hdr.b_buf->b_data;
5891
5892			/*
5893			 * Explicitly set the b_daddr field to a known
5894			 * value which means "invalid address". This
5895			 * enables us to differentiate which stage of
5896			 * l2arc_write_buffers() the particular header
5897			 * is in (e.g. this loop, or the one below).
5898			 * ARC_FLAG_L2_WRITING is not enough to make
5899			 * this distinction, and we need to know in
5900			 * order to do proper l2arc vdev accounting in
5901			 * arc_release() and arc_hdr_destroy().
5902			 *
5903			 * Note, we can't use a new flag to distinguish
5904			 * the two stages because we don't hold the
5905			 * header's hash_lock below, in the second stage
5906			 * of this function. Thus, we can't simply
5907			 * change the b_flags field to denote that the
5908			 * IO has been sent. We can change the b_daddr
5909			 * field of the L2 portion, though, since we'll
5910			 * be holding the l2ad_mtx; which is why we're
5911			 * using it to denote the header's state change.
5912			 */
5913			hdr->b_l2hdr.b_daddr = L2ARC_ADDR_UNSET;
5914
5915			buf_sz = hdr->b_size;
5916			hdr->b_flags |= ARC_FLAG_HAS_L2HDR;
5917
5918			list_insert_head(&dev->l2ad_buflist, hdr);
5919
5920			/*
5921			 * Compute and store the buffer cksum before
5922			 * writing.  On debug the cksum is verified first.
5923			 */
5924			arc_cksum_verify(hdr->b_l1hdr.b_buf);
5925			arc_cksum_compute(hdr->b_l1hdr.b_buf, B_TRUE);
5926
5927			mutex_exit(hash_lock);
5928
5929			write_sz += buf_sz;
5930		}
5931
5932		mutex_exit(list_lock);
5933
5934		if (full == B_TRUE)
5935			break;
5936	}
5937
5938	/* No buffers selected for writing? */
5939	if (pio == NULL) {
5940		ASSERT0(write_sz);
5941		mutex_exit(&dev->l2ad_mtx);
5942		ASSERT(!HDR_HAS_L1HDR(head));
5943		kmem_cache_free(hdr_l2only_cache, head);
5944		return (0);
5945	}
5946
5947	/*
5948	 * Now start writing the buffers. We're starting at the write head
5949	 * and work backwards, retracing the course of the buffer selector
5950	 * loop above.
5951	 */
5952	for (hdr = list_prev(&dev->l2ad_buflist, head); hdr;
5953	    hdr = list_prev(&dev->l2ad_buflist, hdr)) {
5954		uint64_t buf_sz;
5955
5956		/*
5957		 * We shouldn't need to lock the buffer here, since we flagged
5958		 * it as ARC_FLAG_L2_WRITING in the previous step, but we must
5959		 * take care to only access its L2 cache parameters. In
5960		 * particular, hdr->l1hdr.b_buf may be invalid by now due to
5961		 * ARC eviction.
5962		 */
5963		hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
5964
5965		if ((HDR_L2COMPRESS(hdr)) &&
5966		    hdr->b_l2hdr.b_asize >= buf_compress_minsz) {
5967			if (l2arc_compress_buf(hdr)) {
5968				/*
5969				 * If compression succeeded, enable headroom
5970				 * boost on the next scan cycle.
5971				 */
5972				*headroom_boost = B_TRUE;
5973			}
5974		}
5975
5976		/*
5977		 * Pick up the buffer data we had previously stashed away
5978		 * (and now potentially also compressed).
5979		 */
5980		buf_data = hdr->b_l1hdr.b_tmp_cdata;
5981		buf_sz = hdr->b_l2hdr.b_asize;
5982
5983		/*
5984		 * If the data has not been compressed, then clear b_tmp_cdata
5985		 * to make sure that it points only to a temporary compression
5986		 * buffer.
5987		 */
5988		if (!L2ARC_IS_VALID_COMPRESS(HDR_GET_COMPRESS(hdr)))
5989			hdr->b_l1hdr.b_tmp_cdata = NULL;
5990
5991		/*
5992		 * We need to do this regardless if buf_sz is zero or
5993		 * not, otherwise, when this l2hdr is evicted we'll
5994		 * remove a reference that was never added.
5995		 */
5996		(void) refcount_add_many(&dev->l2ad_alloc, buf_sz, hdr);
5997
5998		/* Compression may have squashed the buffer to zero length. */
5999		if (buf_sz != 0) {
6000			uint64_t buf_p_sz;
6001
6002			wzio = zio_write_phys(pio, dev->l2ad_vdev,
6003			    dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
6004			    NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
6005			    ZIO_FLAG_CANFAIL, B_FALSE);
6006
6007			DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
6008			    zio_t *, wzio);
6009			(void) zio_nowait(wzio);
6010
6011			write_asize += buf_sz;
6012
6013			/*
6014			 * Keep the clock hand suitably device-aligned.
6015			 */
6016			buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
6017			write_psize += buf_p_sz;
6018			dev->l2ad_hand += buf_p_sz;
6019		}
6020	}
6021
6022	mutex_exit(&dev->l2ad_mtx);
6023
6024	ASSERT3U(write_asize, <=, target_sz);
6025	ARCSTAT_BUMP(arcstat_l2_writes_sent);
6026	ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
6027	ARCSTAT_INCR(arcstat_l2_size, write_sz);
6028	ARCSTAT_INCR(arcstat_l2_asize, write_asize);
6029	vdev_space_update(dev->l2ad_vdev, write_asize, 0, 0);
6030
6031	/*
6032	 * Bump device hand to the device start if it is approaching the end.
6033	 * l2arc_evict() will already have evicted ahead for this case.
6034	 */
6035	if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
6036		dev->l2ad_hand = dev->l2ad_start;
6037		dev->l2ad_first = B_FALSE;
6038	}
6039
6040	dev->l2ad_writing = B_TRUE;
6041	(void) zio_wait(pio);
6042	dev->l2ad_writing = B_FALSE;
6043
6044	return (write_asize);
6045}
6046
6047/*
6048 * Compresses an L2ARC buffer.
6049 * The data to be compressed must be prefilled in l1hdr.b_tmp_cdata and its
6050 * size in l2hdr->b_asize. This routine tries to compress the data and
6051 * depending on the compression result there are three possible outcomes:
6052 * *) The buffer was incompressible. The original l2hdr contents were left
6053 *    untouched and are ready for writing to an L2 device.
6054 * *) The buffer was all-zeros, so there is no need to write it to an L2
6055 *    device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
6056 *    set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
6057 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
6058 *    data buffer which holds the compressed data to be written, and b_asize
6059 *    tells us how much data there is. b_compress is set to the appropriate
6060 *    compression algorithm. Once writing is done, invoke
6061 *    l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
6062 *
6063 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
6064 * buffer was incompressible).
6065 */
6066static boolean_t
6067l2arc_compress_buf(arc_buf_hdr_t *hdr)
6068{
6069	void *cdata;
6070	size_t csize, len, rounded;
6071	ASSERT(HDR_HAS_L2HDR(hdr));
6072	l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
6073
6074	ASSERT(HDR_HAS_L1HDR(hdr));
6075	ASSERT(HDR_GET_COMPRESS(hdr) == ZIO_COMPRESS_OFF);
6076	ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6077
6078	len = l2hdr->b_asize;
6079	cdata = zio_data_buf_alloc(len);
6080	ASSERT3P(cdata, !=, NULL);
6081	csize = zio_compress_data(ZIO_COMPRESS_LZ4, hdr->b_l1hdr.b_tmp_cdata,
6082	    cdata, l2hdr->b_asize);
6083
6084	if (csize == 0) {
6085		/* zero block, indicate that there's nothing to write */
6086		zio_data_buf_free(cdata, len);
6087		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_EMPTY);
6088		l2hdr->b_asize = 0;
6089		hdr->b_l1hdr.b_tmp_cdata = NULL;
6090		ARCSTAT_BUMP(arcstat_l2_compress_zeros);
6091		return (B_TRUE);
6092	}
6093
6094	rounded = P2ROUNDUP(csize,
6095	    (size_t)1 << l2hdr->b_dev->l2ad_vdev->vdev_ashift);
6096	if (rounded < len) {
6097		/*
6098		 * Compression succeeded, we'll keep the cdata around for
6099		 * writing and release it afterwards.
6100		 */
6101		if (rounded > csize) {
6102			bzero((char *)cdata + csize, rounded - csize);
6103			csize = rounded;
6104		}
6105		HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_LZ4);
6106		l2hdr->b_asize = csize;
6107		hdr->b_l1hdr.b_tmp_cdata = cdata;
6108		ARCSTAT_BUMP(arcstat_l2_compress_successes);
6109		return (B_TRUE);
6110	} else {
6111		/*
6112		 * Compression failed, release the compressed buffer.
6113		 * l2hdr will be left unmodified.
6114		 */
6115		zio_data_buf_free(cdata, len);
6116		ARCSTAT_BUMP(arcstat_l2_compress_failures);
6117		return (B_FALSE);
6118	}
6119}
6120
6121/*
6122 * Decompresses a zio read back from an l2arc device. On success, the
6123 * underlying zio's io_data buffer is overwritten by the uncompressed
6124 * version. On decompression error (corrupt compressed stream), the
6125 * zio->io_error value is set to signal an I/O error.
6126 *
6127 * Please note that the compressed data stream is not checksummed, so
6128 * if the underlying device is experiencing data corruption, we may feed
6129 * corrupt data to the decompressor, so the decompressor needs to be
6130 * able to handle this situation (LZ4 does).
6131 */
6132static void
6133l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
6134{
6135	ASSERT(L2ARC_IS_VALID_COMPRESS(c));
6136
6137	if (zio->io_error != 0) {
6138		/*
6139		 * An io error has occured, just restore the original io
6140		 * size in preparation for a main pool read.
6141		 */
6142		zio->io_orig_size = zio->io_size = hdr->b_size;
6143		return;
6144	}
6145
6146	if (c == ZIO_COMPRESS_EMPTY) {
6147		/*
6148		 * An empty buffer results in a null zio, which means we
6149		 * need to fill its io_data after we're done restoring the
6150		 * buffer's contents.
6151		 */
6152		ASSERT(hdr->b_l1hdr.b_buf != NULL);
6153		bzero(hdr->b_l1hdr.b_buf->b_data, hdr->b_size);
6154		zio->io_data = zio->io_orig_data = hdr->b_l1hdr.b_buf->b_data;
6155	} else {
6156		ASSERT(zio->io_data != NULL);
6157		/*
6158		 * We copy the compressed data from the start of the arc buffer
6159		 * (the zio_read will have pulled in only what we need, the
6160		 * rest is garbage which we will overwrite at decompression)
6161		 * and then decompress back to the ARC data buffer. This way we
6162		 * can minimize copying by simply decompressing back over the
6163		 * original compressed data (rather than decompressing to an
6164		 * aux buffer and then copying back the uncompressed buffer,
6165		 * which is likely to be much larger).
6166		 */
6167		uint64_t csize;
6168		void *cdata;
6169
6170		csize = zio->io_size;
6171		cdata = zio_data_buf_alloc(csize);
6172		bcopy(zio->io_data, cdata, csize);
6173		if (zio_decompress_data(c, cdata, zio->io_data, csize,
6174		    hdr->b_size) != 0)
6175			zio->io_error = EIO;
6176		zio_data_buf_free(cdata, csize);
6177	}
6178
6179	/* Restore the expected uncompressed IO size. */
6180	zio->io_orig_size = zio->io_size = hdr->b_size;
6181}
6182
6183/*
6184 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
6185 * This buffer serves as a temporary holder of compressed data while
6186 * the buffer entry is being written to an l2arc device. Once that is
6187 * done, we can dispose of it.
6188 */
6189static void
6190l2arc_release_cdata_buf(arc_buf_hdr_t *hdr)
6191{
6192	ASSERT(HDR_HAS_L1HDR(hdr));
6193	if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_EMPTY) {
6194		/*
6195		 * If the data was compressed, then we've allocated a
6196		 * temporary buffer for it, so now we need to release it.
6197		 */
6198		ASSERT(hdr->b_l1hdr.b_tmp_cdata != NULL);
6199		zio_data_buf_free(hdr->b_l1hdr.b_tmp_cdata,
6200		    hdr->b_size);
6201		hdr->b_l1hdr.b_tmp_cdata = NULL;
6202	} else {
6203		ASSERT(hdr->b_l1hdr.b_tmp_cdata == NULL);
6204	}
6205}
6206
6207/*
6208 * This thread feeds the L2ARC at regular intervals.  This is the beating
6209 * heart of the L2ARC.
6210 */
6211static void
6212l2arc_feed_thread(void *dummy __unused)
6213{
6214	callb_cpr_t cpr;
6215	l2arc_dev_t *dev;
6216	spa_t *spa;
6217	uint64_t size, wrote;
6218	clock_t begin, next = ddi_get_lbolt();
6219	boolean_t headroom_boost = B_FALSE;
6220
6221	CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
6222
6223	mutex_enter(&l2arc_feed_thr_lock);
6224
6225	while (l2arc_thread_exit == 0) {
6226		CALLB_CPR_SAFE_BEGIN(&cpr);
6227		(void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
6228		    next - ddi_get_lbolt());
6229		CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
6230		next = ddi_get_lbolt() + hz;
6231
6232		/*
6233		 * Quick check for L2ARC devices.
6234		 */
6235		mutex_enter(&l2arc_dev_mtx);
6236		if (l2arc_ndev == 0) {
6237			mutex_exit(&l2arc_dev_mtx);
6238			continue;
6239		}
6240		mutex_exit(&l2arc_dev_mtx);
6241		begin = ddi_get_lbolt();
6242
6243		/*
6244		 * This selects the next l2arc device to write to, and in
6245		 * doing so the next spa to feed from: dev->l2ad_spa.   This
6246		 * will return NULL if there are now no l2arc devices or if
6247		 * they are all faulted.
6248		 *
6249		 * If a device is returned, its spa's config lock is also
6250		 * held to prevent device removal.  l2arc_dev_get_next()
6251		 * will grab and release l2arc_dev_mtx.
6252		 */
6253		if ((dev = l2arc_dev_get_next()) == NULL)
6254			continue;
6255
6256		spa = dev->l2ad_spa;
6257		ASSERT(spa != NULL);
6258
6259		/*
6260		 * If the pool is read-only then force the feed thread to
6261		 * sleep a little longer.
6262		 */
6263		if (!spa_writeable(spa)) {
6264			next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
6265			spa_config_exit(spa, SCL_L2ARC, dev);
6266			continue;
6267		}
6268
6269		/*
6270		 * Avoid contributing to memory pressure.
6271		 */
6272		if (arc_reclaim_needed()) {
6273			ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
6274			spa_config_exit(spa, SCL_L2ARC, dev);
6275			continue;
6276		}
6277
6278		ARCSTAT_BUMP(arcstat_l2_feeds);
6279
6280		size = l2arc_write_size();
6281
6282		/*
6283		 * Evict L2ARC buffers that will be overwritten.
6284		 */
6285		l2arc_evict(dev, size, B_FALSE);
6286
6287		/*
6288		 * Write ARC buffers.
6289		 */
6290		wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
6291
6292		/*
6293		 * Calculate interval between writes.
6294		 */
6295		next = l2arc_write_interval(begin, size, wrote);
6296		spa_config_exit(spa, SCL_L2ARC, dev);
6297	}
6298
6299	l2arc_thread_exit = 0;
6300	cv_broadcast(&l2arc_feed_thr_cv);
6301	CALLB_CPR_EXIT(&cpr);		/* drops l2arc_feed_thr_lock */
6302	thread_exit();
6303}
6304
6305boolean_t
6306l2arc_vdev_present(vdev_t *vd)
6307{
6308	l2arc_dev_t *dev;
6309
6310	mutex_enter(&l2arc_dev_mtx);
6311	for (dev = list_head(l2arc_dev_list); dev != NULL;
6312	    dev = list_next(l2arc_dev_list, dev)) {
6313		if (dev->l2ad_vdev == vd)
6314			break;
6315	}
6316	mutex_exit(&l2arc_dev_mtx);
6317
6318	return (dev != NULL);
6319}
6320
6321/*
6322 * Add a vdev for use by the L2ARC.  By this point the spa has already
6323 * validated the vdev and opened it.
6324 */
6325void
6326l2arc_add_vdev(spa_t *spa, vdev_t *vd)
6327{
6328	l2arc_dev_t *adddev;
6329
6330	ASSERT(!l2arc_vdev_present(vd));
6331
6332	vdev_ashift_optimize(vd);
6333
6334	/*
6335	 * Create a new l2arc device entry.
6336	 */
6337	adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
6338	adddev->l2ad_spa = spa;
6339	adddev->l2ad_vdev = vd;
6340	adddev->l2ad_start = VDEV_LABEL_START_SIZE;
6341	adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
6342	adddev->l2ad_hand = adddev->l2ad_start;
6343	adddev->l2ad_first = B_TRUE;
6344	adddev->l2ad_writing = B_FALSE;
6345
6346	mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
6347	/*
6348	 * This is a list of all ARC buffers that are still valid on the
6349	 * device.
6350	 */
6351	list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
6352	    offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
6353
6354	vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
6355	refcount_create(&adddev->l2ad_alloc);
6356
6357	/*
6358	 * Add device to global list
6359	 */
6360	mutex_enter(&l2arc_dev_mtx);
6361	list_insert_head(l2arc_dev_list, adddev);
6362	atomic_inc_64(&l2arc_ndev);
6363	mutex_exit(&l2arc_dev_mtx);
6364}
6365
6366/*
6367 * Remove a vdev from the L2ARC.
6368 */
6369void
6370l2arc_remove_vdev(vdev_t *vd)
6371{
6372	l2arc_dev_t *dev, *nextdev, *remdev = NULL;
6373
6374	/*
6375	 * Find the device by vdev
6376	 */
6377	mutex_enter(&l2arc_dev_mtx);
6378	for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
6379		nextdev = list_next(l2arc_dev_list, dev);
6380		if (vd == dev->l2ad_vdev) {
6381			remdev = dev;
6382			break;
6383		}
6384	}
6385	ASSERT(remdev != NULL);
6386
6387	/*
6388	 * Remove device from global list
6389	 */
6390	list_remove(l2arc_dev_list, remdev);
6391	l2arc_dev_last = NULL;		/* may have been invalidated */
6392	atomic_dec_64(&l2arc_ndev);
6393	mutex_exit(&l2arc_dev_mtx);
6394
6395	/*
6396	 * Clear all buflists and ARC references.  L2ARC device flush.
6397	 */
6398	l2arc_evict(remdev, 0, B_TRUE);
6399	list_destroy(&remdev->l2ad_buflist);
6400	mutex_destroy(&remdev->l2ad_mtx);
6401	refcount_destroy(&remdev->l2ad_alloc);
6402	kmem_free(remdev, sizeof (l2arc_dev_t));
6403}
6404
6405void
6406l2arc_init(void)
6407{
6408	l2arc_thread_exit = 0;
6409	l2arc_ndev = 0;
6410	l2arc_writes_sent = 0;
6411	l2arc_writes_done = 0;
6412
6413	mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
6414	cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
6415	mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
6416	mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
6417
6418	l2arc_dev_list = &L2ARC_dev_list;
6419	l2arc_free_on_write = &L2ARC_free_on_write;
6420	list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
6421	    offsetof(l2arc_dev_t, l2ad_node));
6422	list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
6423	    offsetof(l2arc_data_free_t, l2df_list_node));
6424}
6425
6426void
6427l2arc_fini(void)
6428{
6429	/*
6430	 * This is called from dmu_fini(), which is called from spa_fini();
6431	 * Because of this, we can assume that all l2arc devices have
6432	 * already been removed when the pools themselves were removed.
6433	 */
6434
6435	l2arc_do_free_on_write();
6436
6437	mutex_destroy(&l2arc_feed_thr_lock);
6438	cv_destroy(&l2arc_feed_thr_cv);
6439	mutex_destroy(&l2arc_dev_mtx);
6440	mutex_destroy(&l2arc_free_on_write_mtx);
6441
6442	list_destroy(l2arc_dev_list);
6443	list_destroy(l2arc_free_on_write);
6444}
6445
6446void
6447l2arc_start(void)
6448{
6449	if (!(spa_mode_global & FWRITE))
6450		return;
6451
6452	(void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
6453	    TS_RUN, minclsyspri);
6454}
6455
6456void
6457l2arc_stop(void)
6458{
6459	if (!(spa_mode_global & FWRITE))
6460		return;
6461
6462	mutex_enter(&l2arc_feed_thr_lock);
6463	cv_signal(&l2arc_feed_thr_cv);	/* kick thread out of startup */
6464	l2arc_thread_exit = 1;
6465	while (l2arc_thread_exit != 0)
6466		cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
6467	mutex_exit(&l2arc_feed_thr_lock);
6468}
6469