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