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