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