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