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