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