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