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