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