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