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