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