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