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