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