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