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