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