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