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