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