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