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