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