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