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