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