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