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