]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
Merge llvm, clang, lld, lldb, compiler-rt and libc++ release_70 branch
[FreeBSD/FreeBSD.git] / sys / cddl / contrib / opensolaris / uts / common / fs / zfs / arc.c
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2018, Joyent, Inc.
24  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2014 by Saso Kiselkov. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
27  */
28
29 /*
30  * DVA-based Adjustable Replacement Cache
31  *
32  * While much of the theory of operation used here is
33  * based on the self-tuning, low overhead replacement cache
34  * presented by Megiddo and Modha at FAST 2003, there are some
35  * significant differences:
36  *
37  * 1. The Megiddo and Modha model assumes any page is evictable.
38  * Pages in its cache cannot be "locked" into memory.  This makes
39  * the eviction algorithm simple: evict the last page in the list.
40  * This also make the performance characteristics easy to reason
41  * about.  Our cache is not so simple.  At any given moment, some
42  * subset of the blocks in the cache are un-evictable because we
43  * have handed out a reference to them.  Blocks are only evictable
44  * when there are no external references active.  This makes
45  * eviction far more problematic:  we choose to evict the evictable
46  * blocks that are the "lowest" in the list.
47  *
48  * There are times when it is not possible to evict the requested
49  * space.  In these circumstances we are unable to adjust the cache
50  * size.  To prevent the cache growing unbounded at these times we
51  * implement a "cache throttle" that slows the flow of new data
52  * into the cache until we can make space available.
53  *
54  * 2. The Megiddo and Modha model assumes a fixed cache size.
55  * Pages are evicted when the cache is full and there is a cache
56  * miss.  Our model has a variable sized cache.  It grows with
57  * high use, but also tries to react to memory pressure from the
58  * operating system: decreasing its size when system memory is
59  * tight.
60  *
61  * 3. The Megiddo and Modha model assumes a fixed page size. All
62  * elements of the cache are therefore exactly the same size.  So
63  * when adjusting the cache size following a cache miss, its simply
64  * a matter of choosing a single page to evict.  In our model, we
65  * have variable sized cache blocks (rangeing from 512 bytes to
66  * 128K bytes).  We therefore choose a set of blocks to evict to make
67  * space for a cache miss that approximates as closely as possible
68  * the space used by the new block.
69  *
70  * See also:  "ARC: A Self-Tuning, Low Overhead Replacement Cache"
71  * by N. Megiddo & D. Modha, FAST 2003
72  */
73
74 /*
75  * The locking model:
76  *
77  * A new reference to a cache buffer can be obtained in two
78  * ways: 1) via a hash table lookup using the DVA as a key,
79  * or 2) via one of the ARC lists.  The arc_read() interface
80  * uses method 1, while the internal ARC algorithms for
81  * adjusting the cache use method 2.  We therefore provide two
82  * types of locks: 1) the hash table lock array, and 2) the
83  * ARC list locks.
84  *
85  * Buffers do not have their own mutexes, rather they rely on the
86  * hash table mutexes for the bulk of their protection (i.e. most
87  * fields in the arc_buf_hdr_t are protected by these mutexes).
88  *
89  * buf_hash_find() returns the appropriate mutex (held) when it
90  * locates the requested buffer in the hash table.  It returns
91  * NULL for the mutex if the buffer was not in the table.
92  *
93  * buf_hash_remove() expects the appropriate hash mutex to be
94  * already held before it is invoked.
95  *
96  * Each ARC state also has a mutex which is used to protect the
97  * buffer list associated with the state.  When attempting to
98  * obtain a hash table lock while holding an ARC list lock you
99  * must use: mutex_tryenter() to avoid deadlock.  Also note that
100  * the active state mutex must be held before the ghost state mutex.
101  *
102  * It as also possible to register a callback which is run when the
103  * arc_meta_limit is reached and no buffers can be safely evicted.  In
104  * this case the arc user should drop a reference on some arc buffers so
105  * they can be reclaimed and the arc_meta_limit honored.  For example,
106  * when using the ZPL each dentry holds a references on a znode.  These
107  * dentries must be pruned before the arc buffer holding the znode can
108  * be safely evicted.
109  *
110  * Note that the majority of the performance stats are manipulated
111  * with atomic operations.
112  *
113  * The L2ARC uses the l2ad_mtx on each vdev for the following:
114  *
115  *      - L2ARC buflist creation
116  *      - L2ARC buflist eviction
117  *      - L2ARC write completion, which walks L2ARC buflists
118  *      - ARC header destruction, as it removes from L2ARC buflists
119  *      - ARC header release, as it removes from L2ARC buflists
120  */
121
122 /*
123  * ARC operation:
124  *
125  * Every block that is in the ARC is tracked by an arc_buf_hdr_t structure.
126  * This structure can point either to a block that is still in the cache or to
127  * one that is only accessible in an L2 ARC device, or it can provide
128  * information about a block that was recently evicted. If a block is
129  * only accessible in the L2ARC, then the arc_buf_hdr_t only has enough
130  * information to retrieve it from the L2ARC device. This information is
131  * stored in the l2arc_buf_hdr_t sub-structure of the arc_buf_hdr_t. A block
132  * that is in this state cannot access the data directly.
133  *
134  * Blocks that are actively being referenced or have not been evicted
135  * are cached in the L1ARC. The L1ARC (l1arc_buf_hdr_t) is a structure within
136  * the arc_buf_hdr_t that will point to the data block in memory. A block can
137  * only be read by a consumer if it has an l1arc_buf_hdr_t. The L1ARC
138  * caches data in two ways -- in a list of ARC buffers (arc_buf_t) and
139  * also in the arc_buf_hdr_t's private physical data block pointer (b_pabd).
140  *
141  * The L1ARC's data pointer may or may not be uncompressed. The ARC has the
142  * ability to store the physical data (b_pabd) associated with the DVA of the
143  * arc_buf_hdr_t. Since the b_pabd is a copy of the on-disk physical block,
144  * it will match its on-disk compression characteristics. This behavior can be
145  * disabled by setting 'zfs_compressed_arc_enabled' to B_FALSE. When the
146  * compressed ARC functionality is disabled, the b_pabd will point to an
147  * uncompressed version of the on-disk data.
148  *
149  * Data in the L1ARC is not accessed by consumers of the ARC directly. Each
150  * arc_buf_hdr_t can have multiple ARC buffers (arc_buf_t) which reference it.
151  * Each ARC buffer (arc_buf_t) is being actively accessed by a specific ARC
152  * consumer. The ARC will provide references to this data and will keep it
153  * cached until it is no longer in use. The ARC caches only the L1ARC's physical
154  * data block and will evict any arc_buf_t that is no longer referenced. The
155  * amount of memory consumed by the arc_buf_ts' data buffers can be seen via the
156  * "overhead_size" kstat.
157  *
158  * Depending on the consumer, an arc_buf_t can be requested in uncompressed or
159  * compressed form. The typical case is that consumers will want uncompressed
160  * data, and when that happens a new data buffer is allocated where the data is
161  * decompressed for them to use. Currently the only consumer who wants
162  * compressed arc_buf_t's is "zfs send", when it streams data exactly as it
163  * exists on disk. When this happens, the arc_buf_t's data buffer is shared
164  * with the arc_buf_hdr_t.
165  *
166  * Here is a diagram showing an arc_buf_hdr_t referenced by two arc_buf_t's. The
167  * first one is owned by a compressed send consumer (and therefore references
168  * the same compressed data buffer as the arc_buf_hdr_t) and the second could be
169  * used by any other consumer (and has its own uncompressed copy of the data
170  * buffer).
171  *
172  *   arc_buf_hdr_t
173  *   +-----------+
174  *   | fields    |
175  *   | common to |
176  *   | L1- and   |
177  *   | L2ARC     |
178  *   +-----------+
179  *   | l2arc_buf_hdr_t
180  *   |           |
181  *   +-----------+
182  *   | l1arc_buf_hdr_t
183  *   |           |              arc_buf_t
184  *   | b_buf     +------------>+-----------+      arc_buf_t
185  *   | b_pabd    +-+           |b_next     +---->+-----------+
186  *   +-----------+ |           |-----------|     |b_next     +-->NULL
187  *                 |           |b_comp = T |     +-----------+
188  *                 |           |b_data     +-+   |b_comp = F |
189  *                 |           +-----------+ |   |b_data     +-+
190  *                 +->+------+               |   +-----------+ |
191  *        compressed  |      |               |                 |
192  *           data     |      |<--------------+                 | uncompressed
193  *                    +------+          compressed,            |     data
194  *                                        shared               +-->+------+
195  *                                         data                    |      |
196  *                                                                 |      |
197  *                                                                 +------+
198  *
199  * When a consumer reads a block, the ARC must first look to see if the
200  * arc_buf_hdr_t is cached. If the hdr is cached then the ARC allocates a new
201  * arc_buf_t and either copies uncompressed data into a new data buffer from an
202  * existing uncompressed arc_buf_t, decompresses the hdr's b_pabd buffer into a
203  * new data buffer, or shares the hdr's b_pabd buffer, depending on whether the
204  * hdr is compressed and the desired compression characteristics of the
205  * arc_buf_t consumer. If the arc_buf_t ends up sharing data with the
206  * arc_buf_hdr_t and both of them are uncompressed then the arc_buf_t must be
207  * the last buffer in the hdr's b_buf list, however a shared compressed buf can
208  * be anywhere in the hdr's list.
209  *
210  * The diagram below shows an example of an uncompressed ARC hdr that is
211  * sharing its data with an arc_buf_t (note that the shared uncompressed buf is
212  * the last element in the buf list):
213  *
214  *                arc_buf_hdr_t
215  *                +-----------+
216  *                |           |
217  *                |           |
218  *                |           |
219  *                +-----------+
220  * l2arc_buf_hdr_t|           |
221  *                |           |
222  *                +-----------+
223  * l1arc_buf_hdr_t|           |
224  *                |           |                 arc_buf_t    (shared)
225  *                |    b_buf  +------------>+---------+      arc_buf_t
226  *                |           |             |b_next   +---->+---------+
227  *                |  b_pabd   +-+           |---------|     |b_next   +-->NULL
228  *                +-----------+ |           |         |     +---------+
229  *                              |           |b_data   +-+   |         |
230  *                              |           +---------+ |   |b_data   +-+
231  *                              +->+------+             |   +---------+ |
232  *                                 |      |             |               |
233  *                   uncompressed  |      |             |               |
234  *                        data     +------+             |               |
235  *                                    ^                 +->+------+     |
236  *                                    |       uncompressed |      |     |
237  *                                    |           data     |      |     |
238  *                                    |                    +------+     |
239  *                                    +---------------------------------+
240  *
241  * Writing to the ARC requires that the ARC first discard the hdr's b_pabd
242  * since the physical block is about to be rewritten. The new data contents
243  * will be contained in the arc_buf_t. As the I/O pipeline performs the write,
244  * it may compress the data before writing it to disk. The ARC will be called
245  * with the transformed data and will bcopy the transformed on-disk block into
246  * a newly allocated b_pabd. Writes are always done into buffers which have
247  * either been loaned (and hence are new and don't have other readers) or
248  * buffers which have been released (and hence have their own hdr, if there
249  * were originally other readers of the buf's original hdr). This ensures that
250  * the ARC only needs to update a single buf and its hdr after a write occurs.
251  *
252  * When the L2ARC is in use, it will also take advantage of the b_pabd. The
253  * L2ARC will always write the contents of b_pabd to the L2ARC. This means
254  * that when compressed ARC is enabled that the L2ARC blocks are identical
255  * to the on-disk block in the main data pool. This provides a significant
256  * advantage since the ARC can leverage the bp's checksum when reading from the
257  * L2ARC to determine if the contents are valid. However, if the compressed
258  * ARC is disabled, then the L2ARC's block must be transformed to look
259  * like the physical block in the main data pool before comparing the
260  * checksum and determining its validity.
261  */
262
263 #include <sys/spa.h>
264 #include <sys/zio.h>
265 #include <sys/spa_impl.h>
266 #include <sys/zio_compress.h>
267 #include <sys/zio_checksum.h>
268 #include <sys/zfs_context.h>
269 #include <sys/arc.h>
270 #include <sys/refcount.h>
271 #include <sys/vdev.h>
272 #include <sys/vdev_impl.h>
273 #include <sys/dsl_pool.h>
274 #include <sys/zio_checksum.h>
275 #include <sys/multilist.h>
276 #include <sys/abd.h>
277 #ifdef _KERNEL
278 #include <sys/dnlc.h>
279 #include <sys/racct.h>
280 #endif
281 #include <sys/callb.h>
282 #include <sys/kstat.h>
283 #include <sys/trim_map.h>
284 #include <zfs_fletcher.h>
285 #include <sys/sdt.h>
286 #include <sys/aggsum.h>
287 #include <sys/cityhash.h>
288
289 #include <machine/vmparam.h>
290
291 #ifdef illumos
292 #ifndef _KERNEL
293 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
294 boolean_t arc_watch = B_FALSE;
295 int arc_procfd;
296 #endif
297 #endif /* illumos */
298
299 static kmutex_t         arc_reclaim_lock;
300 static kcondvar_t       arc_reclaim_thread_cv;
301 static boolean_t        arc_reclaim_thread_exit;
302 static kcondvar_t       arc_reclaim_waiters_cv;
303
304 static kmutex_t         arc_dnlc_evicts_lock;
305 static kcondvar_t       arc_dnlc_evicts_cv;
306 static boolean_t        arc_dnlc_evicts_thread_exit;
307
308 uint_t arc_reduce_dnlc_percent = 3;
309
310 /*
311  * The number of headers to evict in arc_evict_state_impl() before
312  * dropping the sublist lock and evicting from another sublist. A lower
313  * value means we're more likely to evict the "correct" header (i.e. the
314  * oldest header in the arc state), but comes with higher overhead
315  * (i.e. more invocations of arc_evict_state_impl()).
316  */
317 int zfs_arc_evict_batch_limit = 10;
318
319 /* number of seconds before growing cache again */
320 static int              arc_grow_retry = 60;
321
322 /* number of milliseconds before attempting a kmem-cache-reap */
323 static int              arc_kmem_cache_reap_retry_ms = 0;
324
325 /* shift of arc_c for calculating overflow limit in arc_get_data_impl */
326 int             zfs_arc_overflow_shift = 8;
327
328 /* shift of arc_c for calculating both min and max arc_p */
329 static int              arc_p_min_shift = 4;
330
331 /* log2(fraction of arc to reclaim) */
332 static int              arc_shrink_shift = 7;
333
334 /*
335  * log2(fraction of ARC which must be free to allow growing).
336  * I.e. If there is less than arc_c >> arc_no_grow_shift free memory,
337  * when reading a new block into the ARC, we will evict an equal-sized block
338  * from the ARC.
339  *
340  * This must be less than arc_shrink_shift, so that when we shrink the ARC,
341  * we will still not allow it to grow.
342  */
343 int                     arc_no_grow_shift = 5;
344
345
346 /*
347  * minimum lifespan of a prefetch block in clock ticks
348  * (initialized in arc_init())
349  */
350 static int              zfs_arc_min_prefetch_ms = 1;
351 static int              zfs_arc_min_prescient_prefetch_ms = 6;
352
353 /*
354  * If this percent of memory is free, don't throttle.
355  */
356 int arc_lotsfree_percent = 10;
357
358 static int arc_dead;
359 extern boolean_t zfs_prefetch_disable;
360
361 /*
362  * The arc has filled available memory and has now warmed up.
363  */
364 static boolean_t arc_warm;
365
366 /*
367  * log2 fraction of the zio arena to keep free.
368  */
369 int arc_zio_arena_free_shift = 2;
370
371 /*
372  * These tunables are for performance analysis.
373  */
374 uint64_t zfs_arc_max;
375 uint64_t zfs_arc_min;
376 uint64_t zfs_arc_meta_limit = 0;
377 uint64_t zfs_arc_meta_min = 0;
378 uint64_t zfs_arc_dnode_limit = 0;
379 uint64_t zfs_arc_dnode_reduce_percent = 10;
380 int zfs_arc_grow_retry = 0;
381 int zfs_arc_shrink_shift = 0;
382 int zfs_arc_no_grow_shift = 0;
383 int zfs_arc_p_min_shift = 0;
384 uint64_t zfs_arc_average_blocksize = 8 * 1024; /* 8KB */
385 u_int zfs_arc_free_target = 0;
386
387 /* Absolute min for arc min / max is 16MB. */
388 static uint64_t arc_abs_min = 16 << 20;
389
390 /*
391  * ARC dirty data constraints for arc_tempreserve_space() throttle
392  */
393 uint_t zfs_arc_dirty_limit_percent = 50;        /* total dirty data limit */
394 uint_t zfs_arc_anon_limit_percent = 25;         /* anon block dirty limit */
395 uint_t zfs_arc_pool_dirty_percent = 20;         /* each pool's anon allowance */
396
397 boolean_t zfs_compressed_arc_enabled = B_TRUE;
398
399 static int sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS);
400 static int sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS);
401 static int sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS);
402 static int sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS);
403 static int sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS);
404
405 #if defined(__FreeBSD__) && defined(_KERNEL)
406 static void
407 arc_free_target_init(void *unused __unused)
408 {
409
410         zfs_arc_free_target = vm_cnt.v_free_target;
411 }
412 SYSINIT(arc_free_target_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY,
413     arc_free_target_init, NULL);
414
415 TUNABLE_QUAD("vfs.zfs.arc_meta_limit", &zfs_arc_meta_limit);
416 TUNABLE_QUAD("vfs.zfs.arc_meta_min", &zfs_arc_meta_min);
417 TUNABLE_INT("vfs.zfs.arc_shrink_shift", &zfs_arc_shrink_shift);
418 TUNABLE_INT("vfs.zfs.arc_grow_retry", &zfs_arc_grow_retry);
419 TUNABLE_INT("vfs.zfs.arc_no_grow_shift", &zfs_arc_no_grow_shift);
420 SYSCTL_DECL(_vfs_zfs);
421 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_max, CTLTYPE_U64 | CTLFLAG_RWTUN,
422     0, sizeof(uint64_t), sysctl_vfs_zfs_arc_max, "QU", "Maximum ARC size");
423 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_min, CTLTYPE_U64 | CTLFLAG_RWTUN,
424     0, sizeof(uint64_t), sysctl_vfs_zfs_arc_min, "QU", "Minimum ARC size");
425 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_no_grow_shift, CTLTYPE_U32 | CTLFLAG_RWTUN,
426     0, sizeof(uint32_t), sysctl_vfs_zfs_arc_no_grow_shift, "U",
427     "log2(fraction of ARC which must be free to allow growing)");
428 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, arc_average_blocksize, CTLFLAG_RDTUN,
429     &zfs_arc_average_blocksize, 0,
430     "ARC average blocksize");
431 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_shrink_shift, CTLFLAG_RW,
432     &arc_shrink_shift, 0,
433     "log2(fraction of arc to reclaim)");
434 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_grow_retry, CTLFLAG_RW,
435     &arc_grow_retry, 0,
436     "Wait in seconds before considering growing ARC");
437 SYSCTL_INT(_vfs_zfs, OID_AUTO, compressed_arc_enabled, CTLFLAG_RDTUN,
438     &zfs_compressed_arc_enabled, 0,
439     "Enable compressed ARC");
440 SYSCTL_INT(_vfs_zfs, OID_AUTO, arc_kmem_cache_reap_retry_ms, CTLFLAG_RWTUN,
441     &arc_kmem_cache_reap_retry_ms, 0,
442     "Interval between ARC kmem_cache reapings");
443
444 /*
445  * We don't have a tunable for arc_free_target due to the dependency on
446  * pagedaemon initialisation.
447  */
448 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_free_target,
449     CTLTYPE_UINT | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(u_int),
450     sysctl_vfs_zfs_arc_free_target, "IU",
451     "Desired number of free pages below which ARC triggers reclaim");
452
453 static int
454 sysctl_vfs_zfs_arc_free_target(SYSCTL_HANDLER_ARGS)
455 {
456         u_int val;
457         int err;
458
459         val = zfs_arc_free_target;
460         err = sysctl_handle_int(oidp, &val, 0, req);
461         if (err != 0 || req->newptr == NULL)
462                 return (err);
463
464         if (val < minfree)
465                 return (EINVAL);
466         if (val > vm_cnt.v_page_count)
467                 return (EINVAL);
468
469         zfs_arc_free_target = val;
470
471         return (0);
472 }
473
474 /*
475  * Must be declared here, before the definition of corresponding kstat
476  * macro which uses the same names will confuse the compiler.
477  */
478 SYSCTL_PROC(_vfs_zfs, OID_AUTO, arc_meta_limit,
479     CTLTYPE_U64 | CTLFLAG_MPSAFE | CTLFLAG_RW, 0, sizeof(uint64_t),
480     sysctl_vfs_zfs_arc_meta_limit, "QU",
481     "ARC metadata limit");
482 #endif
483
484 /*
485  * Note that buffers can be in one of 6 states:
486  *      ARC_anon        - anonymous (discussed below)
487  *      ARC_mru         - recently used, currently cached
488  *      ARC_mru_ghost   - recentely used, no longer in cache
489  *      ARC_mfu         - frequently used, currently cached
490  *      ARC_mfu_ghost   - frequently used, no longer in cache
491  *      ARC_l2c_only    - exists in L2ARC but not other states
492  * When there are no active references to the buffer, they are
493  * are linked onto a list in one of these arc states.  These are
494  * the only buffers that can be evicted or deleted.  Within each
495  * state there are multiple lists, one for meta-data and one for
496  * non-meta-data.  Meta-data (indirect blocks, blocks of dnodes,
497  * etc.) is tracked separately so that it can be managed more
498  * explicitly: favored over data, limited explicitly.
499  *
500  * Anonymous buffers are buffers that are not associated with
501  * a DVA.  These are buffers that hold dirty block copies
502  * before they are written to stable storage.  By definition,
503  * they are "ref'd" and are considered part of arc_mru
504  * that cannot be freed.  Generally, they will aquire a DVA
505  * as they are written and migrate onto the arc_mru list.
506  *
507  * The ARC_l2c_only state is for buffers that are in the second
508  * level ARC but no longer in any of the ARC_m* lists.  The second
509  * level ARC itself may also contain buffers that are in any of
510  * the ARC_m* states - meaning that a buffer can exist in two
511  * places.  The reason for the ARC_l2c_only state is to keep the
512  * buffer header in the hash table, so that reads that hit the
513  * second level ARC benefit from these fast lookups.
514  */
515
516 typedef struct arc_state {
517         /*
518          * list of evictable buffers
519          */
520         multilist_t *arcs_list[ARC_BUFC_NUMTYPES];
521         /*
522          * total amount of evictable data in this state
523          */
524         refcount_t arcs_esize[ARC_BUFC_NUMTYPES];
525         /*
526          * total amount of data in this state; this includes: evictable,
527          * non-evictable, ARC_BUFC_DATA, and ARC_BUFC_METADATA.
528          */
529         refcount_t arcs_size;
530         /*
531          * supports the "dbufs" kstat
532          */
533         arc_state_type_t arcs_state;
534 } arc_state_t;
535
536 /*
537  * Percentage that can be consumed by dnodes of ARC meta buffers.
538  */
539 int zfs_arc_meta_prune = 10000;
540 unsigned long zfs_arc_dnode_limit_percent = 10;
541 int zfs_arc_meta_strategy = ARC_STRATEGY_META_BALANCED;
542 int zfs_arc_meta_adjust_restarts = 4096;
543
544 /* The 6 states: */
545 static arc_state_t ARC_anon;
546 static arc_state_t ARC_mru;
547 static arc_state_t ARC_mru_ghost;
548 static arc_state_t ARC_mfu;
549 static arc_state_t ARC_mfu_ghost;
550 static arc_state_t ARC_l2c_only;
551
552 typedef struct arc_stats {
553         kstat_named_t arcstat_hits;
554         kstat_named_t arcstat_misses;
555         kstat_named_t arcstat_demand_data_hits;
556         kstat_named_t arcstat_demand_data_misses;
557         kstat_named_t arcstat_demand_metadata_hits;
558         kstat_named_t arcstat_demand_metadata_misses;
559         kstat_named_t arcstat_prefetch_data_hits;
560         kstat_named_t arcstat_prefetch_data_misses;
561         kstat_named_t arcstat_prefetch_metadata_hits;
562         kstat_named_t arcstat_prefetch_metadata_misses;
563         kstat_named_t arcstat_mru_hits;
564         kstat_named_t arcstat_mru_ghost_hits;
565         kstat_named_t arcstat_mfu_hits;
566         kstat_named_t arcstat_mfu_ghost_hits;
567         kstat_named_t arcstat_allocated;
568         kstat_named_t arcstat_deleted;
569         /*
570          * Number of buffers that could not be evicted because the hash lock
571          * was held by another thread.  The lock may not necessarily be held
572          * by something using the same buffer, since hash locks are shared
573          * by multiple buffers.
574          */
575         kstat_named_t arcstat_mutex_miss;
576         /*
577          * Number of buffers skipped when updating the access state due to the
578          * header having already been released after acquiring the hash lock.
579          */
580         kstat_named_t arcstat_access_skip;
581         /*
582          * Number of buffers skipped because they have I/O in progress, are
583          * indirect prefetch buffers that have not lived long enough, or are
584          * not from the spa we're trying to evict from.
585          */
586         kstat_named_t arcstat_evict_skip;
587         /*
588          * Number of times arc_evict_state() was unable to evict enough
589          * buffers to reach it's target amount.
590          */
591         kstat_named_t arcstat_evict_not_enough;
592         kstat_named_t arcstat_evict_l2_cached;
593         kstat_named_t arcstat_evict_l2_eligible;
594         kstat_named_t arcstat_evict_l2_ineligible;
595         kstat_named_t arcstat_evict_l2_skip;
596         kstat_named_t arcstat_hash_elements;
597         kstat_named_t arcstat_hash_elements_max;
598         kstat_named_t arcstat_hash_collisions;
599         kstat_named_t arcstat_hash_chains;
600         kstat_named_t arcstat_hash_chain_max;
601         kstat_named_t arcstat_p;
602         kstat_named_t arcstat_c;
603         kstat_named_t arcstat_c_min;
604         kstat_named_t arcstat_c_max;
605         /* Not updated directly; only synced in arc_kstat_update. */
606         kstat_named_t arcstat_size;
607         /*
608          * Number of compressed bytes stored in the arc_buf_hdr_t's b_pabd.
609          * Note that the compressed bytes may match the uncompressed bytes
610          * if the block is either not compressed or compressed arc is disabled.
611          */
612         kstat_named_t arcstat_compressed_size;
613         /*
614          * Uncompressed size of the data stored in b_pabd. If compressed
615          * arc is disabled then this value will be identical to the stat
616          * above.
617          */
618         kstat_named_t arcstat_uncompressed_size;
619         /*
620          * Number of bytes stored in all the arc_buf_t's. This is classified
621          * as "overhead" since this data is typically short-lived and will
622          * be evicted from the arc when it becomes unreferenced unless the
623          * zfs_keep_uncompressed_metadata or zfs_keep_uncompressed_level
624          * values have been set (see comment in dbuf.c for more information).
625          */
626         kstat_named_t arcstat_overhead_size;
627         /*
628          * Number of bytes consumed by internal ARC structures necessary
629          * for tracking purposes; these structures are not actually
630          * backed by ARC buffers. This includes arc_buf_hdr_t structures
631          * (allocated via arc_buf_hdr_t_full and arc_buf_hdr_t_l2only
632          * caches), and arc_buf_t structures (allocated via arc_buf_t
633          * cache).
634          * Not updated directly; only synced in arc_kstat_update.
635          */
636         kstat_named_t arcstat_hdr_size;
637         /*
638          * Number of bytes consumed by ARC buffers of type equal to
639          * ARC_BUFC_DATA. This is generally consumed by buffers backing
640          * on disk user data (e.g. plain file contents).
641          * Not updated directly; only synced in arc_kstat_update.
642          */
643         kstat_named_t arcstat_data_size;
644         /*
645          * Number of bytes consumed by ARC buffers of type equal to
646          * ARC_BUFC_METADATA. This is generally consumed by buffers
647          * backing on disk data that is used for internal ZFS
648          * structures (e.g. ZAP, dnode, indirect blocks, etc).
649          * Not updated directly; only synced in arc_kstat_update.
650          */
651         kstat_named_t arcstat_metadata_size;
652         /*
653          * Number of bytes consumed by dmu_buf_impl_t objects.
654          */
655         kstat_named_t arcstat_dbuf_size;
656         /*
657          * Number of bytes consumed by dnode_t objects.
658          */
659         kstat_named_t arcstat_dnode_size;
660         /*
661          * Number of bytes consumed by bonus buffers.
662          */
663         kstat_named_t arcstat_bonus_size;
664         /*
665          * Total number of bytes consumed by ARC buffers residing in the
666          * arc_anon state. This includes *all* buffers in the arc_anon
667          * state; e.g. data, metadata, evictable, and unevictable buffers
668          * are all included in this value.
669          * Not updated directly; only synced in arc_kstat_update.
670          */
671         kstat_named_t arcstat_anon_size;
672         /*
673          * Number of bytes consumed by ARC buffers that meet the
674          * following criteria: backing buffers of type ARC_BUFC_DATA,
675          * residing in the arc_anon state, and are eligible for eviction
676          * (e.g. have no outstanding holds on the buffer).
677          * Not updated directly; only synced in arc_kstat_update.
678          */
679         kstat_named_t arcstat_anon_evictable_data;
680         /*
681          * Number of bytes consumed by ARC buffers that meet the
682          * following criteria: backing buffers of type ARC_BUFC_METADATA,
683          * residing in the arc_anon state, and are eligible for eviction
684          * (e.g. have no outstanding holds on the buffer).
685          * Not updated directly; only synced in arc_kstat_update.
686          */
687         kstat_named_t arcstat_anon_evictable_metadata;
688         /*
689          * Total number of bytes consumed by ARC buffers residing in the
690          * arc_mru state. This includes *all* buffers in the arc_mru
691          * state; e.g. data, metadata, evictable, and unevictable buffers
692          * are all included in this value.
693          * Not updated directly; only synced in arc_kstat_update.
694          */
695         kstat_named_t arcstat_mru_size;
696         /*
697          * Number of bytes consumed by ARC buffers that meet the
698          * following criteria: backing buffers of type ARC_BUFC_DATA,
699          * residing in the arc_mru state, and are eligible for eviction
700          * (e.g. have no outstanding holds on the buffer).
701          * Not updated directly; only synced in arc_kstat_update.
702          */
703         kstat_named_t arcstat_mru_evictable_data;
704         /*
705          * Number of bytes consumed by ARC buffers that meet the
706          * following criteria: backing buffers of type ARC_BUFC_METADATA,
707          * residing in the arc_mru state, and are eligible for eviction
708          * (e.g. have no outstanding holds on the buffer).
709          * Not updated directly; only synced in arc_kstat_update.
710          */
711         kstat_named_t arcstat_mru_evictable_metadata;
712         /*
713          * Total number of bytes that *would have been* consumed by ARC
714          * buffers in the arc_mru_ghost state. The key thing to note
715          * here, is the fact that this size doesn't actually indicate
716          * RAM consumption. The ghost lists only consist of headers and
717          * don't actually have ARC buffers linked off of these headers.
718          * Thus, *if* the headers had associated ARC buffers, these
719          * buffers *would have* consumed this number of bytes.
720          * Not updated directly; only synced in arc_kstat_update.
721          */
722         kstat_named_t arcstat_mru_ghost_size;
723         /*
724          * Number of bytes that *would have been* consumed by ARC
725          * buffers that are eligible for eviction, of type
726          * ARC_BUFC_DATA, and linked off the arc_mru_ghost state.
727          * Not updated directly; only synced in arc_kstat_update.
728          */
729         kstat_named_t arcstat_mru_ghost_evictable_data;
730         /*
731          * Number of bytes that *would have been* consumed by ARC
732          * buffers that are eligible for eviction, of type
733          * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
734          * Not updated directly; only synced in arc_kstat_update.
735          */
736         kstat_named_t arcstat_mru_ghost_evictable_metadata;
737         /*
738          * Total number of bytes consumed by ARC buffers residing in the
739          * arc_mfu state. This includes *all* buffers in the arc_mfu
740          * state; e.g. data, metadata, evictable, and unevictable buffers
741          * are all included in this value.
742          * Not updated directly; only synced in arc_kstat_update.
743          */
744         kstat_named_t arcstat_mfu_size;
745         /*
746          * Number of bytes consumed by ARC buffers that are eligible for
747          * eviction, of type ARC_BUFC_DATA, and reside in the arc_mfu
748          * state.
749          * Not updated directly; only synced in arc_kstat_update.
750          */
751         kstat_named_t arcstat_mfu_evictable_data;
752         /*
753          * Number of bytes consumed by ARC buffers that are eligible for
754          * eviction, of type ARC_BUFC_METADATA, and reside in the
755          * arc_mfu state.
756          * Not updated directly; only synced in arc_kstat_update.
757          */
758         kstat_named_t arcstat_mfu_evictable_metadata;
759         /*
760          * Total number of bytes that *would have been* consumed by ARC
761          * buffers in the arc_mfu_ghost state. See the comment above
762          * arcstat_mru_ghost_size for more details.
763          * Not updated directly; only synced in arc_kstat_update.
764          */
765         kstat_named_t arcstat_mfu_ghost_size;
766         /*
767          * Number of bytes that *would have been* consumed by ARC
768          * buffers that are eligible for eviction, of type
769          * ARC_BUFC_DATA, and linked off the arc_mfu_ghost state.
770          * Not updated directly; only synced in arc_kstat_update.
771          */
772         kstat_named_t arcstat_mfu_ghost_evictable_data;
773         /*
774          * Number of bytes that *would have been* consumed by ARC
775          * buffers that are eligible for eviction, of type
776          * ARC_BUFC_METADATA, and linked off the arc_mru_ghost state.
777          * Not updated directly; only synced in arc_kstat_update.
778          */
779         kstat_named_t arcstat_mfu_ghost_evictable_metadata;
780         kstat_named_t arcstat_l2_hits;
781         kstat_named_t arcstat_l2_misses;
782         kstat_named_t arcstat_l2_feeds;
783         kstat_named_t arcstat_l2_rw_clash;
784         kstat_named_t arcstat_l2_read_bytes;
785         kstat_named_t arcstat_l2_write_bytes;
786         kstat_named_t arcstat_l2_writes_sent;
787         kstat_named_t arcstat_l2_writes_done;
788         kstat_named_t arcstat_l2_writes_error;
789         kstat_named_t arcstat_l2_writes_lock_retry;
790         kstat_named_t arcstat_l2_evict_lock_retry;
791         kstat_named_t arcstat_l2_evict_reading;
792         kstat_named_t arcstat_l2_evict_l1cached;
793         kstat_named_t arcstat_l2_free_on_write;
794         kstat_named_t arcstat_l2_abort_lowmem;
795         kstat_named_t arcstat_l2_cksum_bad;
796         kstat_named_t arcstat_l2_io_error;
797         kstat_named_t arcstat_l2_lsize;
798         kstat_named_t arcstat_l2_psize;
799         /* Not updated directly; only synced in arc_kstat_update. */
800         kstat_named_t arcstat_l2_hdr_size;
801         kstat_named_t arcstat_l2_write_trylock_fail;
802         kstat_named_t arcstat_l2_write_passed_headroom;
803         kstat_named_t arcstat_l2_write_spa_mismatch;
804         kstat_named_t arcstat_l2_write_in_l2;
805         kstat_named_t arcstat_l2_write_hdr_io_in_progress;
806         kstat_named_t arcstat_l2_write_not_cacheable;
807         kstat_named_t arcstat_l2_write_full;
808         kstat_named_t arcstat_l2_write_buffer_iter;
809         kstat_named_t arcstat_l2_write_pios;
810         kstat_named_t arcstat_l2_write_buffer_bytes_scanned;
811         kstat_named_t arcstat_l2_write_buffer_list_iter;
812         kstat_named_t arcstat_l2_write_buffer_list_null_iter;
813         kstat_named_t arcstat_memory_throttle_count;
814         kstat_named_t arcstat_memory_direct_count;
815         kstat_named_t arcstat_memory_indirect_count;
816         kstat_named_t arcstat_memory_all_bytes;
817         kstat_named_t arcstat_memory_free_bytes;
818         kstat_named_t arcstat_memory_available_bytes;
819         kstat_named_t arcstat_no_grow;
820         kstat_named_t arcstat_tempreserve;
821         kstat_named_t arcstat_loaned_bytes;
822         kstat_named_t arcstat_prune;
823         /* Not updated directly; only synced in arc_kstat_update. */
824         kstat_named_t arcstat_meta_used;
825         kstat_named_t arcstat_meta_limit;
826         kstat_named_t arcstat_dnode_limit;
827         kstat_named_t arcstat_meta_max;
828         kstat_named_t arcstat_meta_min;
829         kstat_named_t arcstat_async_upgrade_sync;
830         kstat_named_t arcstat_demand_hit_predictive_prefetch;
831         kstat_named_t arcstat_demand_hit_prescient_prefetch;
832 } arc_stats_t;
833
834 static arc_stats_t arc_stats = {
835         { "hits",                       KSTAT_DATA_UINT64 },
836         { "misses",                     KSTAT_DATA_UINT64 },
837         { "demand_data_hits",           KSTAT_DATA_UINT64 },
838         { "demand_data_misses",         KSTAT_DATA_UINT64 },
839         { "demand_metadata_hits",       KSTAT_DATA_UINT64 },
840         { "demand_metadata_misses",     KSTAT_DATA_UINT64 },
841         { "prefetch_data_hits",         KSTAT_DATA_UINT64 },
842         { "prefetch_data_misses",       KSTAT_DATA_UINT64 },
843         { "prefetch_metadata_hits",     KSTAT_DATA_UINT64 },
844         { "prefetch_metadata_misses",   KSTAT_DATA_UINT64 },
845         { "mru_hits",                   KSTAT_DATA_UINT64 },
846         { "mru_ghost_hits",             KSTAT_DATA_UINT64 },
847         { "mfu_hits",                   KSTAT_DATA_UINT64 },
848         { "mfu_ghost_hits",             KSTAT_DATA_UINT64 },
849         { "allocated",                  KSTAT_DATA_UINT64 },
850         { "deleted",                    KSTAT_DATA_UINT64 },
851         { "mutex_miss",                 KSTAT_DATA_UINT64 },
852         { "access_skip",                KSTAT_DATA_UINT64 },
853         { "evict_skip",                 KSTAT_DATA_UINT64 },
854         { "evict_not_enough",           KSTAT_DATA_UINT64 },
855         { "evict_l2_cached",            KSTAT_DATA_UINT64 },
856         { "evict_l2_eligible",          KSTAT_DATA_UINT64 },
857         { "evict_l2_ineligible",        KSTAT_DATA_UINT64 },
858         { "evict_l2_skip",              KSTAT_DATA_UINT64 },
859         { "hash_elements",              KSTAT_DATA_UINT64 },
860         { "hash_elements_max",          KSTAT_DATA_UINT64 },
861         { "hash_collisions",            KSTAT_DATA_UINT64 },
862         { "hash_chains",                KSTAT_DATA_UINT64 },
863         { "hash_chain_max",             KSTAT_DATA_UINT64 },
864         { "p",                          KSTAT_DATA_UINT64 },
865         { "c",                          KSTAT_DATA_UINT64 },
866         { "c_min",                      KSTAT_DATA_UINT64 },
867         { "c_max",                      KSTAT_DATA_UINT64 },
868         { "size",                       KSTAT_DATA_UINT64 },
869         { "compressed_size",            KSTAT_DATA_UINT64 },
870         { "uncompressed_size",          KSTAT_DATA_UINT64 },
871         { "overhead_size",              KSTAT_DATA_UINT64 },
872         { "hdr_size",                   KSTAT_DATA_UINT64 },
873         { "data_size",                  KSTAT_DATA_UINT64 },
874         { "metadata_size",              KSTAT_DATA_UINT64 },
875         { "dbuf_size",                  KSTAT_DATA_UINT64 },
876         { "dnode_size",                 KSTAT_DATA_UINT64 },
877         { "bonus_size",                 KSTAT_DATA_UINT64 },
878         { "anon_size",                  KSTAT_DATA_UINT64 },
879         { "anon_evictable_data",        KSTAT_DATA_UINT64 },
880         { "anon_evictable_metadata",    KSTAT_DATA_UINT64 },
881         { "mru_size",                   KSTAT_DATA_UINT64 },
882         { "mru_evictable_data",         KSTAT_DATA_UINT64 },
883         { "mru_evictable_metadata",     KSTAT_DATA_UINT64 },
884         { "mru_ghost_size",             KSTAT_DATA_UINT64 },
885         { "mru_ghost_evictable_data",   KSTAT_DATA_UINT64 },
886         { "mru_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
887         { "mfu_size",                   KSTAT_DATA_UINT64 },
888         { "mfu_evictable_data",         KSTAT_DATA_UINT64 },
889         { "mfu_evictable_metadata",     KSTAT_DATA_UINT64 },
890         { "mfu_ghost_size",             KSTAT_DATA_UINT64 },
891         { "mfu_ghost_evictable_data",   KSTAT_DATA_UINT64 },
892         { "mfu_ghost_evictable_metadata", KSTAT_DATA_UINT64 },
893         { "l2_hits",                    KSTAT_DATA_UINT64 },
894         { "l2_misses",                  KSTAT_DATA_UINT64 },
895         { "l2_feeds",                   KSTAT_DATA_UINT64 },
896         { "l2_rw_clash",                KSTAT_DATA_UINT64 },
897         { "l2_read_bytes",              KSTAT_DATA_UINT64 },
898         { "l2_write_bytes",             KSTAT_DATA_UINT64 },
899         { "l2_writes_sent",             KSTAT_DATA_UINT64 },
900         { "l2_writes_done",             KSTAT_DATA_UINT64 },
901         { "l2_writes_error",            KSTAT_DATA_UINT64 },
902         { "l2_writes_lock_retry",       KSTAT_DATA_UINT64 },
903         { "l2_evict_lock_retry",        KSTAT_DATA_UINT64 },
904         { "l2_evict_reading",           KSTAT_DATA_UINT64 },
905         { "l2_evict_l1cached",          KSTAT_DATA_UINT64 },
906         { "l2_free_on_write",           KSTAT_DATA_UINT64 },
907         { "l2_abort_lowmem",            KSTAT_DATA_UINT64 },
908         { "l2_cksum_bad",               KSTAT_DATA_UINT64 },
909         { "l2_io_error",                KSTAT_DATA_UINT64 },
910         { "l2_size",                    KSTAT_DATA_UINT64 },
911         { "l2_asize",                   KSTAT_DATA_UINT64 },
912         { "l2_hdr_size",                KSTAT_DATA_UINT64 },
913         { "l2_write_trylock_fail",      KSTAT_DATA_UINT64 },
914         { "l2_write_passed_headroom",   KSTAT_DATA_UINT64 },
915         { "l2_write_spa_mismatch",      KSTAT_DATA_UINT64 },
916         { "l2_write_in_l2",             KSTAT_DATA_UINT64 },
917         { "l2_write_io_in_progress",    KSTAT_DATA_UINT64 },
918         { "l2_write_not_cacheable",     KSTAT_DATA_UINT64 },
919         { "l2_write_full",              KSTAT_DATA_UINT64 },
920         { "l2_write_buffer_iter",       KSTAT_DATA_UINT64 },
921         { "l2_write_pios",              KSTAT_DATA_UINT64 },
922         { "l2_write_buffer_bytes_scanned", KSTAT_DATA_UINT64 },
923         { "l2_write_buffer_list_iter",  KSTAT_DATA_UINT64 },
924         { "l2_write_buffer_list_null_iter", KSTAT_DATA_UINT64 },
925         { "memory_throttle_count",      KSTAT_DATA_UINT64 },
926         { "memory_direct_count",        KSTAT_DATA_UINT64 },
927         { "memory_indirect_count",      KSTAT_DATA_UINT64 },
928         { "memory_all_bytes",           KSTAT_DATA_UINT64 },
929         { "memory_free_bytes",          KSTAT_DATA_UINT64 },
930         { "memory_available_bytes",     KSTAT_DATA_UINT64 },
931         { "arc_no_grow",                KSTAT_DATA_UINT64 },
932         { "arc_tempreserve",            KSTAT_DATA_UINT64 },
933         { "arc_loaned_bytes",           KSTAT_DATA_UINT64 },
934         { "arc_prune",                  KSTAT_DATA_UINT64 },
935         { "arc_meta_used",              KSTAT_DATA_UINT64 },
936         { "arc_meta_limit",             KSTAT_DATA_UINT64 },
937         { "arc_dnode_limit",            KSTAT_DATA_UINT64 },
938         { "arc_meta_max",               KSTAT_DATA_UINT64 },
939         { "arc_meta_min",               KSTAT_DATA_UINT64 },
940         { "async_upgrade_sync",         KSTAT_DATA_UINT64 },
941         { "demand_hit_predictive_prefetch", KSTAT_DATA_UINT64 },
942         { "demand_hit_prescient_prefetch", KSTAT_DATA_UINT64 },
943 };
944
945 #define ARCSTAT(stat)   (arc_stats.stat.value.ui64)
946
947 #define ARCSTAT_INCR(stat, val) \
948         atomic_add_64(&arc_stats.stat.value.ui64, (val))
949
950 #define ARCSTAT_BUMP(stat)      ARCSTAT_INCR(stat, 1)
951 #define ARCSTAT_BUMPDOWN(stat)  ARCSTAT_INCR(stat, -1)
952
953 #define ARCSTAT_MAX(stat, val) {                                        \
954         uint64_t m;                                                     \
955         while ((val) > (m = arc_stats.stat.value.ui64) &&               \
956             (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
957                 continue;                                               \
958 }
959
960 #define ARCSTAT_MAXSTAT(stat) \
961         ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
962
963 /*
964  * We define a macro to allow ARC hits/misses to be easily broken down by
965  * two separate conditions, giving a total of four different subtypes for
966  * each of hits and misses (so eight statistics total).
967  */
968 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
969         if (cond1) {                                                    \
970                 if (cond2) {                                            \
971                         ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
972                 } else {                                                \
973                         ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
974                 }                                                       \
975         } else {                                                        \
976                 if (cond2) {                                            \
977                         ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
978                 } else {                                                \
979                         ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
980                 }                                                       \
981         }
982
983 kstat_t                 *arc_ksp;
984 static arc_state_t      *arc_anon;
985 static arc_state_t      *arc_mru;
986 static arc_state_t      *arc_mru_ghost;
987 static arc_state_t      *arc_mfu;
988 static arc_state_t      *arc_mfu_ghost;
989 static arc_state_t      *arc_l2c_only;
990
991 /*
992  * There are several ARC variables that are critical to export as kstats --
993  * but we don't want to have to grovel around in the kstat whenever we wish to
994  * manipulate them.  For these variables, we therefore define them to be in
995  * terms of the statistic variable.  This assures that we are not introducing
996  * the possibility of inconsistency by having shadow copies of the variables,
997  * while still allowing the code to be readable.
998  */
999 #define arc_p           ARCSTAT(arcstat_p)      /* target size of MRU */
1000 #define arc_c           ARCSTAT(arcstat_c)      /* target size of cache */
1001 #define arc_c_min       ARCSTAT(arcstat_c_min)  /* min target cache size */
1002 #define arc_c_max       ARCSTAT(arcstat_c_max)  /* max target cache size */
1003 #define arc_meta_limit  ARCSTAT(arcstat_meta_limit) /* max size for metadata */
1004 #define arc_dnode_limit ARCSTAT(arcstat_dnode_limit) /* max size for dnodes */
1005 #define arc_meta_min    ARCSTAT(arcstat_meta_min) /* min size for metadata */
1006 #define arc_meta_max    ARCSTAT(arcstat_meta_max) /* max size of metadata */
1007 #define arc_dbuf_size   ARCSTAT(arcstat_dbuf_size) /* dbuf metadata */
1008 #define arc_dnode_size  ARCSTAT(arcstat_dnode_size) /* dnode metadata */
1009 #define arc_bonus_size  ARCSTAT(arcstat_bonus_size) /* bonus buffer metadata */
1010
1011 /* compressed size of entire arc */
1012 #define arc_compressed_size     ARCSTAT(arcstat_compressed_size)
1013 /* uncompressed size of entire arc */
1014 #define arc_uncompressed_size   ARCSTAT(arcstat_uncompressed_size)
1015 /* number of bytes in the arc from arc_buf_t's */
1016 #define arc_overhead_size       ARCSTAT(arcstat_overhead_size)
1017
1018 /*
1019  * There are also some ARC variables that we want to export, but that are
1020  * updated so often that having the canonical representation be the statistic
1021  * variable causes a performance bottleneck. We want to use aggsum_t's for these
1022  * instead, but still be able to export the kstat in the same way as before.
1023  * The solution is to always use the aggsum version, except in the kstat update
1024  * callback.
1025  */
1026 aggsum_t arc_size;
1027 aggsum_t arc_meta_used;
1028 aggsum_t astat_data_size;
1029 aggsum_t astat_metadata_size;
1030 aggsum_t astat_hdr_size;
1031 aggsum_t astat_bonus_size;
1032 aggsum_t astat_dnode_size;
1033 aggsum_t astat_dbuf_size;
1034 aggsum_t astat_l2_hdr_size;
1035
1036 static list_t arc_prune_list;
1037 static kmutex_t arc_prune_mtx;
1038 static taskq_t *arc_prune_taskq;
1039
1040 static int              arc_no_grow;    /* Don't try to grow cache size */
1041 static uint64_t         arc_tempreserve;
1042 static uint64_t         arc_loaned_bytes;
1043
1044 typedef struct arc_callback arc_callback_t;
1045
1046 struct arc_callback {
1047         void                    *acb_private;
1048         arc_read_done_func_t    *acb_done;
1049         arc_buf_t               *acb_buf;
1050         boolean_t               acb_compressed;
1051         zio_t                   *acb_zio_dummy;
1052         zio_t                   *acb_zio_head;
1053         arc_callback_t          *acb_next;
1054 };
1055
1056 typedef struct arc_write_callback arc_write_callback_t;
1057
1058 struct arc_write_callback {
1059         void                    *awcb_private;
1060         arc_write_done_func_t   *awcb_ready;
1061         arc_write_done_func_t   *awcb_children_ready;
1062         arc_write_done_func_t   *awcb_physdone;
1063         arc_write_done_func_t   *awcb_done;
1064         arc_buf_t               *awcb_buf;
1065 };
1066
1067 /*
1068  * ARC buffers are separated into multiple structs as a memory saving measure:
1069  *   - Common fields struct, always defined, and embedded within it:
1070  *       - L2-only fields, always allocated but undefined when not in L2ARC
1071  *       - L1-only fields, only allocated when in L1ARC
1072  *
1073  *           Buffer in L1                     Buffer only in L2
1074  *    +------------------------+          +------------------------+
1075  *    | arc_buf_hdr_t          |          | arc_buf_hdr_t          |
1076  *    |                        |          |                        |
1077  *    |                        |          |                        |
1078  *    |                        |          |                        |
1079  *    +------------------------+          +------------------------+
1080  *    | l2arc_buf_hdr_t        |          | l2arc_buf_hdr_t        |
1081  *    | (undefined if L1-only) |          |                        |
1082  *    +------------------------+          +------------------------+
1083  *    | l1arc_buf_hdr_t        |
1084  *    |                        |
1085  *    |                        |
1086  *    |                        |
1087  *    |                        |
1088  *    +------------------------+
1089  *
1090  * Because it's possible for the L2ARC to become extremely large, we can wind
1091  * up eating a lot of memory in L2ARC buffer headers, so the size of a header
1092  * is minimized by only allocating the fields necessary for an L1-cached buffer
1093  * when a header is actually in the L1 cache. The sub-headers (l1arc_buf_hdr and
1094  * l2arc_buf_hdr) are embedded rather than allocated separately to save a couple
1095  * words in pointers. arc_hdr_realloc() is used to switch a header between
1096  * these two allocation states.
1097  */
1098 typedef struct l1arc_buf_hdr {
1099         kmutex_t                b_freeze_lock;
1100         zio_cksum_t             *b_freeze_cksum;
1101 #ifdef ZFS_DEBUG
1102         /*
1103          * Used for debugging with kmem_flags - by allocating and freeing
1104          * b_thawed when the buffer is thawed, we get a record of the stack
1105          * trace that thawed it.
1106          */
1107         void                    *b_thawed;
1108 #endif
1109
1110         arc_buf_t               *b_buf;
1111         uint32_t                b_bufcnt;
1112         /* for waiting on writes to complete */
1113         kcondvar_t              b_cv;
1114         uint8_t                 b_byteswap;
1115
1116         /* protected by arc state mutex */
1117         arc_state_t             *b_state;
1118         multilist_node_t        b_arc_node;
1119
1120         /* updated atomically */
1121         clock_t                 b_arc_access;
1122         uint32_t                b_mru_hits;
1123         uint32_t                b_mru_ghost_hits;
1124         uint32_t                b_mfu_hits;
1125         uint32_t                b_mfu_ghost_hits;
1126         uint32_t                b_l2_hits;
1127
1128         /* self protecting */
1129         refcount_t              b_refcnt;
1130
1131         arc_callback_t          *b_acb;
1132         abd_t                   *b_pabd;
1133 } l1arc_buf_hdr_t;
1134
1135 typedef struct l2arc_dev l2arc_dev_t;
1136
1137 typedef struct l2arc_buf_hdr {
1138         /* protected by arc_buf_hdr mutex */
1139         l2arc_dev_t             *b_dev;         /* L2ARC device */
1140         uint64_t                b_daddr;        /* disk address, offset byte */
1141         uint32_t                b_hits;
1142
1143         list_node_t             b_l2node;
1144 } l2arc_buf_hdr_t;
1145
1146 struct arc_buf_hdr {
1147         /* protected by hash lock */
1148         dva_t                   b_dva;
1149         uint64_t                b_birth;
1150
1151         arc_buf_contents_t      b_type;
1152         arc_buf_hdr_t           *b_hash_next;
1153         arc_flags_t             b_flags;
1154
1155         /*
1156          * This field stores the size of the data buffer after
1157          * compression, and is set in the arc's zio completion handlers.
1158          * It is in units of SPA_MINBLOCKSIZE (e.g. 1 == 512 bytes).
1159          *
1160          * While the block pointers can store up to 32MB in their psize
1161          * field, we can only store up to 32MB minus 512B. This is due
1162          * to the bp using a bias of 1, whereas we use a bias of 0 (i.e.
1163          * a field of zeros represents 512B in the bp). We can't use a
1164          * bias of 1 since we need to reserve a psize of zero, here, to
1165          * represent holes and embedded blocks.
1166          *
1167          * This isn't a problem in practice, since the maximum size of a
1168          * buffer is limited to 16MB, so we never need to store 32MB in
1169          * this field. Even in the upstream illumos code base, the
1170          * maximum size of a buffer is limited to 16MB.
1171          */
1172         uint16_t                b_psize;
1173
1174         /*
1175          * This field stores the size of the data buffer before
1176          * compression, and cannot change once set. It is in units
1177          * of SPA_MINBLOCKSIZE (e.g. 2 == 1024 bytes)
1178          */
1179         uint16_t                b_lsize;        /* immutable */
1180         uint64_t                b_spa;          /* immutable */
1181
1182         /* L2ARC fields. Undefined when not in L2ARC. */
1183         l2arc_buf_hdr_t         b_l2hdr;
1184         /* L1ARC fields. Undefined when in l2arc_only state */
1185         l1arc_buf_hdr_t         b_l1hdr;
1186 };
1187
1188 #if defined(__FreeBSD__) && defined(_KERNEL)
1189 static int
1190 sysctl_vfs_zfs_arc_meta_limit(SYSCTL_HANDLER_ARGS)
1191 {
1192         uint64_t val;
1193         int err;
1194
1195         val = arc_meta_limit;
1196         err = sysctl_handle_64(oidp, &val, 0, req);
1197         if (err != 0 || req->newptr == NULL)
1198                 return (err);
1199
1200         if (val <= 0 || val > arc_c_max)
1201                 return (EINVAL);
1202
1203         arc_meta_limit = val;
1204         return (0);
1205 }
1206
1207 static int
1208 sysctl_vfs_zfs_arc_no_grow_shift(SYSCTL_HANDLER_ARGS)
1209 {
1210         uint32_t val;
1211         int err;
1212
1213         val = arc_no_grow_shift;
1214         err = sysctl_handle_32(oidp, &val, 0, req);
1215         if (err != 0 || req->newptr == NULL)
1216                 return (err);
1217
1218         if (val >= arc_shrink_shift)
1219                 return (EINVAL);
1220
1221         arc_no_grow_shift = val;
1222         return (0);
1223 }
1224
1225 static int
1226 sysctl_vfs_zfs_arc_max(SYSCTL_HANDLER_ARGS)
1227 {
1228         uint64_t val;
1229         int err;
1230
1231         val = zfs_arc_max;
1232         err = sysctl_handle_64(oidp, &val, 0, req);
1233         if (err != 0 || req->newptr == NULL)
1234                 return (err);
1235
1236         if (zfs_arc_max == 0) {
1237                 /* Loader tunable so blindly set */
1238                 zfs_arc_max = val;
1239                 return (0);
1240         }
1241
1242         if (val < arc_abs_min || val > kmem_size())
1243                 return (EINVAL);
1244         if (val < arc_c_min)
1245                 return (EINVAL);
1246         if (zfs_arc_meta_limit > 0 && val < zfs_arc_meta_limit)
1247                 return (EINVAL);
1248
1249         arc_c_max = val;
1250
1251         arc_c = arc_c_max;
1252         arc_p = (arc_c >> 1);
1253
1254         if (zfs_arc_meta_limit == 0) {
1255                 /* limit meta-data to 1/4 of the arc capacity */
1256                 arc_meta_limit = arc_c_max / 4;
1257         }
1258
1259         /* if kmem_flags are set, lets try to use less memory */
1260         if (kmem_debugging())
1261                 arc_c = arc_c / 2;
1262
1263         zfs_arc_max = arc_c;
1264
1265         return (0);
1266 }
1267
1268 static int
1269 sysctl_vfs_zfs_arc_min(SYSCTL_HANDLER_ARGS)
1270 {
1271         uint64_t val;
1272         int err;
1273
1274         val = zfs_arc_min;
1275         err = sysctl_handle_64(oidp, &val, 0, req);
1276         if (err != 0 || req->newptr == NULL)
1277                 return (err);
1278
1279         if (zfs_arc_min == 0) {
1280                 /* Loader tunable so blindly set */
1281                 zfs_arc_min = val;
1282                 return (0);
1283         }
1284
1285         if (val < arc_abs_min || val > arc_c_max)
1286                 return (EINVAL);
1287
1288         arc_c_min = val;
1289
1290         if (zfs_arc_meta_min == 0)
1291                 arc_meta_min = arc_c_min / 2;
1292
1293         if (arc_c < arc_c_min)
1294                 arc_c = arc_c_min;
1295
1296         zfs_arc_min = arc_c_min;
1297
1298         return (0);
1299 }
1300 #endif
1301
1302 #define GHOST_STATE(state)      \
1303         ((state) == arc_mru_ghost || (state) == arc_mfu_ghost ||        \
1304         (state) == arc_l2c_only)
1305
1306 #define HDR_IN_HASH_TABLE(hdr)  ((hdr)->b_flags & ARC_FLAG_IN_HASH_TABLE)
1307 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS)
1308 #define HDR_IO_ERROR(hdr)       ((hdr)->b_flags & ARC_FLAG_IO_ERROR)
1309 #define HDR_PREFETCH(hdr)       ((hdr)->b_flags & ARC_FLAG_PREFETCH)
1310 #define HDR_PRESCIENT_PREFETCH(hdr)     \
1311         ((hdr)->b_flags & ARC_FLAG_PRESCIENT_PREFETCH)
1312 #define HDR_COMPRESSION_ENABLED(hdr)    \
1313         ((hdr)->b_flags & ARC_FLAG_COMPRESSED_ARC)
1314
1315 #define HDR_L2CACHE(hdr)        ((hdr)->b_flags & ARC_FLAG_L2CACHE)
1316 #define HDR_L2_READING(hdr)     \
1317         (((hdr)->b_flags & ARC_FLAG_IO_IN_PROGRESS) &&  \
1318         ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR))
1319 #define HDR_L2_WRITING(hdr)     ((hdr)->b_flags & ARC_FLAG_L2_WRITING)
1320 #define HDR_L2_EVICTED(hdr)     ((hdr)->b_flags & ARC_FLAG_L2_EVICTED)
1321 #define HDR_L2_WRITE_HEAD(hdr)  ((hdr)->b_flags & ARC_FLAG_L2_WRITE_HEAD)
1322 #define HDR_SHARED_DATA(hdr)    ((hdr)->b_flags & ARC_FLAG_SHARED_DATA)
1323
1324 #define HDR_ISTYPE_METADATA(hdr)        \
1325         ((hdr)->b_flags & ARC_FLAG_BUFC_METADATA)
1326 #define HDR_ISTYPE_DATA(hdr)    (!HDR_ISTYPE_METADATA(hdr))
1327
1328 #define HDR_HAS_L1HDR(hdr)      ((hdr)->b_flags & ARC_FLAG_HAS_L1HDR)
1329 #define HDR_HAS_L2HDR(hdr)      ((hdr)->b_flags & ARC_FLAG_HAS_L2HDR)
1330
1331 /* For storing compression mode in b_flags */
1332 #define HDR_COMPRESS_OFFSET     (highbit64(ARC_FLAG_COMPRESS_0) - 1)
1333
1334 #define HDR_GET_COMPRESS(hdr)   ((enum zio_compress)BF32_GET((hdr)->b_flags, \
1335         HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS))
1336 #define HDR_SET_COMPRESS(hdr, cmp) BF32_SET((hdr)->b_flags, \
1337         HDR_COMPRESS_OFFSET, SPA_COMPRESSBITS, (cmp));
1338
1339 #define ARC_BUF_LAST(buf)       ((buf)->b_next == NULL)
1340 #define ARC_BUF_SHARED(buf)     ((buf)->b_flags & ARC_BUF_FLAG_SHARED)
1341 #define ARC_BUF_COMPRESSED(buf) ((buf)->b_flags & ARC_BUF_FLAG_COMPRESSED)
1342
1343 /*
1344  * Other sizes
1345  */
1346
1347 #define HDR_FULL_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
1348 #define HDR_L2ONLY_SIZE ((int64_t)offsetof(arc_buf_hdr_t, b_l1hdr))
1349
1350 /*
1351  * Hash table routines
1352  */
1353
1354 #define HT_LOCK_PAD     CACHE_LINE_SIZE
1355
1356 struct ht_lock {
1357         kmutex_t        ht_lock;
1358 #ifdef _KERNEL
1359         unsigned char   pad[(HT_LOCK_PAD - sizeof (kmutex_t))];
1360 #endif
1361 };
1362
1363 #define BUF_LOCKS 256
1364 typedef struct buf_hash_table {
1365         uint64_t ht_mask;
1366         arc_buf_hdr_t **ht_table;
1367         struct ht_lock ht_locks[BUF_LOCKS] __aligned(CACHE_LINE_SIZE);
1368 } buf_hash_table_t;
1369
1370 static buf_hash_table_t buf_hash_table;
1371
1372 #define BUF_HASH_INDEX(spa, dva, birth) \
1373         (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
1374 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
1375 #define BUF_HASH_LOCK(idx)      (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
1376 #define HDR_LOCK(hdr) \
1377         (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
1378
1379 uint64_t zfs_crc64_table[256];
1380
1381 /*
1382  * Level 2 ARC
1383  */
1384
1385 #define L2ARC_WRITE_SIZE        (8 * 1024 * 1024)       /* initial write max */
1386 #define L2ARC_HEADROOM          2                       /* num of writes */
1387 /*
1388  * If we discover during ARC scan any buffers to be compressed, we boost
1389  * our headroom for the next scanning cycle by this percentage multiple.
1390  */
1391 #define L2ARC_HEADROOM_BOOST    200
1392 #define L2ARC_FEED_SECS         1               /* caching interval secs */
1393 #define L2ARC_FEED_MIN_MS       200             /* min caching interval ms */
1394
1395 #define l2arc_writes_sent       ARCSTAT(arcstat_l2_writes_sent)
1396 #define l2arc_writes_done       ARCSTAT(arcstat_l2_writes_done)
1397
1398 /* L2ARC Performance Tunables */
1399 uint64_t l2arc_write_max = L2ARC_WRITE_SIZE;    /* default max write size */
1400 uint64_t l2arc_write_boost = L2ARC_WRITE_SIZE;  /* extra write during warmup */
1401 uint64_t l2arc_headroom = L2ARC_HEADROOM;       /* number of dev writes */
1402 uint64_t l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
1403 uint64_t l2arc_feed_secs = L2ARC_FEED_SECS;     /* interval seconds */
1404 uint64_t l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval milliseconds */
1405 boolean_t l2arc_noprefetch = B_TRUE;            /* don't cache prefetch bufs */
1406 boolean_t l2arc_feed_again = B_TRUE;            /* turbo warmup */
1407 boolean_t l2arc_norw = B_TRUE;                  /* no reads during writes */
1408
1409 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_max, CTLFLAG_RW,
1410     &l2arc_write_max, 0, "max write size");
1411 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_write_boost, CTLFLAG_RW,
1412     &l2arc_write_boost, 0, "extra write during warmup");
1413 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_headroom, CTLFLAG_RW,
1414     &l2arc_headroom, 0, "number of dev writes");
1415 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_secs, CTLFLAG_RW,
1416     &l2arc_feed_secs, 0, "interval seconds");
1417 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2arc_feed_min_ms, CTLFLAG_RW,
1418     &l2arc_feed_min_ms, 0, "min interval milliseconds");
1419
1420 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_noprefetch, CTLFLAG_RW,
1421     &l2arc_noprefetch, 0, "don't cache prefetch bufs");
1422 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_feed_again, CTLFLAG_RW,
1423     &l2arc_feed_again, 0, "turbo warmup");
1424 SYSCTL_INT(_vfs_zfs, OID_AUTO, l2arc_norw, CTLFLAG_RW,
1425     &l2arc_norw, 0, "no reads during writes");
1426
1427 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_size, CTLFLAG_RD,
1428     &ARC_anon.arcs_size.rc_count, 0, "size of anonymous state");
1429 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_metadata_esize, CTLFLAG_RD,
1430     &ARC_anon.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1431     "size of anonymous state");
1432 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, anon_data_esize, CTLFLAG_RD,
1433     &ARC_anon.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1434     "size of anonymous state");
1435
1436 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_size, CTLFLAG_RD,
1437     &ARC_mru.arcs_size.rc_count, 0, "size of mru state");
1438 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_metadata_esize, CTLFLAG_RD,
1439     &ARC_mru.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1440     "size of metadata in mru state");
1441 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_data_esize, CTLFLAG_RD,
1442     &ARC_mru.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1443     "size of data in mru state");
1444
1445 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_size, CTLFLAG_RD,
1446     &ARC_mru_ghost.arcs_size.rc_count, 0, "size of mru ghost state");
1447 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_metadata_esize, CTLFLAG_RD,
1448     &ARC_mru_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1449     "size of metadata in mru ghost state");
1450 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mru_ghost_data_esize, CTLFLAG_RD,
1451     &ARC_mru_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1452     "size of data in mru ghost state");
1453
1454 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_size, CTLFLAG_RD,
1455     &ARC_mfu.arcs_size.rc_count, 0, "size of mfu state");
1456 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_metadata_esize, CTLFLAG_RD,
1457     &ARC_mfu.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1458     "size of metadata in mfu state");
1459 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_data_esize, CTLFLAG_RD,
1460     &ARC_mfu.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1461     "size of data in mfu state");
1462
1463 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_size, CTLFLAG_RD,
1464     &ARC_mfu_ghost.arcs_size.rc_count, 0, "size of mfu ghost state");
1465 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_metadata_esize, CTLFLAG_RD,
1466     &ARC_mfu_ghost.arcs_esize[ARC_BUFC_METADATA].rc_count, 0,
1467     "size of metadata in mfu ghost state");
1468 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, mfu_ghost_data_esize, CTLFLAG_RD,
1469     &ARC_mfu_ghost.arcs_esize[ARC_BUFC_DATA].rc_count, 0,
1470     "size of data in mfu ghost state");
1471
1472 SYSCTL_UQUAD(_vfs_zfs, OID_AUTO, l2c_only_size, CTLFLAG_RD,
1473     &ARC_l2c_only.arcs_size.rc_count, 0, "size of mru state");
1474
1475 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prefetch_ms, CTLFLAG_RW,
1476     &zfs_arc_min_prefetch_ms, 0, "Min life of prefetch block in ms");
1477 SYSCTL_UINT(_vfs_zfs, OID_AUTO, arc_min_prescient_prefetch_ms, CTLFLAG_RW,
1478     &zfs_arc_min_prescient_prefetch_ms, 0, "Min life of prescient prefetched block in ms");
1479
1480 /*
1481  * L2ARC Internals
1482  */
1483 struct l2arc_dev {
1484         vdev_t                  *l2ad_vdev;     /* vdev */
1485         spa_t                   *l2ad_spa;      /* spa */
1486         uint64_t                l2ad_hand;      /* next write location */
1487         uint64_t                l2ad_start;     /* first addr on device */
1488         uint64_t                l2ad_end;       /* last addr on device */
1489         boolean_t               l2ad_first;     /* first sweep through */
1490         boolean_t               l2ad_writing;   /* currently writing */
1491         kmutex_t                l2ad_mtx;       /* lock for buffer list */
1492         list_t                  l2ad_buflist;   /* buffer list */
1493         list_node_t             l2ad_node;      /* device list node */
1494         refcount_t              l2ad_alloc;     /* allocated bytes */
1495 };
1496
1497 static list_t L2ARC_dev_list;                   /* device list */
1498 static list_t *l2arc_dev_list;                  /* device list pointer */
1499 static kmutex_t l2arc_dev_mtx;                  /* device list mutex */
1500 static l2arc_dev_t *l2arc_dev_last;             /* last device used */
1501 static list_t L2ARC_free_on_write;              /* free after write buf list */
1502 static list_t *l2arc_free_on_write;             /* free after write list ptr */
1503 static kmutex_t l2arc_free_on_write_mtx;        /* mutex for list */
1504 static uint64_t l2arc_ndev;                     /* number of devices */
1505
1506 typedef struct l2arc_read_callback {
1507         arc_buf_hdr_t           *l2rcb_hdr;             /* read header */
1508         blkptr_t                l2rcb_bp;               /* original blkptr */
1509         zbookmark_phys_t        l2rcb_zb;               /* original bookmark */
1510         int                     l2rcb_flags;            /* original flags */
1511         abd_t                   *l2rcb_abd;             /* temporary buffer */
1512 } l2arc_read_callback_t;
1513
1514 typedef struct l2arc_write_callback {
1515         l2arc_dev_t     *l2wcb_dev;             /* device info */
1516         arc_buf_hdr_t   *l2wcb_head;            /* head of write buflist */
1517 } l2arc_write_callback_t;
1518
1519 typedef struct l2arc_data_free {
1520         /* protected by l2arc_free_on_write_mtx */
1521         abd_t           *l2df_abd;
1522         size_t          l2df_size;
1523         arc_buf_contents_t l2df_type;
1524         list_node_t     l2df_list_node;
1525 } l2arc_data_free_t;
1526
1527 static kmutex_t l2arc_feed_thr_lock;
1528 static kcondvar_t l2arc_feed_thr_cv;
1529 static uint8_t l2arc_thread_exit;
1530
1531 static abd_t *arc_get_data_abd(arc_buf_hdr_t *, uint64_t, void *);
1532 static void *arc_get_data_buf(arc_buf_hdr_t *, uint64_t, void *);
1533 static void arc_get_data_impl(arc_buf_hdr_t *, uint64_t, void *);
1534 static void arc_free_data_abd(arc_buf_hdr_t *, abd_t *, uint64_t, void *);
1535 static void arc_free_data_buf(arc_buf_hdr_t *, void *, uint64_t, void *);
1536 static void arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag);
1537 static void arc_hdr_free_pabd(arc_buf_hdr_t *);
1538 static void arc_hdr_alloc_pabd(arc_buf_hdr_t *);
1539 static void arc_access(arc_buf_hdr_t *, kmutex_t *);
1540 static boolean_t arc_is_overflowing();
1541 static void arc_buf_watch(arc_buf_t *);
1542 static void arc_prune_async(int64_t);
1543
1544 static arc_buf_contents_t arc_buf_type(arc_buf_hdr_t *);
1545 static uint32_t arc_bufc_to_flags(arc_buf_contents_t);
1546 static inline void arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1547 static inline void arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags);
1548
1549 static boolean_t l2arc_write_eligible(uint64_t, arc_buf_hdr_t *);
1550 static void l2arc_read_done(zio_t *);
1551
1552 static void
1553 l2arc_trim(const arc_buf_hdr_t *hdr)
1554 {
1555         l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
1556
1557         ASSERT(HDR_HAS_L2HDR(hdr));
1558         ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
1559
1560         if (HDR_GET_PSIZE(hdr) != 0) {
1561                 trim_map_free(dev->l2ad_vdev, hdr->b_l2hdr.b_daddr,
1562                     HDR_GET_PSIZE(hdr), 0);
1563         }
1564 }
1565
1566 /*
1567  * We use Cityhash for this. It's fast, and has good hash properties without
1568  * requiring any large static buffers.
1569  */
1570 static uint64_t
1571 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
1572 {
1573         return (cityhash4(spa, dva->dva_word[0], dva->dva_word[1], birth));
1574 }
1575
1576 #define HDR_EMPTY(hdr)                                          \
1577         ((hdr)->b_dva.dva_word[0] == 0 &&                       \
1578         (hdr)->b_dva.dva_word[1] == 0)
1579
1580 #define HDR_EQUAL(spa, dva, birth, hdr)                         \
1581         ((hdr)->b_dva.dva_word[0] == (dva)->dva_word[0]) &&     \
1582         ((hdr)->b_dva.dva_word[1] == (dva)->dva_word[1]) &&     \
1583         ((hdr)->b_birth == birth) && ((hdr)->b_spa == spa)
1584
1585 static void
1586 buf_discard_identity(arc_buf_hdr_t *hdr)
1587 {
1588         hdr->b_dva.dva_word[0] = 0;
1589         hdr->b_dva.dva_word[1] = 0;
1590         hdr->b_birth = 0;
1591 }
1592
1593 static arc_buf_hdr_t *
1594 buf_hash_find(uint64_t spa, const blkptr_t *bp, kmutex_t **lockp)
1595 {
1596         const dva_t *dva = BP_IDENTITY(bp);
1597         uint64_t birth = BP_PHYSICAL_BIRTH(bp);
1598         uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
1599         kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1600         arc_buf_hdr_t *hdr;
1601
1602         mutex_enter(hash_lock);
1603         for (hdr = buf_hash_table.ht_table[idx]; hdr != NULL;
1604             hdr = hdr->b_hash_next) {
1605                 if (HDR_EQUAL(spa, dva, birth, hdr)) {
1606                         *lockp = hash_lock;
1607                         return (hdr);
1608                 }
1609         }
1610         mutex_exit(hash_lock);
1611         *lockp = NULL;
1612         return (NULL);
1613 }
1614
1615 /*
1616  * Insert an entry into the hash table.  If there is already an element
1617  * equal to elem in the hash table, then the already existing element
1618  * will be returned and the new element will not be inserted.
1619  * Otherwise returns NULL.
1620  * If lockp == NULL, the caller is assumed to already hold the hash lock.
1621  */
1622 static arc_buf_hdr_t *
1623 buf_hash_insert(arc_buf_hdr_t *hdr, kmutex_t **lockp)
1624 {
1625         uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1626         kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
1627         arc_buf_hdr_t *fhdr;
1628         uint32_t i;
1629
1630         ASSERT(!DVA_IS_EMPTY(&hdr->b_dva));
1631         ASSERT(hdr->b_birth != 0);
1632         ASSERT(!HDR_IN_HASH_TABLE(hdr));
1633
1634         if (lockp != NULL) {
1635                 *lockp = hash_lock;
1636                 mutex_enter(hash_lock);
1637         } else {
1638                 ASSERT(MUTEX_HELD(hash_lock));
1639         }
1640
1641         for (fhdr = buf_hash_table.ht_table[idx], i = 0; fhdr != NULL;
1642             fhdr = fhdr->b_hash_next, i++) {
1643                 if (HDR_EQUAL(hdr->b_spa, &hdr->b_dva, hdr->b_birth, fhdr))
1644                         return (fhdr);
1645         }
1646
1647         hdr->b_hash_next = buf_hash_table.ht_table[idx];
1648         buf_hash_table.ht_table[idx] = hdr;
1649         arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1650
1651         /* collect some hash table performance data */
1652         if (i > 0) {
1653                 ARCSTAT_BUMP(arcstat_hash_collisions);
1654                 if (i == 1)
1655                         ARCSTAT_BUMP(arcstat_hash_chains);
1656
1657                 ARCSTAT_MAX(arcstat_hash_chain_max, i);
1658         }
1659
1660         ARCSTAT_BUMP(arcstat_hash_elements);
1661         ARCSTAT_MAXSTAT(arcstat_hash_elements);
1662
1663         return (NULL);
1664 }
1665
1666 static void
1667 buf_hash_remove(arc_buf_hdr_t *hdr)
1668 {
1669         arc_buf_hdr_t *fhdr, **hdrp;
1670         uint64_t idx = BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth);
1671
1672         ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
1673         ASSERT(HDR_IN_HASH_TABLE(hdr));
1674
1675         hdrp = &buf_hash_table.ht_table[idx];
1676         while ((fhdr = *hdrp) != hdr) {
1677                 ASSERT3P(fhdr, !=, NULL);
1678                 hdrp = &fhdr->b_hash_next;
1679         }
1680         *hdrp = hdr->b_hash_next;
1681         hdr->b_hash_next = NULL;
1682         arc_hdr_clear_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
1683
1684         /* collect some hash table performance data */
1685         ARCSTAT_BUMPDOWN(arcstat_hash_elements);
1686
1687         if (buf_hash_table.ht_table[idx] &&
1688             buf_hash_table.ht_table[idx]->b_hash_next == NULL)
1689                 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
1690 }
1691
1692 /*
1693  * Global data structures and functions for the buf kmem cache.
1694  */
1695 static kmem_cache_t *hdr_full_cache;
1696 static kmem_cache_t *hdr_l2only_cache;
1697 static kmem_cache_t *buf_cache;
1698
1699 static void
1700 buf_fini(void)
1701 {
1702         int i;
1703
1704         kmem_free(buf_hash_table.ht_table,
1705             (buf_hash_table.ht_mask + 1) * sizeof (void *));
1706         for (i = 0; i < BUF_LOCKS; i++)
1707                 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
1708         kmem_cache_destroy(hdr_full_cache);
1709         kmem_cache_destroy(hdr_l2only_cache);
1710         kmem_cache_destroy(buf_cache);
1711 }
1712
1713 /*
1714  * Constructor callback - called when the cache is empty
1715  * and a new buf is requested.
1716  */
1717 /* ARGSUSED */
1718 static int
1719 hdr_full_cons(void *vbuf, void *unused, int kmflag)
1720 {
1721         arc_buf_hdr_t *hdr = vbuf;
1722
1723         bzero(hdr, HDR_FULL_SIZE);
1724         cv_init(&hdr->b_l1hdr.b_cv, NULL, CV_DEFAULT, NULL);
1725         refcount_create(&hdr->b_l1hdr.b_refcnt);
1726         mutex_init(&hdr->b_l1hdr.b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
1727         multilist_link_init(&hdr->b_l1hdr.b_arc_node);
1728         arc_space_consume(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1729
1730         return (0);
1731 }
1732
1733 /* ARGSUSED */
1734 static int
1735 hdr_l2only_cons(void *vbuf, void *unused, int kmflag)
1736 {
1737         arc_buf_hdr_t *hdr = vbuf;
1738
1739         bzero(hdr, HDR_L2ONLY_SIZE);
1740         arc_space_consume(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1741
1742         return (0);
1743 }
1744
1745 /* ARGSUSED */
1746 static int
1747 buf_cons(void *vbuf, void *unused, int kmflag)
1748 {
1749         arc_buf_t *buf = vbuf;
1750
1751         bzero(buf, sizeof (arc_buf_t));
1752         mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
1753         arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1754
1755         return (0);
1756 }
1757
1758 /*
1759  * Destructor callback - called when a cached buf is
1760  * no longer required.
1761  */
1762 /* ARGSUSED */
1763 static void
1764 hdr_full_dest(void *vbuf, void *unused)
1765 {
1766         arc_buf_hdr_t *hdr = vbuf;
1767
1768         ASSERT(HDR_EMPTY(hdr));
1769         cv_destroy(&hdr->b_l1hdr.b_cv);
1770         refcount_destroy(&hdr->b_l1hdr.b_refcnt);
1771         mutex_destroy(&hdr->b_l1hdr.b_freeze_lock);
1772         ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
1773         arc_space_return(HDR_FULL_SIZE, ARC_SPACE_HDRS);
1774 }
1775
1776 /* ARGSUSED */
1777 static void
1778 hdr_l2only_dest(void *vbuf, void *unused)
1779 {
1780         arc_buf_hdr_t *hdr = vbuf;
1781
1782         ASSERT(HDR_EMPTY(hdr));
1783         arc_space_return(HDR_L2ONLY_SIZE, ARC_SPACE_L2HDRS);
1784 }
1785
1786 /* ARGSUSED */
1787 static void
1788 buf_dest(void *vbuf, void *unused)
1789 {
1790         arc_buf_t *buf = vbuf;
1791
1792         mutex_destroy(&buf->b_evict_lock);
1793         arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
1794 }
1795
1796 /*
1797  * Reclaim callback -- invoked when memory is low.
1798  */
1799 /* ARGSUSED */
1800 static void
1801 hdr_recl(void *unused)
1802 {
1803         dprintf("hdr_recl called\n");
1804         /*
1805          * umem calls the reclaim func when we destroy the buf cache,
1806          * which is after we do arc_fini().
1807          */
1808         if (!arc_dead)
1809                 cv_signal(&arc_reclaim_thread_cv);
1810 }
1811
1812 static void
1813 buf_init(void)
1814 {
1815         uint64_t *ct;
1816         uint64_t hsize = 1ULL << 12;
1817         int i, j;
1818
1819         /*
1820          * The hash table is big enough to fill all of physical memory
1821          * with an average block size of zfs_arc_average_blocksize (default 8K).
1822          * By default, the table will take up
1823          * totalmem * sizeof(void*) / 8K (1MB per GB with 8-byte pointers).
1824          */
1825         while (hsize * zfs_arc_average_blocksize < (uint64_t)physmem * PAGESIZE)
1826                 hsize <<= 1;
1827 retry:
1828         buf_hash_table.ht_mask = hsize - 1;
1829         buf_hash_table.ht_table =
1830             kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1831         if (buf_hash_table.ht_table == NULL) {
1832                 ASSERT(hsize > (1ULL << 8));
1833                 hsize >>= 1;
1834                 goto retry;
1835         }
1836
1837         hdr_full_cache = kmem_cache_create("arc_buf_hdr_t_full", HDR_FULL_SIZE,
1838             0, hdr_full_cons, hdr_full_dest, hdr_recl, NULL, NULL, 0);
1839         hdr_l2only_cache = kmem_cache_create("arc_buf_hdr_t_l2only",
1840             HDR_L2ONLY_SIZE, 0, hdr_l2only_cons, hdr_l2only_dest, hdr_recl,
1841             NULL, NULL, 0);
1842         buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1843             0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1844
1845         for (i = 0; i < 256; i++)
1846                 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1847                         *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1848
1849         for (i = 0; i < BUF_LOCKS; i++) {
1850                 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1851                     NULL, MUTEX_DEFAULT, NULL);
1852         }
1853 }
1854
1855 /*
1856  * This is the size that the buf occupies in memory. If the buf is compressed,
1857  * it will correspond to the compressed size. You should use this method of
1858  * getting the buf size unless you explicitly need the logical size.
1859  */
1860 int32_t
1861 arc_buf_size(arc_buf_t *buf)
1862 {
1863         return (ARC_BUF_COMPRESSED(buf) ?
1864             HDR_GET_PSIZE(buf->b_hdr) : HDR_GET_LSIZE(buf->b_hdr));
1865 }
1866
1867 int32_t
1868 arc_buf_lsize(arc_buf_t *buf)
1869 {
1870         return (HDR_GET_LSIZE(buf->b_hdr));
1871 }
1872
1873 enum zio_compress
1874 arc_get_compression(arc_buf_t *buf)
1875 {
1876         return (ARC_BUF_COMPRESSED(buf) ?
1877             HDR_GET_COMPRESS(buf->b_hdr) : ZIO_COMPRESS_OFF);
1878 }
1879
1880 #define ARC_MINTIME     (hz>>4) /* 62 ms */
1881
1882 static inline boolean_t
1883 arc_buf_is_shared(arc_buf_t *buf)
1884 {
1885         boolean_t shared = (buf->b_data != NULL &&
1886             buf->b_hdr->b_l1hdr.b_pabd != NULL &&
1887             abd_is_linear(buf->b_hdr->b_l1hdr.b_pabd) &&
1888             buf->b_data == abd_to_buf(buf->b_hdr->b_l1hdr.b_pabd));
1889         IMPLY(shared, HDR_SHARED_DATA(buf->b_hdr));
1890         IMPLY(shared, ARC_BUF_SHARED(buf));
1891         IMPLY(shared, ARC_BUF_COMPRESSED(buf) || ARC_BUF_LAST(buf));
1892
1893         /*
1894          * It would be nice to assert arc_can_share() too, but the "hdr isn't
1895          * already being shared" requirement prevents us from doing that.
1896          */
1897
1898         return (shared);
1899 }
1900
1901 /*
1902  * Free the checksum associated with this header. If there is no checksum, this
1903  * is a no-op.
1904  */
1905 static inline void
1906 arc_cksum_free(arc_buf_hdr_t *hdr)
1907 {
1908         ASSERT(HDR_HAS_L1HDR(hdr));
1909         mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1910         if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
1911                 kmem_free(hdr->b_l1hdr.b_freeze_cksum, sizeof (zio_cksum_t));
1912                 hdr->b_l1hdr.b_freeze_cksum = NULL;
1913         }
1914         mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1915 }
1916
1917 /*
1918  * Return true iff at least one of the bufs on hdr is not compressed.
1919  */
1920 static boolean_t
1921 arc_hdr_has_uncompressed_buf(arc_buf_hdr_t *hdr)
1922 {
1923         for (arc_buf_t *b = hdr->b_l1hdr.b_buf; b != NULL; b = b->b_next) {
1924                 if (!ARC_BUF_COMPRESSED(b)) {
1925                         return (B_TRUE);
1926                 }
1927         }
1928         return (B_FALSE);
1929 }
1930
1931 /*
1932  * If we've turned on the ZFS_DEBUG_MODIFY flag, verify that the buf's data
1933  * matches the checksum that is stored in the hdr. If there is no checksum,
1934  * or if the buf is compressed, this is a no-op.
1935  */
1936 static void
1937 arc_cksum_verify(arc_buf_t *buf)
1938 {
1939         arc_buf_hdr_t *hdr = buf->b_hdr;
1940         zio_cksum_t zc;
1941
1942         if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1943                 return;
1944
1945         if (ARC_BUF_COMPRESSED(buf)) {
1946                 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
1947                     arc_hdr_has_uncompressed_buf(hdr));
1948                 return;
1949         }
1950
1951         ASSERT(HDR_HAS_L1HDR(hdr));
1952
1953         mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
1954         if (hdr->b_l1hdr.b_freeze_cksum == NULL || HDR_IO_ERROR(hdr)) {
1955                 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1956                 return;
1957         }
1958
1959         fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL, &zc);
1960         if (!ZIO_CHECKSUM_EQUAL(*hdr->b_l1hdr.b_freeze_cksum, zc))
1961                 panic("buffer modified while frozen!");
1962         mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
1963 }
1964
1965 static boolean_t
1966 arc_cksum_is_equal(arc_buf_hdr_t *hdr, zio_t *zio)
1967 {
1968         enum zio_compress compress = BP_GET_COMPRESS(zio->io_bp);
1969         boolean_t valid_cksum;
1970
1971         ASSERT(!BP_IS_EMBEDDED(zio->io_bp));
1972         VERIFY3U(BP_GET_PSIZE(zio->io_bp), ==, HDR_GET_PSIZE(hdr));
1973
1974         /*
1975          * We rely on the blkptr's checksum to determine if the block
1976          * is valid or not. When compressed arc is enabled, the l2arc
1977          * writes the block to the l2arc just as it appears in the pool.
1978          * This allows us to use the blkptr's checksum to validate the
1979          * data that we just read off of the l2arc without having to store
1980          * a separate checksum in the arc_buf_hdr_t. However, if compressed
1981          * arc is disabled, then the data written to the l2arc is always
1982          * uncompressed and won't match the block as it exists in the main
1983          * pool. When this is the case, we must first compress it if it is
1984          * compressed on the main pool before we can validate the checksum.
1985          */
1986         if (!HDR_COMPRESSION_ENABLED(hdr) && compress != ZIO_COMPRESS_OFF) {
1987                 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
1988                 uint64_t lsize = HDR_GET_LSIZE(hdr);
1989                 uint64_t csize;
1990
1991                 abd_t *cdata = abd_alloc_linear(HDR_GET_PSIZE(hdr), B_TRUE);
1992                 csize = zio_compress_data(compress, zio->io_abd,
1993                     abd_to_buf(cdata), lsize);
1994
1995                 ASSERT3U(csize, <=, HDR_GET_PSIZE(hdr));
1996                 if (csize < HDR_GET_PSIZE(hdr)) {
1997                         /*
1998                          * Compressed blocks are always a multiple of the
1999                          * smallest ashift in the pool. Ideally, we would
2000                          * like to round up the csize to the next
2001                          * spa_min_ashift but that value may have changed
2002                          * since the block was last written. Instead,
2003                          * we rely on the fact that the hdr's psize
2004                          * was set to the psize of the block when it was
2005                          * last written. We set the csize to that value
2006                          * and zero out any part that should not contain
2007                          * data.
2008                          */
2009                         abd_zero_off(cdata, csize, HDR_GET_PSIZE(hdr) - csize);
2010                         csize = HDR_GET_PSIZE(hdr);
2011                 }
2012                 zio_push_transform(zio, cdata, csize, HDR_GET_PSIZE(hdr), NULL);
2013         }
2014
2015         /*
2016          * Block pointers always store the checksum for the logical data.
2017          * If the block pointer has the gang bit set, then the checksum
2018          * it represents is for the reconstituted data and not for an
2019          * individual gang member. The zio pipeline, however, must be able to
2020          * determine the checksum of each of the gang constituents so it
2021          * treats the checksum comparison differently than what we need
2022          * for l2arc blocks. This prevents us from using the
2023          * zio_checksum_error() interface directly. Instead we must call the
2024          * zio_checksum_error_impl() so that we can ensure the checksum is
2025          * generated using the correct checksum algorithm and accounts for the
2026          * logical I/O size and not just a gang fragment.
2027          */
2028         valid_cksum = (zio_checksum_error_impl(zio->io_spa, zio->io_bp,
2029             BP_GET_CHECKSUM(zio->io_bp), zio->io_abd, zio->io_size,
2030             zio->io_offset, NULL) == 0);
2031         zio_pop_transforms(zio);
2032         return (valid_cksum);
2033 }
2034
2035 /*
2036  * Given a buf full of data, if ZFS_DEBUG_MODIFY is enabled this computes a
2037  * checksum and attaches it to the buf's hdr so that we can ensure that the buf
2038  * isn't modified later on. If buf is compressed or there is already a checksum
2039  * on the hdr, this is a no-op (we only checksum uncompressed bufs).
2040  */
2041 static void
2042 arc_cksum_compute(arc_buf_t *buf)
2043 {
2044         arc_buf_hdr_t *hdr = buf->b_hdr;
2045
2046         if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2047                 return;
2048
2049         ASSERT(HDR_HAS_L1HDR(hdr));
2050
2051         mutex_enter(&buf->b_hdr->b_l1hdr.b_freeze_lock);
2052         if (hdr->b_l1hdr.b_freeze_cksum != NULL) {
2053                 ASSERT(arc_hdr_has_uncompressed_buf(hdr));
2054                 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2055                 return;
2056         } else if (ARC_BUF_COMPRESSED(buf)) {
2057                 mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2058                 return;
2059         }
2060
2061         ASSERT(!ARC_BUF_COMPRESSED(buf));
2062         hdr->b_l1hdr.b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
2063             KM_SLEEP);
2064         fletcher_2_native(buf->b_data, arc_buf_size(buf), NULL,
2065             hdr->b_l1hdr.b_freeze_cksum);
2066         mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2067 #ifdef illumos
2068         arc_buf_watch(buf);
2069 #endif
2070 }
2071
2072 #ifdef illumos
2073 #ifndef _KERNEL
2074 typedef struct procctl {
2075         long cmd;
2076         prwatch_t prwatch;
2077 } procctl_t;
2078 #endif
2079
2080 /* ARGSUSED */
2081 static void
2082 arc_buf_unwatch(arc_buf_t *buf)
2083 {
2084 #ifndef _KERNEL
2085         if (arc_watch) {
2086                 int result;
2087                 procctl_t ctl;
2088                 ctl.cmd = PCWATCH;
2089                 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2090                 ctl.prwatch.pr_size = 0;
2091                 ctl.prwatch.pr_wflags = 0;
2092                 result = write(arc_procfd, &ctl, sizeof (ctl));
2093                 ASSERT3U(result, ==, sizeof (ctl));
2094         }
2095 #endif
2096 }
2097
2098 /* ARGSUSED */
2099 static void
2100 arc_buf_watch(arc_buf_t *buf)
2101 {
2102 #ifndef _KERNEL
2103         if (arc_watch) {
2104                 int result;
2105                 procctl_t ctl;
2106                 ctl.cmd = PCWATCH;
2107                 ctl.prwatch.pr_vaddr = (uintptr_t)buf->b_data;
2108                 ctl.prwatch.pr_size = arc_buf_size(buf);
2109                 ctl.prwatch.pr_wflags = WA_WRITE;
2110                 result = write(arc_procfd, &ctl, sizeof (ctl));
2111                 ASSERT3U(result, ==, sizeof (ctl));
2112         }
2113 #endif
2114 }
2115 #endif /* illumos */
2116
2117 static arc_buf_contents_t
2118 arc_buf_type(arc_buf_hdr_t *hdr)
2119 {
2120         arc_buf_contents_t type;
2121         if (HDR_ISTYPE_METADATA(hdr)) {
2122                 type = ARC_BUFC_METADATA;
2123         } else {
2124                 type = ARC_BUFC_DATA;
2125         }
2126         VERIFY3U(hdr->b_type, ==, type);
2127         return (type);
2128 }
2129
2130 boolean_t
2131 arc_is_metadata(arc_buf_t *buf)
2132 {
2133         return (HDR_ISTYPE_METADATA(buf->b_hdr) != 0);
2134 }
2135
2136 static uint32_t
2137 arc_bufc_to_flags(arc_buf_contents_t type)
2138 {
2139         switch (type) {
2140         case ARC_BUFC_DATA:
2141                 /* metadata field is 0 if buffer contains normal data */
2142                 return (0);
2143         case ARC_BUFC_METADATA:
2144                 return (ARC_FLAG_BUFC_METADATA);
2145         default:
2146                 break;
2147         }
2148         panic("undefined ARC buffer type!");
2149         return ((uint32_t)-1);
2150 }
2151
2152 void
2153 arc_buf_thaw(arc_buf_t *buf)
2154 {
2155         arc_buf_hdr_t *hdr = buf->b_hdr;
2156
2157         ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
2158         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
2159
2160         arc_cksum_verify(buf);
2161
2162         /*
2163          * Compressed buffers do not manipulate the b_freeze_cksum or
2164          * allocate b_thawed.
2165          */
2166         if (ARC_BUF_COMPRESSED(buf)) {
2167                 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2168                     arc_hdr_has_uncompressed_buf(hdr));
2169                 return;
2170         }
2171
2172         ASSERT(HDR_HAS_L1HDR(hdr));
2173         arc_cksum_free(hdr);
2174
2175         mutex_enter(&hdr->b_l1hdr.b_freeze_lock);
2176 #ifdef ZFS_DEBUG
2177         if (zfs_flags & ZFS_DEBUG_MODIFY) {
2178                 if (hdr->b_l1hdr.b_thawed != NULL)
2179                         kmem_free(hdr->b_l1hdr.b_thawed, 1);
2180                 hdr->b_l1hdr.b_thawed = kmem_alloc(1, KM_SLEEP);
2181         }
2182 #endif
2183
2184         mutex_exit(&hdr->b_l1hdr.b_freeze_lock);
2185
2186 #ifdef illumos
2187         arc_buf_unwatch(buf);
2188 #endif
2189 }
2190
2191 void
2192 arc_buf_freeze(arc_buf_t *buf)
2193 {
2194         arc_buf_hdr_t *hdr = buf->b_hdr;
2195         kmutex_t *hash_lock;
2196
2197         if (!(zfs_flags & ZFS_DEBUG_MODIFY))
2198                 return;
2199
2200         if (ARC_BUF_COMPRESSED(buf)) {
2201                 ASSERT(hdr->b_l1hdr.b_freeze_cksum == NULL ||
2202                     arc_hdr_has_uncompressed_buf(hdr));
2203                 return;
2204         }
2205
2206         hash_lock = HDR_LOCK(hdr);
2207         mutex_enter(hash_lock);
2208
2209         ASSERT(HDR_HAS_L1HDR(hdr));
2210         ASSERT(hdr->b_l1hdr.b_freeze_cksum != NULL ||
2211             hdr->b_l1hdr.b_state == arc_anon);
2212         arc_cksum_compute(buf);
2213         mutex_exit(hash_lock);
2214 }
2215
2216 /*
2217  * The arc_buf_hdr_t's b_flags should never be modified directly. Instead,
2218  * the following functions should be used to ensure that the flags are
2219  * updated in a thread-safe way. When manipulating the flags either
2220  * the hash_lock must be held or the hdr must be undiscoverable. This
2221  * ensures that we're not racing with any other threads when updating
2222  * the flags.
2223  */
2224 static inline void
2225 arc_hdr_set_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2226 {
2227         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2228         hdr->b_flags |= flags;
2229 }
2230
2231 static inline void
2232 arc_hdr_clear_flags(arc_buf_hdr_t *hdr, arc_flags_t flags)
2233 {
2234         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2235         hdr->b_flags &= ~flags;
2236 }
2237
2238 /*
2239  * Setting the compression bits in the arc_buf_hdr_t's b_flags is
2240  * done in a special way since we have to clear and set bits
2241  * at the same time. Consumers that wish to set the compression bits
2242  * must use this function to ensure that the flags are updated in
2243  * thread-safe manner.
2244  */
2245 static void
2246 arc_hdr_set_compress(arc_buf_hdr_t *hdr, enum zio_compress cmp)
2247 {
2248         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2249
2250         /*
2251          * Holes and embedded blocks will always have a psize = 0 so
2252          * we ignore the compression of the blkptr and set the
2253          * arc_buf_hdr_t's compression to ZIO_COMPRESS_OFF.
2254          * Holes and embedded blocks remain anonymous so we don't
2255          * want to uncompress them. Mark them as uncompressed.
2256          */
2257         if (!zfs_compressed_arc_enabled || HDR_GET_PSIZE(hdr) == 0) {
2258                 arc_hdr_clear_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2259                 HDR_SET_COMPRESS(hdr, ZIO_COMPRESS_OFF);
2260                 ASSERT(!HDR_COMPRESSION_ENABLED(hdr));
2261                 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
2262         } else {
2263                 arc_hdr_set_flags(hdr, ARC_FLAG_COMPRESSED_ARC);
2264                 HDR_SET_COMPRESS(hdr, cmp);
2265                 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, cmp);
2266                 ASSERT(HDR_COMPRESSION_ENABLED(hdr));
2267         }
2268 }
2269
2270 /*
2271  * Looks for another buf on the same hdr which has the data decompressed, copies
2272  * from it, and returns true. If no such buf exists, returns false.
2273  */
2274 static boolean_t
2275 arc_buf_try_copy_decompressed_data(arc_buf_t *buf)
2276 {
2277         arc_buf_hdr_t *hdr = buf->b_hdr;
2278         boolean_t copied = B_FALSE;
2279
2280         ASSERT(HDR_HAS_L1HDR(hdr));
2281         ASSERT3P(buf->b_data, !=, NULL);
2282         ASSERT(!ARC_BUF_COMPRESSED(buf));
2283
2284         for (arc_buf_t *from = hdr->b_l1hdr.b_buf; from != NULL;
2285             from = from->b_next) {
2286                 /* can't use our own data buffer */
2287                 if (from == buf) {
2288                         continue;
2289                 }
2290
2291                 if (!ARC_BUF_COMPRESSED(from)) {
2292                         bcopy(from->b_data, buf->b_data, arc_buf_size(buf));
2293                         copied = B_TRUE;
2294                         break;
2295                 }
2296         }
2297
2298         /*
2299          * There were no decompressed bufs, so there should not be a
2300          * checksum on the hdr either.
2301          */
2302         EQUIV(!copied, hdr->b_l1hdr.b_freeze_cksum == NULL);
2303
2304         return (copied);
2305 }
2306
2307 /*
2308  * Given a buf that has a data buffer attached to it, this function will
2309  * efficiently fill the buf with data of the specified compression setting from
2310  * the hdr and update the hdr's b_freeze_cksum if necessary. If the buf and hdr
2311  * are already sharing a data buf, no copy is performed.
2312  *
2313  * If the buf is marked as compressed but uncompressed data was requested, this
2314  * will allocate a new data buffer for the buf, remove that flag, and fill the
2315  * buf with uncompressed data. You can't request a compressed buf on a hdr with
2316  * uncompressed data, and (since we haven't added support for it yet) if you
2317  * want compressed data your buf must already be marked as compressed and have
2318  * the correct-sized data buffer.
2319  */
2320 static int
2321 arc_buf_fill(arc_buf_t *buf, boolean_t compressed)
2322 {
2323         arc_buf_hdr_t *hdr = buf->b_hdr;
2324         boolean_t hdr_compressed = (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
2325         dmu_object_byteswap_t bswap = hdr->b_l1hdr.b_byteswap;
2326
2327         ASSERT3P(buf->b_data, !=, NULL);
2328         IMPLY(compressed, hdr_compressed);
2329         IMPLY(compressed, ARC_BUF_COMPRESSED(buf));
2330
2331         if (hdr_compressed == compressed) {
2332                 if (!arc_buf_is_shared(buf)) {
2333                         abd_copy_to_buf(buf->b_data, hdr->b_l1hdr.b_pabd,
2334                             arc_buf_size(buf));
2335                 }
2336         } else {
2337                 ASSERT(hdr_compressed);
2338                 ASSERT(!compressed);
2339                 ASSERT3U(HDR_GET_LSIZE(hdr), !=, HDR_GET_PSIZE(hdr));
2340
2341                 /*
2342                  * If the buf is sharing its data with the hdr, unlink it and
2343                  * allocate a new data buffer for the buf.
2344                  */
2345                 if (arc_buf_is_shared(buf)) {
2346                         ASSERT(ARC_BUF_COMPRESSED(buf));
2347
2348                         /* We need to give the buf it's own b_data */
2349                         buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
2350                         buf->b_data =
2351                             arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2352                         arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
2353
2354                         /* Previously overhead was 0; just add new overhead */
2355                         ARCSTAT_INCR(arcstat_overhead_size, HDR_GET_LSIZE(hdr));
2356                 } else if (ARC_BUF_COMPRESSED(buf)) {
2357                         /* We need to reallocate the buf's b_data */
2358                         arc_free_data_buf(hdr, buf->b_data, HDR_GET_PSIZE(hdr),
2359                             buf);
2360                         buf->b_data =
2361                             arc_get_data_buf(hdr, HDR_GET_LSIZE(hdr), buf);
2362
2363                         /* We increased the size of b_data; update overhead */
2364                         ARCSTAT_INCR(arcstat_overhead_size,
2365                             HDR_GET_LSIZE(hdr) - HDR_GET_PSIZE(hdr));
2366                 }
2367
2368                 /*
2369                  * Regardless of the buf's previous compression settings, it
2370                  * should not be compressed at the end of this function.
2371                  */
2372                 buf->b_flags &= ~ARC_BUF_FLAG_COMPRESSED;
2373
2374                 /*
2375                  * Try copying the data from another buf which already has a
2376                  * decompressed version. If that's not possible, it's time to
2377                  * bite the bullet and decompress the data from the hdr.
2378                  */
2379                 if (arc_buf_try_copy_decompressed_data(buf)) {
2380                         /* Skip byteswapping and checksumming (already done) */
2381                         ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, !=, NULL);
2382                         return (0);
2383                 } else {
2384                         int error = zio_decompress_data(HDR_GET_COMPRESS(hdr),
2385                             hdr->b_l1hdr.b_pabd, buf->b_data,
2386                             HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2387
2388                         /*
2389                          * Absent hardware errors or software bugs, this should
2390                          * be impossible, but log it anyway so we can debug it.
2391                          */
2392                         if (error != 0) {
2393                                 zfs_dbgmsg(
2394                                     "hdr %p, compress %d, psize %d, lsize %d",
2395                                     hdr, HDR_GET_COMPRESS(hdr),
2396                                     HDR_GET_PSIZE(hdr), HDR_GET_LSIZE(hdr));
2397                                 return (SET_ERROR(EIO));
2398                         }
2399                 }
2400         }
2401
2402         /* Byteswap the buf's data if necessary */
2403         if (bswap != DMU_BSWAP_NUMFUNCS) {
2404                 ASSERT(!HDR_SHARED_DATA(hdr));
2405                 ASSERT3U(bswap, <, DMU_BSWAP_NUMFUNCS);
2406                 dmu_ot_byteswap[bswap].ob_func(buf->b_data, HDR_GET_LSIZE(hdr));
2407         }
2408
2409         /* Compute the hdr's checksum if necessary */
2410         arc_cksum_compute(buf);
2411
2412         return (0);
2413 }
2414
2415 int
2416 arc_decompress(arc_buf_t *buf)
2417 {
2418         return (arc_buf_fill(buf, B_FALSE));
2419 }
2420
2421 /*
2422  * Return the size of the block, b_pabd, that is stored in the arc_buf_hdr_t.
2423  */
2424 static uint64_t
2425 arc_hdr_size(arc_buf_hdr_t *hdr)
2426 {
2427         uint64_t size;
2428
2429         if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF &&
2430             HDR_GET_PSIZE(hdr) > 0) {
2431                 size = HDR_GET_PSIZE(hdr);
2432         } else {
2433                 ASSERT3U(HDR_GET_LSIZE(hdr), !=, 0);
2434                 size = HDR_GET_LSIZE(hdr);
2435         }
2436         return (size);
2437 }
2438
2439 /*
2440  * Increment the amount of evictable space in the arc_state_t's refcount.
2441  * We account for the space used by the hdr and the arc buf individually
2442  * so that we can add and remove them from the refcount individually.
2443  */
2444 static void
2445 arc_evictable_space_increment(arc_buf_hdr_t *hdr, arc_state_t *state)
2446 {
2447         arc_buf_contents_t type = arc_buf_type(hdr);
2448
2449         ASSERT(HDR_HAS_L1HDR(hdr));
2450
2451         if (GHOST_STATE(state)) {
2452                 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2453                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2454                 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2455                 (void) refcount_add_many(&state->arcs_esize[type],
2456                     HDR_GET_LSIZE(hdr), hdr);
2457                 return;
2458         }
2459
2460         ASSERT(!GHOST_STATE(state));
2461         if (hdr->b_l1hdr.b_pabd != NULL) {
2462                 (void) refcount_add_many(&state->arcs_esize[type],
2463                     arc_hdr_size(hdr), hdr);
2464         }
2465         for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2466             buf = buf->b_next) {
2467                 if (arc_buf_is_shared(buf))
2468                         continue;
2469                 (void) refcount_add_many(&state->arcs_esize[type],
2470                     arc_buf_size(buf), buf);
2471         }
2472 }
2473
2474 /*
2475  * Decrement the amount of evictable space in the arc_state_t's refcount.
2476  * We account for the space used by the hdr and the arc buf individually
2477  * so that we can add and remove them from the refcount individually.
2478  */
2479 static void
2480 arc_evictable_space_decrement(arc_buf_hdr_t *hdr, arc_state_t *state)
2481 {
2482         arc_buf_contents_t type = arc_buf_type(hdr);
2483
2484         ASSERT(HDR_HAS_L1HDR(hdr));
2485
2486         if (GHOST_STATE(state)) {
2487                 ASSERT0(hdr->b_l1hdr.b_bufcnt);
2488                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2489                 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2490                 (void) refcount_remove_many(&state->arcs_esize[type],
2491                     HDR_GET_LSIZE(hdr), hdr);
2492                 return;
2493         }
2494
2495         ASSERT(!GHOST_STATE(state));
2496         if (hdr->b_l1hdr.b_pabd != NULL) {
2497                 (void) refcount_remove_many(&state->arcs_esize[type],
2498                     arc_hdr_size(hdr), hdr);
2499         }
2500         for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2501             buf = buf->b_next) {
2502                 if (arc_buf_is_shared(buf))
2503                         continue;
2504                 (void) refcount_remove_many(&state->arcs_esize[type],
2505                     arc_buf_size(buf), buf);
2506         }
2507 }
2508
2509 /*
2510  * Add a reference to this hdr indicating that someone is actively
2511  * referencing that memory. When the refcount transitions from 0 to 1,
2512  * we remove it from the respective arc_state_t list to indicate that
2513  * it is not evictable.
2514  */
2515 static void
2516 add_reference(arc_buf_hdr_t *hdr, void *tag)
2517 {
2518         ASSERT(HDR_HAS_L1HDR(hdr));
2519         if (!MUTEX_HELD(HDR_LOCK(hdr))) {
2520                 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
2521                 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
2522                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2523         }
2524
2525         arc_state_t *state = hdr->b_l1hdr.b_state;
2526
2527         if ((refcount_add(&hdr->b_l1hdr.b_refcnt, tag) == 1) &&
2528             (state != arc_anon)) {
2529                 /* We don't use the L2-only state list. */
2530                 if (state != arc_l2c_only) {
2531                         multilist_remove(state->arcs_list[arc_buf_type(hdr)],
2532                             hdr);
2533                         arc_evictable_space_decrement(hdr, state);
2534                 }
2535                 /* remove the prefetch flag if we get a reference */
2536                 arc_hdr_clear_flags(hdr, ARC_FLAG_PREFETCH);
2537         }
2538 }
2539
2540 /*
2541  * Remove a reference from this hdr. When the reference transitions from
2542  * 1 to 0 and we're not anonymous, then we add this hdr to the arc_state_t's
2543  * list making it eligible for eviction.
2544  */
2545 static int
2546 remove_reference(arc_buf_hdr_t *hdr, kmutex_t *hash_lock, void *tag)
2547 {
2548         int cnt;
2549         arc_state_t *state = hdr->b_l1hdr.b_state;
2550
2551         ASSERT(HDR_HAS_L1HDR(hdr));
2552         ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
2553         ASSERT(!GHOST_STATE(state));
2554
2555         /*
2556          * arc_l2c_only counts as a ghost state so we don't need to explicitly
2557          * check to prevent usage of the arc_l2c_only list.
2558          */
2559         if (((cnt = refcount_remove(&hdr->b_l1hdr.b_refcnt, tag)) == 0) &&
2560             (state != arc_anon)) {
2561                 multilist_insert(state->arcs_list[arc_buf_type(hdr)], hdr);
2562                 ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
2563                 arc_evictable_space_increment(hdr, state);
2564         }
2565         return (cnt);
2566 }
2567
2568 /*
2569  * Returns detailed information about a specific arc buffer.  When the
2570  * state_index argument is set the function will calculate the arc header
2571  * list position for its arc state.  Since this requires a linear traversal
2572  * callers are strongly encourage not to do this.  However, it can be helpful
2573  * for targeted analysis so the functionality is provided.
2574  */
2575 void
2576 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
2577 {
2578         arc_buf_hdr_t *hdr = ab->b_hdr;
2579         l1arc_buf_hdr_t *l1hdr = NULL;
2580         l2arc_buf_hdr_t *l2hdr = NULL;
2581         arc_state_t *state = NULL;
2582
2583         memset(abi, 0, sizeof (arc_buf_info_t));
2584
2585         if (hdr == NULL)
2586                 return;
2587
2588         abi->abi_flags = hdr->b_flags;
2589
2590         if (HDR_HAS_L1HDR(hdr)) {
2591                 l1hdr = &hdr->b_l1hdr;
2592                 state = l1hdr->b_state;
2593         }
2594         if (HDR_HAS_L2HDR(hdr))
2595                 l2hdr = &hdr->b_l2hdr;
2596
2597         if (l1hdr) {
2598                 abi->abi_bufcnt = l1hdr->b_bufcnt;
2599                 abi->abi_access = l1hdr->b_arc_access;
2600                 abi->abi_mru_hits = l1hdr->b_mru_hits;
2601                 abi->abi_mru_ghost_hits = l1hdr->b_mru_ghost_hits;
2602                 abi->abi_mfu_hits = l1hdr->b_mfu_hits;
2603                 abi->abi_mfu_ghost_hits = l1hdr->b_mfu_ghost_hits;
2604                 abi->abi_holds = refcount_count(&l1hdr->b_refcnt);
2605         }
2606
2607         if (l2hdr) {
2608                 abi->abi_l2arc_dattr = l2hdr->b_daddr;
2609                 abi->abi_l2arc_hits = l2hdr->b_hits;
2610         }
2611
2612         abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
2613         abi->abi_state_contents = arc_buf_type(hdr);
2614         abi->abi_size = arc_hdr_size(hdr);
2615 }
2616
2617 /*
2618  * Move the supplied buffer to the indicated state. The hash lock
2619  * for the buffer must be held by the caller.
2620  */
2621 static void
2622 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *hdr,
2623     kmutex_t *hash_lock)
2624 {
2625         arc_state_t *old_state;
2626         int64_t refcnt;
2627         uint32_t bufcnt;
2628         boolean_t update_old, update_new;
2629         arc_buf_contents_t buftype = arc_buf_type(hdr);
2630
2631         /*
2632          * We almost always have an L1 hdr here, since we call arc_hdr_realloc()
2633          * in arc_read() when bringing a buffer out of the L2ARC.  However, the
2634          * L1 hdr doesn't always exist when we change state to arc_anon before
2635          * destroying a header, in which case reallocating to add the L1 hdr is
2636          * pointless.
2637          */
2638         if (HDR_HAS_L1HDR(hdr)) {
2639                 old_state = hdr->b_l1hdr.b_state;
2640                 refcnt = refcount_count(&hdr->b_l1hdr.b_refcnt);
2641                 bufcnt = hdr->b_l1hdr.b_bufcnt;
2642                 update_old = (bufcnt > 0 || hdr->b_l1hdr.b_pabd != NULL);
2643         } else {
2644                 old_state = arc_l2c_only;
2645                 refcnt = 0;
2646                 bufcnt = 0;
2647                 update_old = B_FALSE;
2648         }
2649         update_new = update_old;
2650
2651         ASSERT(MUTEX_HELD(hash_lock));
2652         ASSERT3P(new_state, !=, old_state);
2653         ASSERT(!GHOST_STATE(new_state) || bufcnt == 0);
2654         ASSERT(old_state != arc_anon || bufcnt <= 1);
2655
2656         /*
2657          * If this buffer is evictable, transfer it from the
2658          * old state list to the new state list.
2659          */
2660         if (refcnt == 0) {
2661                 if (old_state != arc_anon && old_state != arc_l2c_only) {
2662                         ASSERT(HDR_HAS_L1HDR(hdr));
2663                         multilist_remove(old_state->arcs_list[buftype], hdr);
2664
2665                         if (GHOST_STATE(old_state)) {
2666                                 ASSERT0(bufcnt);
2667                                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2668                                 update_old = B_TRUE;
2669                         }
2670                         arc_evictable_space_decrement(hdr, old_state);
2671                 }
2672                 if (new_state != arc_anon && new_state != arc_l2c_only) {
2673
2674                         /*
2675                          * An L1 header always exists here, since if we're
2676                          * moving to some L1-cached state (i.e. not l2c_only or
2677                          * anonymous), we realloc the header to add an L1hdr
2678                          * beforehand.
2679                          */
2680                         ASSERT(HDR_HAS_L1HDR(hdr));
2681                         multilist_insert(new_state->arcs_list[buftype], hdr);
2682
2683                         if (GHOST_STATE(new_state)) {
2684                                 ASSERT0(bufcnt);
2685                                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
2686                                 update_new = B_TRUE;
2687                         }
2688                         arc_evictable_space_increment(hdr, new_state);
2689                 }
2690         }
2691
2692         ASSERT(!HDR_EMPTY(hdr));
2693         if (new_state == arc_anon && HDR_IN_HASH_TABLE(hdr))
2694                 buf_hash_remove(hdr);
2695
2696         /* adjust state sizes (ignore arc_l2c_only) */
2697
2698         if (update_new && new_state != arc_l2c_only) {
2699                 ASSERT(HDR_HAS_L1HDR(hdr));
2700                 if (GHOST_STATE(new_state)) {
2701                         ASSERT0(bufcnt);
2702
2703                         /*
2704                          * When moving a header to a ghost state, we first
2705                          * remove all arc buffers. Thus, we'll have a
2706                          * bufcnt of zero, and no arc buffer to use for
2707                          * the reference. As a result, we use the arc
2708                          * header pointer for the reference.
2709                          */
2710                         (void) refcount_add_many(&new_state->arcs_size,
2711                             HDR_GET_LSIZE(hdr), hdr);
2712                         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2713                 } else {
2714                         uint32_t buffers = 0;
2715
2716                         /*
2717                          * Each individual buffer holds a unique reference,
2718                          * thus we must remove each of these references one
2719                          * at a time.
2720                          */
2721                         for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2722                             buf = buf->b_next) {
2723                                 ASSERT3U(bufcnt, !=, 0);
2724                                 buffers++;
2725
2726                                 /*
2727                                  * When the arc_buf_t is sharing the data
2728                                  * block with the hdr, the owner of the
2729                                  * reference belongs to the hdr. Only
2730                                  * add to the refcount if the arc_buf_t is
2731                                  * not shared.
2732                                  */
2733                                 if (arc_buf_is_shared(buf))
2734                                         continue;
2735
2736                                 (void) refcount_add_many(&new_state->arcs_size,
2737                                     arc_buf_size(buf), buf);
2738                         }
2739                         ASSERT3U(bufcnt, ==, buffers);
2740
2741                         if (hdr->b_l1hdr.b_pabd != NULL) {
2742                                 (void) refcount_add_many(&new_state->arcs_size,
2743                                     arc_hdr_size(hdr), hdr);
2744                         } else {
2745                                 ASSERT(GHOST_STATE(old_state));
2746                         }
2747                 }
2748         }
2749
2750         if (update_old && old_state != arc_l2c_only) {
2751                 ASSERT(HDR_HAS_L1HDR(hdr));
2752                 if (GHOST_STATE(old_state)) {
2753                         ASSERT0(bufcnt);
2754                         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
2755
2756                         /*
2757                          * When moving a header off of a ghost state,
2758                          * the header will not contain any arc buffers.
2759                          * We use the arc header pointer for the reference
2760                          * which is exactly what we did when we put the
2761                          * header on the ghost state.
2762                          */
2763
2764                         (void) refcount_remove_many(&old_state->arcs_size,
2765                             HDR_GET_LSIZE(hdr), hdr);
2766                 } else {
2767                         uint32_t buffers = 0;
2768
2769                         /*
2770                          * Each individual buffer holds a unique reference,
2771                          * thus we must remove each of these references one
2772                          * at a time.
2773                          */
2774                         for (arc_buf_t *buf = hdr->b_l1hdr.b_buf; buf != NULL;
2775                             buf = buf->b_next) {
2776                                 ASSERT3U(bufcnt, !=, 0);
2777                                 buffers++;
2778
2779                                 /*
2780                                  * When the arc_buf_t is sharing the data
2781                                  * block with the hdr, the owner of the
2782                                  * reference belongs to the hdr. Only
2783                                  * add to the refcount if the arc_buf_t is
2784                                  * not shared.
2785                                  */
2786                                 if (arc_buf_is_shared(buf))
2787                                         continue;
2788
2789                                 (void) refcount_remove_many(
2790                                     &old_state->arcs_size, arc_buf_size(buf),
2791                                     buf);
2792                         }
2793                         ASSERT3U(bufcnt, ==, buffers);
2794                         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
2795                         (void) refcount_remove_many(
2796                             &old_state->arcs_size, arc_hdr_size(hdr), hdr);
2797                 }
2798         }
2799
2800         if (HDR_HAS_L1HDR(hdr))
2801                 hdr->b_l1hdr.b_state = new_state;
2802
2803         /*
2804          * L2 headers should never be on the L2 state list since they don't
2805          * have L1 headers allocated.
2806          */
2807         ASSERT(multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_DATA]) &&
2808             multilist_is_empty(arc_l2c_only->arcs_list[ARC_BUFC_METADATA]));
2809 }
2810
2811 void
2812 arc_space_consume(uint64_t space, arc_space_type_t type)
2813 {
2814         ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2815
2816         switch (type) {
2817         case ARC_SPACE_DATA:
2818                 aggsum_add(&astat_data_size, space);
2819                 break;
2820         case ARC_SPACE_META:
2821                 aggsum_add(&astat_metadata_size, space);
2822                 break;
2823         case ARC_SPACE_BONUS:
2824                 aggsum_add(&astat_bonus_size, space);
2825                 break;
2826         case ARC_SPACE_DNODE:
2827                 aggsum_add(&astat_dnode_size, space);
2828                 break;
2829         case ARC_SPACE_DBUF:
2830                 aggsum_add(&astat_dbuf_size, space);
2831                 break;
2832         case ARC_SPACE_HDRS:
2833                 aggsum_add(&astat_hdr_size, space);
2834                 break;
2835         case ARC_SPACE_L2HDRS:
2836                 aggsum_add(&astat_l2_hdr_size, space);
2837                 break;
2838         }
2839
2840         if (type != ARC_SPACE_DATA)
2841                 aggsum_add(&arc_meta_used, space);
2842
2843         aggsum_add(&arc_size, space);
2844 }
2845
2846 void
2847 arc_space_return(uint64_t space, arc_space_type_t type)
2848 {
2849         ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
2850
2851         switch (type) {
2852         case ARC_SPACE_DATA:
2853                 aggsum_add(&astat_data_size, -space);
2854                 break;
2855         case ARC_SPACE_META:
2856                 aggsum_add(&astat_metadata_size, -space);
2857                 break;
2858         case ARC_SPACE_BONUS:
2859                 aggsum_add(&astat_bonus_size, -space);
2860                 break;
2861         case ARC_SPACE_DNODE:
2862                 aggsum_add(&astat_dnode_size, -space);
2863                 break;
2864         case ARC_SPACE_DBUF:
2865                 aggsum_add(&astat_dbuf_size, -space);
2866                 break;
2867         case ARC_SPACE_HDRS:
2868                 aggsum_add(&astat_hdr_size, -space);
2869                 break;
2870         case ARC_SPACE_L2HDRS:
2871                 aggsum_add(&astat_l2_hdr_size, -space);
2872                 break;
2873         }
2874
2875         if (type != ARC_SPACE_DATA) {
2876                 ASSERT(aggsum_compare(&arc_meta_used, space) >= 0);
2877                 /*
2878                  * We use the upper bound here rather than the precise value
2879                  * because the arc_meta_max value doesn't need to be
2880                  * precise. It's only consumed by humans via arcstats.
2881                  */
2882                 if (arc_meta_max < aggsum_upper_bound(&arc_meta_used))
2883                         arc_meta_max = aggsum_upper_bound(&arc_meta_used);
2884                 aggsum_add(&arc_meta_used, -space);
2885         }
2886
2887         ASSERT(aggsum_compare(&arc_size, space) >= 0);
2888         aggsum_add(&arc_size, -space);
2889 }
2890
2891 /*
2892  * Given a hdr and a buf, returns whether that buf can share its b_data buffer
2893  * with the hdr's b_pabd.
2894  */
2895 static boolean_t
2896 arc_can_share(arc_buf_hdr_t *hdr, arc_buf_t *buf)
2897 {
2898         /*
2899          * The criteria for sharing a hdr's data are:
2900          * 1. the hdr's compression matches the buf's compression
2901          * 2. the hdr doesn't need to be byteswapped
2902          * 3. the hdr isn't already being shared
2903          * 4. the buf is either compressed or it is the last buf in the hdr list
2904          *
2905          * Criterion #4 maintains the invariant that shared uncompressed
2906          * bufs must be the final buf in the hdr's b_buf list. Reading this, you
2907          * might ask, "if a compressed buf is allocated first, won't that be the
2908          * last thing in the list?", but in that case it's impossible to create
2909          * a shared uncompressed buf anyway (because the hdr must be compressed
2910          * to have the compressed buf). You might also think that #3 is
2911          * sufficient to make this guarantee, however it's possible
2912          * (specifically in the rare L2ARC write race mentioned in
2913          * arc_buf_alloc_impl()) there will be an existing uncompressed buf that
2914          * is sharable, but wasn't at the time of its allocation. Rather than
2915          * allow a new shared uncompressed buf to be created and then shuffle
2916          * the list around to make it the last element, this simply disallows
2917          * sharing if the new buf isn't the first to be added.
2918          */
2919         ASSERT3P(buf->b_hdr, ==, hdr);
2920         boolean_t hdr_compressed = HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF;
2921         boolean_t buf_compressed = ARC_BUF_COMPRESSED(buf) != 0;
2922         return (buf_compressed == hdr_compressed &&
2923             hdr->b_l1hdr.b_byteswap == DMU_BSWAP_NUMFUNCS &&
2924             !HDR_SHARED_DATA(hdr) &&
2925             (ARC_BUF_LAST(buf) || ARC_BUF_COMPRESSED(buf)));
2926 }
2927
2928 /*
2929  * Allocate a buf for this hdr. If you care about the data that's in the hdr,
2930  * or if you want a compressed buffer, pass those flags in. Returns 0 if the
2931  * copy was made successfully, or an error code otherwise.
2932  */
2933 static int
2934 arc_buf_alloc_impl(arc_buf_hdr_t *hdr, void *tag, boolean_t compressed,
2935     boolean_t fill, arc_buf_t **ret)
2936 {
2937         arc_buf_t *buf;
2938
2939         ASSERT(HDR_HAS_L1HDR(hdr));
2940         ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
2941         VERIFY(hdr->b_type == ARC_BUFC_DATA ||
2942             hdr->b_type == ARC_BUFC_METADATA);
2943         ASSERT3P(ret, !=, NULL);
2944         ASSERT3P(*ret, ==, NULL);
2945
2946         buf = *ret = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
2947         buf->b_hdr = hdr;
2948         buf->b_data = NULL;
2949         buf->b_next = hdr->b_l1hdr.b_buf;
2950         buf->b_flags = 0;
2951
2952         add_reference(hdr, tag);
2953
2954         /*
2955          * We're about to change the hdr's b_flags. We must either
2956          * hold the hash_lock or be undiscoverable.
2957          */
2958         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
2959
2960         /*
2961          * Only honor requests for compressed bufs if the hdr is actually
2962          * compressed.
2963          */
2964         if (compressed && HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF)
2965                 buf->b_flags |= ARC_BUF_FLAG_COMPRESSED;
2966
2967         /*
2968          * If the hdr's data can be shared then we share the data buffer and
2969          * set the appropriate bit in the hdr's b_flags to indicate the hdr is
2970          * sharing it's b_pabd with the arc_buf_t. Otherwise, we allocate a new
2971          * buffer to store the buf's data.
2972          *
2973          * There are two additional restrictions here because we're sharing
2974          * hdr -> buf instead of the usual buf -> hdr. First, the hdr can't be
2975          * actively involved in an L2ARC write, because if this buf is used by
2976          * an arc_write() then the hdr's data buffer will be released when the
2977          * write completes, even though the L2ARC write might still be using it.
2978          * Second, the hdr's ABD must be linear so that the buf's user doesn't
2979          * need to be ABD-aware.
2980          */
2981         boolean_t can_share = arc_can_share(hdr, buf) && !HDR_L2_WRITING(hdr) &&
2982             abd_is_linear(hdr->b_l1hdr.b_pabd);
2983
2984         /* Set up b_data and sharing */
2985         if (can_share) {
2986                 buf->b_data = abd_to_buf(hdr->b_l1hdr.b_pabd);
2987                 buf->b_flags |= ARC_BUF_FLAG_SHARED;
2988                 arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
2989         } else {
2990                 buf->b_data =
2991                     arc_get_data_buf(hdr, arc_buf_size(buf), buf);
2992                 ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
2993         }
2994         VERIFY3P(buf->b_data, !=, NULL);
2995
2996         hdr->b_l1hdr.b_buf = buf;
2997         hdr->b_l1hdr.b_bufcnt += 1;
2998
2999         /*
3000          * If the user wants the data from the hdr, we need to either copy or
3001          * decompress the data.
3002          */
3003         if (fill) {
3004                 return (arc_buf_fill(buf, ARC_BUF_COMPRESSED(buf) != 0));
3005         }
3006
3007         return (0);
3008 }
3009
3010 static char *arc_onloan_tag = "onloan";
3011
3012 static inline void
3013 arc_loaned_bytes_update(int64_t delta)
3014 {
3015         atomic_add_64(&arc_loaned_bytes, delta);
3016
3017         /* assert that it did not wrap around */
3018         ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
3019 }
3020
3021 /*
3022  * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
3023  * flight data by arc_tempreserve_space() until they are "returned". Loaned
3024  * buffers must be returned to the arc before they can be used by the DMU or
3025  * freed.
3026  */
3027 arc_buf_t *
3028 arc_loan_buf(spa_t *spa, boolean_t is_metadata, int size)
3029 {
3030         arc_buf_t *buf = arc_alloc_buf(spa, arc_onloan_tag,
3031             is_metadata ? ARC_BUFC_METADATA : ARC_BUFC_DATA, size);
3032
3033         arc_loaned_bytes_update(arc_buf_size(buf));
3034
3035         return (buf);
3036 }
3037
3038 arc_buf_t *
3039 arc_loan_compressed_buf(spa_t *spa, uint64_t psize, uint64_t lsize,
3040     enum zio_compress compression_type)
3041 {
3042         arc_buf_t *buf = arc_alloc_compressed_buf(spa, arc_onloan_tag,
3043             psize, lsize, compression_type);
3044
3045         arc_loaned_bytes_update(arc_buf_size(buf));
3046
3047         return (buf);
3048 }
3049
3050
3051 /*
3052  * Return a loaned arc buffer to the arc.
3053  */
3054 void
3055 arc_return_buf(arc_buf_t *buf, void *tag)
3056 {
3057         arc_buf_hdr_t *hdr = buf->b_hdr;
3058
3059         ASSERT3P(buf->b_data, !=, NULL);
3060         ASSERT(HDR_HAS_L1HDR(hdr));
3061         (void) refcount_add(&hdr->b_l1hdr.b_refcnt, tag);
3062         (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3063
3064         arc_loaned_bytes_update(-arc_buf_size(buf));
3065 }
3066
3067 /* Detach an arc_buf from a dbuf (tag) */
3068 void
3069 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
3070 {
3071         arc_buf_hdr_t *hdr = buf->b_hdr;
3072
3073         ASSERT3P(buf->b_data, !=, NULL);
3074         ASSERT(HDR_HAS_L1HDR(hdr));
3075         (void) refcount_add(&hdr->b_l1hdr.b_refcnt, arc_onloan_tag);
3076         (void) refcount_remove(&hdr->b_l1hdr.b_refcnt, tag);
3077
3078         arc_loaned_bytes_update(arc_buf_size(buf));
3079 }
3080
3081 static void
3082 l2arc_free_abd_on_write(abd_t *abd, size_t size, arc_buf_contents_t type)
3083 {
3084         l2arc_data_free_t *df = kmem_alloc(sizeof (*df), KM_SLEEP);
3085
3086         df->l2df_abd = abd;
3087         df->l2df_size = size;
3088         df->l2df_type = type;
3089         mutex_enter(&l2arc_free_on_write_mtx);
3090         list_insert_head(l2arc_free_on_write, df);
3091         mutex_exit(&l2arc_free_on_write_mtx);
3092 }
3093
3094 static void
3095 arc_hdr_free_on_write(arc_buf_hdr_t *hdr)
3096 {
3097         arc_state_t *state = hdr->b_l1hdr.b_state;
3098         arc_buf_contents_t type = arc_buf_type(hdr);
3099         uint64_t size = arc_hdr_size(hdr);
3100
3101         /* protected by hash lock, if in the hash table */
3102         if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
3103                 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3104                 ASSERT(state != arc_anon && state != arc_l2c_only);
3105
3106                 (void) refcount_remove_many(&state->arcs_esize[type],
3107                     size, hdr);
3108         }
3109         (void) refcount_remove_many(&state->arcs_size, size, hdr);
3110         if (type == ARC_BUFC_METADATA) {
3111                 arc_space_return(size, ARC_SPACE_META);
3112         } else {
3113                 ASSERT(type == ARC_BUFC_DATA);
3114                 arc_space_return(size, ARC_SPACE_DATA);
3115         }
3116
3117         l2arc_free_abd_on_write(hdr->b_l1hdr.b_pabd, size, type);
3118 }
3119
3120 /*
3121  * Share the arc_buf_t's data with the hdr. Whenever we are sharing the
3122  * data buffer, we transfer the refcount ownership to the hdr and update
3123  * the appropriate kstats.
3124  */
3125 static void
3126 arc_share_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3127 {
3128         arc_state_t *state = hdr->b_l1hdr.b_state;
3129
3130         ASSERT(arc_can_share(hdr, buf));
3131         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3132         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3133
3134         /*
3135          * Start sharing the data buffer. We transfer the
3136          * refcount ownership to the hdr since it always owns
3137          * the refcount whenever an arc_buf_t is shared.
3138          */
3139         refcount_transfer_ownership(&state->arcs_size, buf, hdr);
3140         hdr->b_l1hdr.b_pabd = abd_get_from_buf(buf->b_data, arc_buf_size(buf));
3141         abd_take_ownership_of_buf(hdr->b_l1hdr.b_pabd,
3142             HDR_ISTYPE_METADATA(hdr));
3143         arc_hdr_set_flags(hdr, ARC_FLAG_SHARED_DATA);
3144         buf->b_flags |= ARC_BUF_FLAG_SHARED;
3145
3146         /*
3147          * Since we've transferred ownership to the hdr we need
3148          * to increment its compressed and uncompressed kstats and
3149          * decrement the overhead size.
3150          */
3151         ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3152         ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3153         ARCSTAT_INCR(arcstat_overhead_size, -arc_buf_size(buf));
3154 }
3155
3156 static void
3157 arc_unshare_buf(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3158 {
3159         arc_state_t *state = hdr->b_l1hdr.b_state;
3160
3161         ASSERT(arc_buf_is_shared(buf));
3162         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3163         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3164
3165         /*
3166          * We are no longer sharing this buffer so we need
3167          * to transfer its ownership to the rightful owner.
3168          */
3169         refcount_transfer_ownership(&state->arcs_size, hdr, buf);
3170         arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3171         abd_release_ownership_of_buf(hdr->b_l1hdr.b_pabd);
3172         abd_put(hdr->b_l1hdr.b_pabd);
3173         hdr->b_l1hdr.b_pabd = NULL;
3174         buf->b_flags &= ~ARC_BUF_FLAG_SHARED;
3175
3176         /*
3177          * Since the buffer is no longer shared between
3178          * the arc buf and the hdr, count it as overhead.
3179          */
3180         ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3181         ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3182         ARCSTAT_INCR(arcstat_overhead_size, arc_buf_size(buf));
3183 }
3184
3185 /*
3186  * Remove an arc_buf_t from the hdr's buf list and return the last
3187  * arc_buf_t on the list. If no buffers remain on the list then return
3188  * NULL.
3189  */
3190 static arc_buf_t *
3191 arc_buf_remove(arc_buf_hdr_t *hdr, arc_buf_t *buf)
3192 {
3193         ASSERT(HDR_HAS_L1HDR(hdr));
3194         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3195
3196         arc_buf_t **bufp = &hdr->b_l1hdr.b_buf;
3197         arc_buf_t *lastbuf = NULL;
3198
3199         /*
3200          * Remove the buf from the hdr list and locate the last
3201          * remaining buffer on the list.
3202          */
3203         while (*bufp != NULL) {
3204                 if (*bufp == buf)
3205                         *bufp = buf->b_next;
3206
3207                 /*
3208                  * If we've removed a buffer in the middle of
3209                  * the list then update the lastbuf and update
3210                  * bufp.
3211                  */
3212                 if (*bufp != NULL) {
3213                         lastbuf = *bufp;
3214                         bufp = &(*bufp)->b_next;
3215                 }
3216         }
3217         buf->b_next = NULL;
3218         ASSERT3P(lastbuf, !=, buf);
3219         IMPLY(hdr->b_l1hdr.b_bufcnt > 0, lastbuf != NULL);
3220         IMPLY(hdr->b_l1hdr.b_bufcnt > 0, hdr->b_l1hdr.b_buf != NULL);
3221         IMPLY(lastbuf != NULL, ARC_BUF_LAST(lastbuf));
3222
3223         return (lastbuf);
3224 }
3225
3226 /*
3227  * Free up buf->b_data and pull the arc_buf_t off of the the arc_buf_hdr_t's
3228  * list and free it.
3229  */
3230 static void
3231 arc_buf_destroy_impl(arc_buf_t *buf)
3232 {
3233         arc_buf_hdr_t *hdr = buf->b_hdr;
3234
3235         /*
3236          * Free up the data associated with the buf but only if we're not
3237          * sharing this with the hdr. If we are sharing it with the hdr, the
3238          * hdr is responsible for doing the free.
3239          */
3240         if (buf->b_data != NULL) {
3241                 /*
3242                  * We're about to change the hdr's b_flags. We must either
3243                  * hold the hash_lock or be undiscoverable.
3244                  */
3245                 ASSERT(MUTEX_HELD(HDR_LOCK(hdr)) || HDR_EMPTY(hdr));
3246
3247                 arc_cksum_verify(buf);
3248 #ifdef illumos
3249                 arc_buf_unwatch(buf);
3250 #endif
3251
3252                 if (arc_buf_is_shared(buf)) {
3253                         arc_hdr_clear_flags(hdr, ARC_FLAG_SHARED_DATA);
3254                 } else {
3255                         uint64_t size = arc_buf_size(buf);
3256                         arc_free_data_buf(hdr, buf->b_data, size, buf);
3257                         ARCSTAT_INCR(arcstat_overhead_size, -size);
3258                 }
3259                 buf->b_data = NULL;
3260
3261                 ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3262                 hdr->b_l1hdr.b_bufcnt -= 1;
3263         }
3264
3265         arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
3266
3267         if (ARC_BUF_SHARED(buf) && !ARC_BUF_COMPRESSED(buf)) {
3268                 /*
3269                  * If the current arc_buf_t is sharing its data buffer with the
3270                  * hdr, then reassign the hdr's b_pabd to share it with the new
3271                  * buffer at the end of the list. The shared buffer is always
3272                  * the last one on the hdr's buffer list.
3273                  *
3274                  * There is an equivalent case for compressed bufs, but since
3275                  * they aren't guaranteed to be the last buf in the list and
3276                  * that is an exceedingly rare case, we just allow that space be
3277                  * wasted temporarily.
3278                  */
3279                 if (lastbuf != NULL) {
3280                         /* Only one buf can be shared at once */
3281                         VERIFY(!arc_buf_is_shared(lastbuf));
3282                         /* hdr is uncompressed so can't have compressed buf */
3283                         VERIFY(!ARC_BUF_COMPRESSED(lastbuf));
3284
3285                         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3286                         arc_hdr_free_pabd(hdr);
3287
3288                         /*
3289                          * We must setup a new shared block between the
3290                          * last buffer and the hdr. The data would have
3291                          * been allocated by the arc buf so we need to transfer
3292                          * ownership to the hdr since it's now being shared.
3293                          */
3294                         arc_share_buf(hdr, lastbuf);
3295                 }
3296         } else if (HDR_SHARED_DATA(hdr)) {
3297                 /*
3298                  * Uncompressed shared buffers are always at the end
3299                  * of the list. Compressed buffers don't have the
3300                  * same requirements. This makes it hard to
3301                  * simply assert that the lastbuf is shared so
3302                  * we rely on the hdr's compression flags to determine
3303                  * if we have a compressed, shared buffer.
3304                  */
3305                 ASSERT3P(lastbuf, !=, NULL);
3306                 ASSERT(arc_buf_is_shared(lastbuf) ||
3307                     HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
3308         }
3309
3310         /*
3311          * Free the checksum if we're removing the last uncompressed buf from
3312          * this hdr.
3313          */
3314         if (!arc_hdr_has_uncompressed_buf(hdr)) {
3315                 arc_cksum_free(hdr);
3316         }
3317
3318         /* clean up the buf */
3319         buf->b_hdr = NULL;
3320         kmem_cache_free(buf_cache, buf);
3321 }
3322
3323 static void
3324 arc_hdr_alloc_pabd(arc_buf_hdr_t *hdr)
3325 {
3326         ASSERT3U(HDR_GET_LSIZE(hdr), >, 0);
3327         ASSERT(HDR_HAS_L1HDR(hdr));
3328         ASSERT(!HDR_SHARED_DATA(hdr));
3329
3330         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3331         hdr->b_l1hdr.b_pabd = arc_get_data_abd(hdr, arc_hdr_size(hdr), hdr);
3332         hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3333         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3334
3335         ARCSTAT_INCR(arcstat_compressed_size, arc_hdr_size(hdr));
3336         ARCSTAT_INCR(arcstat_uncompressed_size, HDR_GET_LSIZE(hdr));
3337 }
3338
3339 static void
3340 arc_hdr_free_pabd(arc_buf_hdr_t *hdr)
3341 {
3342         ASSERT(HDR_HAS_L1HDR(hdr));
3343         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
3344
3345         /*
3346          * If the hdr is currently being written to the l2arc then
3347          * we defer freeing the data by adding it to the l2arc_free_on_write
3348          * list. The l2arc will free the data once it's finished
3349          * writing it to the l2arc device.
3350          */
3351         if (HDR_L2_WRITING(hdr)) {
3352                 arc_hdr_free_on_write(hdr);
3353                 ARCSTAT_BUMP(arcstat_l2_free_on_write);
3354         } else {
3355                 arc_free_data_abd(hdr, hdr->b_l1hdr.b_pabd,
3356                     arc_hdr_size(hdr), hdr);
3357         }
3358         hdr->b_l1hdr.b_pabd = NULL;
3359         hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
3360
3361         ARCSTAT_INCR(arcstat_compressed_size, -arc_hdr_size(hdr));
3362         ARCSTAT_INCR(arcstat_uncompressed_size, -HDR_GET_LSIZE(hdr));
3363 }
3364
3365 static arc_buf_hdr_t *
3366 arc_hdr_alloc(uint64_t spa, int32_t psize, int32_t lsize,
3367     enum zio_compress compression_type, arc_buf_contents_t type)
3368 {
3369         arc_buf_hdr_t *hdr;
3370
3371         VERIFY(type == ARC_BUFC_DATA || type == ARC_BUFC_METADATA);
3372
3373         hdr = kmem_cache_alloc(hdr_full_cache, KM_PUSHPAGE);
3374         ASSERT(HDR_EMPTY(hdr));
3375         ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3376         ASSERT3P(hdr->b_l1hdr.b_thawed, ==, NULL);
3377         HDR_SET_PSIZE(hdr, psize);
3378         HDR_SET_LSIZE(hdr, lsize);
3379         hdr->b_spa = spa;
3380         hdr->b_type = type;
3381         hdr->b_flags = 0;
3382         arc_hdr_set_flags(hdr, arc_bufc_to_flags(type) | ARC_FLAG_HAS_L1HDR);
3383         arc_hdr_set_compress(hdr, compression_type);
3384
3385         hdr->b_l1hdr.b_state = arc_anon;
3386         hdr->b_l1hdr.b_arc_access = 0;
3387         hdr->b_l1hdr.b_bufcnt = 0;
3388         hdr->b_l1hdr.b_buf = NULL;
3389
3390         /*
3391          * Allocate the hdr's buffer. This will contain either
3392          * the compressed or uncompressed data depending on the block
3393          * it references and compressed arc enablement.
3394          */
3395         arc_hdr_alloc_pabd(hdr);
3396         ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3397
3398         return (hdr);
3399 }
3400
3401 /*
3402  * Transition between the two allocation states for the arc_buf_hdr struct.
3403  * The arc_buf_hdr struct can be allocated with (hdr_full_cache) or without
3404  * (hdr_l2only_cache) the fields necessary for the L1 cache - the smaller
3405  * version is used when a cache buffer is only in the L2ARC in order to reduce
3406  * memory usage.
3407  */
3408 static arc_buf_hdr_t *
3409 arc_hdr_realloc(arc_buf_hdr_t *hdr, kmem_cache_t *old, kmem_cache_t *new)
3410 {
3411         ASSERT(HDR_HAS_L2HDR(hdr));
3412
3413         arc_buf_hdr_t *nhdr;
3414         l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3415
3416         ASSERT((old == hdr_full_cache && new == hdr_l2only_cache) ||
3417             (old == hdr_l2only_cache && new == hdr_full_cache));
3418
3419         nhdr = kmem_cache_alloc(new, KM_PUSHPAGE);
3420
3421         ASSERT(MUTEX_HELD(HDR_LOCK(hdr)));
3422         buf_hash_remove(hdr);
3423
3424         bcopy(hdr, nhdr, HDR_L2ONLY_SIZE);
3425
3426         if (new == hdr_full_cache) {
3427                 arc_hdr_set_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3428                 /*
3429                  * arc_access and arc_change_state need to be aware that a
3430                  * header has just come out of L2ARC, so we set its state to
3431                  * l2c_only even though it's about to change.
3432                  */
3433                 nhdr->b_l1hdr.b_state = arc_l2c_only;
3434
3435                 /* Verify previous threads set to NULL before freeing */
3436                 ASSERT3P(nhdr->b_l1hdr.b_pabd, ==, NULL);
3437         } else {
3438                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3439                 ASSERT0(hdr->b_l1hdr.b_bufcnt);
3440                 ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3441
3442                 /*
3443                  * If we've reached here, We must have been called from
3444                  * arc_evict_hdr(), as such we should have already been
3445                  * removed from any ghost list we were previously on
3446                  * (which protects us from racing with arc_evict_state),
3447                  * thus no locking is needed during this check.
3448                  */
3449                 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3450
3451                 /*
3452                  * A buffer must not be moved into the arc_l2c_only
3453                  * state if it's not finished being written out to the
3454                  * l2arc device. Otherwise, the b_l1hdr.b_pabd field
3455                  * might try to be accessed, even though it was removed.
3456                  */
3457                 VERIFY(!HDR_L2_WRITING(hdr));
3458                 VERIFY3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3459
3460 #ifdef ZFS_DEBUG
3461                 if (hdr->b_l1hdr.b_thawed != NULL) {
3462                         kmem_free(hdr->b_l1hdr.b_thawed, 1);
3463                         hdr->b_l1hdr.b_thawed = NULL;
3464                 }
3465 #endif
3466
3467                 arc_hdr_clear_flags(nhdr, ARC_FLAG_HAS_L1HDR);
3468         }
3469         /*
3470          * The header has been reallocated so we need to re-insert it into any
3471          * lists it was on.
3472          */
3473         (void) buf_hash_insert(nhdr, NULL);
3474
3475         ASSERT(list_link_active(&hdr->b_l2hdr.b_l2node));
3476
3477         mutex_enter(&dev->l2ad_mtx);
3478
3479         /*
3480          * We must place the realloc'ed header back into the list at
3481          * the same spot. Otherwise, if it's placed earlier in the list,
3482          * l2arc_write_buffers() could find it during the function's
3483          * write phase, and try to write it out to the l2arc.
3484          */
3485         list_insert_after(&dev->l2ad_buflist, hdr, nhdr);
3486         list_remove(&dev->l2ad_buflist, hdr);
3487
3488         mutex_exit(&dev->l2ad_mtx);
3489
3490         /*
3491          * Since we're using the pointer address as the tag when
3492          * incrementing and decrementing the l2ad_alloc refcount, we
3493          * must remove the old pointer (that we're about to destroy) and
3494          * add the new pointer to the refcount. Otherwise we'd remove
3495          * the wrong pointer address when calling arc_hdr_destroy() later.
3496          */
3497
3498         (void) refcount_remove_many(&dev->l2ad_alloc, arc_hdr_size(hdr), hdr);
3499         (void) refcount_add_many(&dev->l2ad_alloc, arc_hdr_size(nhdr), nhdr);
3500
3501         buf_discard_identity(hdr);
3502         kmem_cache_free(old, hdr);
3503
3504         return (nhdr);
3505 }
3506
3507 /*
3508  * Allocate a new arc_buf_hdr_t and arc_buf_t and return the buf to the caller.
3509  * The buf is returned thawed since we expect the consumer to modify it.
3510  */
3511 arc_buf_t *
3512 arc_alloc_buf(spa_t *spa, void *tag, arc_buf_contents_t type, int32_t size)
3513 {
3514         arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), size, size,
3515             ZIO_COMPRESS_OFF, type);
3516         ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3517
3518         arc_buf_t *buf = NULL;
3519         VERIFY0(arc_buf_alloc_impl(hdr, tag, B_FALSE, B_FALSE, &buf));
3520         arc_buf_thaw(buf);
3521
3522         return (buf);
3523 }
3524
3525 /*
3526  * Allocate a compressed buf in the same manner as arc_alloc_buf. Don't use this
3527  * for bufs containing metadata.
3528  */
3529 arc_buf_t *
3530 arc_alloc_compressed_buf(spa_t *spa, void *tag, uint64_t psize, uint64_t lsize,
3531     enum zio_compress compression_type)
3532 {
3533         ASSERT3U(lsize, >, 0);
3534         ASSERT3U(lsize, >=, psize);
3535         ASSERT(compression_type > ZIO_COMPRESS_OFF);
3536         ASSERT(compression_type < ZIO_COMPRESS_FUNCTIONS);
3537
3538         arc_buf_hdr_t *hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
3539             compression_type, ARC_BUFC_DATA);
3540         ASSERT(!MUTEX_HELD(HDR_LOCK(hdr)));
3541
3542         arc_buf_t *buf = NULL;
3543         VERIFY0(arc_buf_alloc_impl(hdr, tag, B_TRUE, B_FALSE, &buf));
3544         arc_buf_thaw(buf);
3545         ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
3546
3547         if (!arc_buf_is_shared(buf)) {
3548                 /*
3549                  * To ensure that the hdr has the correct data in it if we call
3550                  * arc_decompress() on this buf before it's been written to
3551                  * disk, it's easiest if we just set up sharing between the
3552                  * buf and the hdr.
3553                  */
3554                 ASSERT(!abd_is_linear(hdr->b_l1hdr.b_pabd));
3555                 arc_hdr_free_pabd(hdr);
3556                 arc_share_buf(hdr, buf);
3557         }
3558
3559         return (buf);
3560 }
3561
3562 static void
3563 arc_hdr_l2hdr_destroy(arc_buf_hdr_t *hdr)
3564 {
3565         l2arc_buf_hdr_t *l2hdr = &hdr->b_l2hdr;
3566         l2arc_dev_t *dev = l2hdr->b_dev;
3567         uint64_t psize = arc_hdr_size(hdr);
3568
3569         ASSERT(MUTEX_HELD(&dev->l2ad_mtx));
3570         ASSERT(HDR_HAS_L2HDR(hdr));
3571
3572         list_remove(&dev->l2ad_buflist, hdr);
3573
3574         ARCSTAT_INCR(arcstat_l2_psize, -psize);
3575         ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
3576
3577         vdev_space_update(dev->l2ad_vdev, -psize, 0, 0);
3578
3579         (void) refcount_remove_many(&dev->l2ad_alloc, psize, hdr);
3580         arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
3581 }
3582
3583 static void
3584 arc_hdr_destroy(arc_buf_hdr_t *hdr)
3585 {
3586         if (HDR_HAS_L1HDR(hdr)) {
3587                 ASSERT(hdr->b_l1hdr.b_buf == NULL ||
3588                     hdr->b_l1hdr.b_bufcnt > 0);
3589                 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
3590                 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
3591         }
3592         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3593         ASSERT(!HDR_IN_HASH_TABLE(hdr));
3594
3595         if (!HDR_EMPTY(hdr))
3596                 buf_discard_identity(hdr);
3597
3598         if (HDR_HAS_L2HDR(hdr)) {
3599                 l2arc_dev_t *dev = hdr->b_l2hdr.b_dev;
3600                 boolean_t buflist_held = MUTEX_HELD(&dev->l2ad_mtx);
3601
3602                 if (!buflist_held)
3603                         mutex_enter(&dev->l2ad_mtx);
3604
3605                 /*
3606                  * Even though we checked this conditional above, we
3607                  * need to check this again now that we have the
3608                  * l2ad_mtx. This is because we could be racing with
3609                  * another thread calling l2arc_evict() which might have
3610                  * destroyed this header's L2 portion as we were waiting
3611                  * to acquire the l2ad_mtx. If that happens, we don't
3612                  * want to re-destroy the header's L2 portion.
3613                  */
3614                 if (HDR_HAS_L2HDR(hdr)) {
3615                         l2arc_trim(hdr);
3616                         arc_hdr_l2hdr_destroy(hdr);
3617                 }
3618
3619                 if (!buflist_held)
3620                         mutex_exit(&dev->l2ad_mtx);
3621         }
3622
3623         if (HDR_HAS_L1HDR(hdr)) {
3624                 arc_cksum_free(hdr);
3625
3626                 while (hdr->b_l1hdr.b_buf != NULL)
3627                         arc_buf_destroy_impl(hdr->b_l1hdr.b_buf);
3628
3629 #ifdef ZFS_DEBUG
3630                 if (hdr->b_l1hdr.b_thawed != NULL) {
3631                         kmem_free(hdr->b_l1hdr.b_thawed, 1);
3632                         hdr->b_l1hdr.b_thawed = NULL;
3633                 }
3634 #endif
3635
3636                 if (hdr->b_l1hdr.b_pabd != NULL) {
3637                         arc_hdr_free_pabd(hdr);
3638                 }
3639         }
3640
3641         ASSERT3P(hdr->b_hash_next, ==, NULL);
3642         if (HDR_HAS_L1HDR(hdr)) {
3643                 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
3644                 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
3645                 kmem_cache_free(hdr_full_cache, hdr);
3646         } else {
3647                 kmem_cache_free(hdr_l2only_cache, hdr);
3648         }
3649 }
3650
3651 void
3652 arc_buf_destroy(arc_buf_t *buf, void* tag)
3653 {
3654         arc_buf_hdr_t *hdr = buf->b_hdr;
3655         kmutex_t *hash_lock = HDR_LOCK(hdr);
3656
3657         if (hdr->b_l1hdr.b_state == arc_anon) {
3658                 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
3659                 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3660                 VERIFY0(remove_reference(hdr, NULL, tag));
3661                 arc_hdr_destroy(hdr);
3662                 return;
3663         }
3664
3665         mutex_enter(hash_lock);
3666         ASSERT3P(hdr, ==, buf->b_hdr);
3667         ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
3668         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3669         ASSERT3P(hdr->b_l1hdr.b_state, !=, arc_anon);
3670         ASSERT3P(buf->b_data, !=, NULL);
3671
3672         (void) remove_reference(hdr, hash_lock, tag);
3673         arc_buf_destroy_impl(buf);
3674         mutex_exit(hash_lock);
3675 }
3676
3677 /*
3678  * Evict the arc_buf_hdr that is provided as a parameter. The resultant
3679  * state of the header is dependent on its state prior to entering this
3680  * function. The following transitions are possible:
3681  *
3682  *    - arc_mru -> arc_mru_ghost
3683  *    - arc_mfu -> arc_mfu_ghost
3684  *    - arc_mru_ghost -> arc_l2c_only
3685  *    - arc_mru_ghost -> deleted
3686  *    - arc_mfu_ghost -> arc_l2c_only
3687  *    - arc_mfu_ghost -> deleted
3688  */
3689 static int64_t
3690 arc_evict_hdr(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
3691 {
3692         arc_state_t *evicted_state, *state;
3693         int64_t bytes_evicted = 0;
3694         int min_lifetime = HDR_PRESCIENT_PREFETCH(hdr) ?
3695             zfs_arc_min_prescient_prefetch_ms : zfs_arc_min_prefetch_ms;
3696
3697         ASSERT(MUTEX_HELD(hash_lock));
3698         ASSERT(HDR_HAS_L1HDR(hdr));
3699
3700         state = hdr->b_l1hdr.b_state;
3701         if (GHOST_STATE(state)) {
3702                 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3703                 ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
3704
3705                 /*
3706                  * l2arc_write_buffers() relies on a header's L1 portion
3707                  * (i.e. its b_pabd field) during it's write phase.
3708                  * Thus, we cannot push a header onto the arc_l2c_only
3709                  * state (removing it's L1 piece) until the header is
3710                  * done being written to the l2arc.
3711                  */
3712                 if (HDR_HAS_L2HDR(hdr) && HDR_L2_WRITING(hdr)) {
3713                         ARCSTAT_BUMP(arcstat_evict_l2_skip);
3714                         return (bytes_evicted);
3715                 }
3716
3717                 ARCSTAT_BUMP(arcstat_deleted);
3718                 bytes_evicted += HDR_GET_LSIZE(hdr);
3719
3720                 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, hdr);
3721
3722                 ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
3723                 if (HDR_HAS_L2HDR(hdr)) {
3724                         /*
3725                          * This buffer is cached on the 2nd Level ARC;
3726                          * don't destroy the header.
3727                          */
3728                         arc_change_state(arc_l2c_only, hdr, hash_lock);
3729                         /*
3730                          * dropping from L1+L2 cached to L2-only,
3731                          * realloc to remove the L1 header.
3732                          */
3733                         hdr = arc_hdr_realloc(hdr, hdr_full_cache,
3734                             hdr_l2only_cache);
3735                 } else {
3736                         arc_change_state(arc_anon, hdr, hash_lock);
3737                         arc_hdr_destroy(hdr);
3738                 }
3739                 return (bytes_evicted);
3740         }
3741
3742         ASSERT(state == arc_mru || state == arc_mfu);
3743         evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3744
3745         /* prefetch buffers have a minimum lifespan */
3746         if (HDR_IO_IN_PROGRESS(hdr) ||
3747             ((hdr->b_flags & (ARC_FLAG_PREFETCH | ARC_FLAG_INDIRECT)) &&
3748             ddi_get_lbolt() - hdr->b_l1hdr.b_arc_access < min_lifetime * hz)) {
3749                 ARCSTAT_BUMP(arcstat_evict_skip);
3750                 return (bytes_evicted);
3751         }
3752
3753         ASSERT0(refcount_count(&hdr->b_l1hdr.b_refcnt));
3754         while (hdr->b_l1hdr.b_buf) {
3755                 arc_buf_t *buf = hdr->b_l1hdr.b_buf;
3756                 if (!mutex_tryenter(&buf->b_evict_lock)) {
3757                         ARCSTAT_BUMP(arcstat_mutex_miss);
3758                         break;
3759                 }
3760                 if (buf->b_data != NULL)
3761                         bytes_evicted += HDR_GET_LSIZE(hdr);
3762                 mutex_exit(&buf->b_evict_lock);
3763                 arc_buf_destroy_impl(buf);
3764         }
3765
3766         if (HDR_HAS_L2HDR(hdr)) {
3767                 ARCSTAT_INCR(arcstat_evict_l2_cached, HDR_GET_LSIZE(hdr));
3768         } else {
3769                 if (l2arc_write_eligible(hdr->b_spa, hdr)) {
3770                         ARCSTAT_INCR(arcstat_evict_l2_eligible,
3771                             HDR_GET_LSIZE(hdr));
3772                 } else {
3773                         ARCSTAT_INCR(arcstat_evict_l2_ineligible,
3774                             HDR_GET_LSIZE(hdr));
3775                 }
3776         }
3777
3778         if (hdr->b_l1hdr.b_bufcnt == 0) {
3779                 arc_cksum_free(hdr);
3780
3781                 bytes_evicted += arc_hdr_size(hdr);
3782
3783                 /*
3784                  * If this hdr is being evicted and has a compressed
3785                  * buffer then we discard it here before we change states.
3786                  * This ensures that the accounting is updated correctly
3787                  * in arc_free_data_impl().
3788                  */
3789                 arc_hdr_free_pabd(hdr);
3790
3791                 arc_change_state(evicted_state, hdr, hash_lock);
3792                 ASSERT(HDR_IN_HASH_TABLE(hdr));
3793                 arc_hdr_set_flags(hdr, ARC_FLAG_IN_HASH_TABLE);
3794                 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, hdr);
3795         }
3796
3797         return (bytes_evicted);
3798 }
3799
3800 static uint64_t
3801 arc_evict_state_impl(multilist_t *ml, int idx, arc_buf_hdr_t *marker,
3802     uint64_t spa, int64_t bytes)
3803 {
3804         multilist_sublist_t *mls;
3805         uint64_t bytes_evicted = 0;
3806         arc_buf_hdr_t *hdr;
3807         kmutex_t *hash_lock;
3808         int evict_count = 0;
3809
3810         ASSERT3P(marker, !=, NULL);
3811         IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3812
3813         mls = multilist_sublist_lock(ml, idx);
3814
3815         for (hdr = multilist_sublist_prev(mls, marker); hdr != NULL;
3816             hdr = multilist_sublist_prev(mls, marker)) {
3817                 if ((bytes != ARC_EVICT_ALL && bytes_evicted >= bytes) ||
3818                     (evict_count >= zfs_arc_evict_batch_limit))
3819                         break;
3820
3821                 /*
3822                  * To keep our iteration location, move the marker
3823                  * forward. Since we're not holding hdr's hash lock, we
3824                  * must be very careful and not remove 'hdr' from the
3825                  * sublist. Otherwise, other consumers might mistake the
3826                  * 'hdr' as not being on a sublist when they call the
3827                  * multilist_link_active() function (they all rely on
3828                  * the hash lock protecting concurrent insertions and
3829                  * removals). multilist_sublist_move_forward() was
3830                  * specifically implemented to ensure this is the case
3831                  * (only 'marker' will be removed and re-inserted).
3832                  */
3833                 multilist_sublist_move_forward(mls, marker);
3834
3835                 /*
3836                  * The only case where the b_spa field should ever be
3837                  * zero, is the marker headers inserted by
3838                  * arc_evict_state(). It's possible for multiple threads
3839                  * to be calling arc_evict_state() concurrently (e.g.
3840                  * dsl_pool_close() and zio_inject_fault()), so we must
3841                  * skip any markers we see from these other threads.
3842                  */
3843                 if (hdr->b_spa == 0)
3844                         continue;
3845
3846                 /* we're only interested in evicting buffers of a certain spa */
3847                 if (spa != 0 && hdr->b_spa != spa) {
3848                         ARCSTAT_BUMP(arcstat_evict_skip);
3849                         continue;
3850                 }
3851
3852                 hash_lock = HDR_LOCK(hdr);
3853
3854                 /*
3855                  * We aren't calling this function from any code path
3856                  * that would already be holding a hash lock, so we're
3857                  * asserting on this assumption to be defensive in case
3858                  * this ever changes. Without this check, it would be
3859                  * possible to incorrectly increment arcstat_mutex_miss
3860                  * below (e.g. if the code changed such that we called
3861                  * this function with a hash lock held).
3862                  */
3863                 ASSERT(!MUTEX_HELD(hash_lock));
3864
3865                 if (mutex_tryenter(hash_lock)) {
3866                         uint64_t evicted = arc_evict_hdr(hdr, hash_lock);
3867                         mutex_exit(hash_lock);
3868
3869                         bytes_evicted += evicted;
3870
3871                         /*
3872                          * If evicted is zero, arc_evict_hdr() must have
3873                          * decided to skip this header, don't increment
3874                          * evict_count in this case.
3875                          */
3876                         if (evicted != 0)
3877                                 evict_count++;
3878
3879                         /*
3880                          * If arc_size isn't overflowing, signal any
3881                          * threads that might happen to be waiting.
3882                          *
3883                          * For each header evicted, we wake up a single
3884                          * thread. If we used cv_broadcast, we could
3885                          * wake up "too many" threads causing arc_size
3886                          * to significantly overflow arc_c; since
3887                          * arc_get_data_impl() doesn't check for overflow
3888                          * when it's woken up (it doesn't because it's
3889                          * possible for the ARC to be overflowing while
3890                          * full of un-evictable buffers, and the
3891                          * function should proceed in this case).
3892                          *
3893                          * If threads are left sleeping, due to not
3894                          * using cv_broadcast, they will be woken up
3895                          * just before arc_reclaim_thread() sleeps.
3896                          */
3897                         mutex_enter(&arc_reclaim_lock);
3898                         if (!arc_is_overflowing())
3899                                 cv_signal(&arc_reclaim_waiters_cv);
3900                         mutex_exit(&arc_reclaim_lock);
3901                 } else {
3902                         ARCSTAT_BUMP(arcstat_mutex_miss);
3903                 }
3904         }
3905
3906         multilist_sublist_unlock(mls);
3907
3908         return (bytes_evicted);
3909 }
3910
3911 /*
3912  * Evict buffers from the given arc state, until we've removed the
3913  * specified number of bytes. Move the removed buffers to the
3914  * appropriate evict state.
3915  *
3916  * This function makes a "best effort". It skips over any buffers
3917  * it can't get a hash_lock on, and so, may not catch all candidates.
3918  * It may also return without evicting as much space as requested.
3919  *
3920  * If bytes is specified using the special value ARC_EVICT_ALL, this
3921  * will evict all available (i.e. unlocked and evictable) buffers from
3922  * the given arc state; which is used by arc_flush().
3923  */
3924 static uint64_t
3925 arc_evict_state(arc_state_t *state, uint64_t spa, int64_t bytes,
3926     arc_buf_contents_t type)
3927 {
3928         uint64_t total_evicted = 0;
3929         multilist_t *ml = state->arcs_list[type];
3930         int num_sublists;
3931         arc_buf_hdr_t **markers;
3932
3933         IMPLY(bytes < 0, bytes == ARC_EVICT_ALL);
3934
3935         num_sublists = multilist_get_num_sublists(ml);
3936
3937         /*
3938          * If we've tried to evict from each sublist, made some
3939          * progress, but still have not hit the target number of bytes
3940          * to evict, we want to keep trying. The markers allow us to
3941          * pick up where we left off for each individual sublist, rather
3942          * than starting from the tail each time.
3943          */
3944         markers = kmem_zalloc(sizeof (*markers) * num_sublists, KM_SLEEP);
3945         for (int i = 0; i < num_sublists; i++) {
3946                 markers[i] = kmem_cache_alloc(hdr_full_cache, KM_SLEEP);
3947
3948                 /*
3949                  * A b_spa of 0 is used to indicate that this header is
3950                  * a marker. This fact is used in arc_adjust_type() and
3951                  * arc_evict_state_impl().
3952                  */
3953                 markers[i]->b_spa = 0;
3954
3955                 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
3956                 multilist_sublist_insert_tail(mls, markers[i]);
3957                 multilist_sublist_unlock(mls);
3958         }
3959
3960         /*
3961          * While we haven't hit our target number of bytes to evict, or
3962          * we're evicting all available buffers.
3963          */
3964         while (total_evicted < bytes || bytes == ARC_EVICT_ALL) {
3965                 int sublist_idx = multilist_get_random_index(ml);
3966                 uint64_t scan_evicted = 0;
3967
3968                 /*
3969                  * Try to reduce pinned dnodes with a floor of arc_dnode_limit.
3970                  * Request that 10% of the LRUs be scanned by the superblock
3971                  * shrinker.
3972                  */
3973                 if (type == ARC_BUFC_DATA && aggsum_compare(&astat_dnode_size,
3974                     arc_dnode_limit) > 0) {
3975                         arc_prune_async((aggsum_upper_bound(&astat_dnode_size) -
3976                             arc_dnode_limit) / sizeof (dnode_t) /
3977                             zfs_arc_dnode_reduce_percent);
3978                 }
3979
3980                 /*
3981                  * Start eviction using a randomly selected sublist,
3982                  * this is to try and evenly balance eviction across all
3983                  * sublists. Always starting at the same sublist
3984                  * (e.g. index 0) would cause evictions to favor certain
3985                  * sublists over others.
3986                  */
3987                 for (int i = 0; i < num_sublists; i++) {
3988                         uint64_t bytes_remaining;
3989                         uint64_t bytes_evicted;
3990
3991                         if (bytes == ARC_EVICT_ALL)
3992                                 bytes_remaining = ARC_EVICT_ALL;
3993                         else if (total_evicted < bytes)
3994                                 bytes_remaining = bytes - total_evicted;
3995                         else
3996                                 break;
3997
3998                         bytes_evicted = arc_evict_state_impl(ml, sublist_idx,
3999                             markers[sublist_idx], spa, bytes_remaining);
4000
4001                         scan_evicted += bytes_evicted;
4002                         total_evicted += bytes_evicted;
4003
4004                         /* we've reached the end, wrap to the beginning */
4005                         if (++sublist_idx >= num_sublists)
4006                                 sublist_idx = 0;
4007                 }
4008
4009                 /*
4010                  * If we didn't evict anything during this scan, we have
4011                  * no reason to believe we'll evict more during another
4012                  * scan, so break the loop.
4013                  */
4014                 if (scan_evicted == 0) {
4015                         /* This isn't possible, let's make that obvious */
4016                         ASSERT3S(bytes, !=, 0);
4017
4018                         /*
4019                          * When bytes is ARC_EVICT_ALL, the only way to
4020                          * break the loop is when scan_evicted is zero.
4021                          * In that case, we actually have evicted enough,
4022                          * so we don't want to increment the kstat.
4023                          */
4024                         if (bytes != ARC_EVICT_ALL) {
4025                                 ASSERT3S(total_evicted, <, bytes);
4026                                 ARCSTAT_BUMP(arcstat_evict_not_enough);
4027                         }
4028
4029                         break;
4030                 }
4031         }
4032
4033         for (int i = 0; i < num_sublists; i++) {
4034                 multilist_sublist_t *mls = multilist_sublist_lock(ml, i);
4035                 multilist_sublist_remove(mls, markers[i]);
4036                 multilist_sublist_unlock(mls);
4037
4038                 kmem_cache_free(hdr_full_cache, markers[i]);
4039         }
4040         kmem_free(markers, sizeof (*markers) * num_sublists);
4041
4042         return (total_evicted);
4043 }
4044
4045 /*
4046  * Flush all "evictable" data of the given type from the arc state
4047  * specified. This will not evict any "active" buffers (i.e. referenced).
4048  *
4049  * When 'retry' is set to B_FALSE, the function will make a single pass
4050  * over the state and evict any buffers that it can. Since it doesn't
4051  * continually retry the eviction, it might end up leaving some buffers
4052  * in the ARC due to lock misses.
4053  *
4054  * When 'retry' is set to B_TRUE, the function will continually retry the
4055  * eviction until *all* evictable buffers have been removed from the
4056  * state. As a result, if concurrent insertions into the state are
4057  * allowed (e.g. if the ARC isn't shutting down), this function might
4058  * wind up in an infinite loop, continually trying to evict buffers.
4059  */
4060 static uint64_t
4061 arc_flush_state(arc_state_t *state, uint64_t spa, arc_buf_contents_t type,
4062     boolean_t retry)
4063 {
4064         uint64_t evicted = 0;
4065
4066         while (refcount_count(&state->arcs_esize[type]) != 0) {
4067                 evicted += arc_evict_state(state, spa, ARC_EVICT_ALL, type);
4068
4069                 if (!retry)
4070                         break;
4071         }
4072
4073         return (evicted);
4074 }
4075
4076 /*
4077  * Helper function for arc_prune_async() it is responsible for safely
4078  * handling the execution of a registered arc_prune_func_t.
4079  */
4080 static void
4081 arc_prune_task(void *ptr)
4082 {
4083         arc_prune_t *ap = (arc_prune_t *)ptr;
4084         arc_prune_func_t *func = ap->p_pfunc;
4085
4086         if (func != NULL)
4087                 func(ap->p_adjust, ap->p_private);
4088
4089         refcount_remove(&ap->p_refcnt, func);
4090 }
4091
4092 /*
4093  * Notify registered consumers they must drop holds on a portion of the ARC
4094  * buffered they reference.  This provides a mechanism to ensure the ARC can
4095  * honor the arc_meta_limit and reclaim otherwise pinned ARC buffers.  This
4096  * is analogous to dnlc_reduce_cache() but more generic.
4097  *
4098  * This operation is performed asynchronously so it may be safely called
4099  * in the context of the arc_reclaim_thread().  A reference is taken here
4100  * for each registered arc_prune_t and the arc_prune_task() is responsible
4101  * for releasing it once the registered arc_prune_func_t has completed.
4102  */
4103 static void
4104 arc_prune_async(int64_t adjust)
4105 {
4106         arc_prune_t *ap;
4107
4108         mutex_enter(&arc_prune_mtx);
4109         for (ap = list_head(&arc_prune_list); ap != NULL;
4110             ap = list_next(&arc_prune_list, ap)) {
4111
4112                 if (refcount_count(&ap->p_refcnt) >= 2)
4113                         continue;
4114
4115                 refcount_add(&ap->p_refcnt, ap->p_pfunc);
4116                 ap->p_adjust = adjust;
4117                 if (taskq_dispatch(arc_prune_taskq, arc_prune_task,
4118                     ap, TQ_SLEEP) == TASKQID_INVALID) {
4119                         refcount_remove(&ap->p_refcnt, ap->p_pfunc);
4120                         continue;
4121                 }
4122                 ARCSTAT_BUMP(arcstat_prune);
4123         }
4124         mutex_exit(&arc_prune_mtx);
4125 }
4126
4127 /*
4128  * Evict the specified number of bytes from the state specified,
4129  * restricting eviction to the spa and type given. This function
4130  * prevents us from trying to evict more from a state's list than
4131  * is "evictable", and to skip evicting altogether when passed a
4132  * negative value for "bytes". In contrast, arc_evict_state() will
4133  * evict everything it can, when passed a negative value for "bytes".
4134  */
4135 static uint64_t
4136 arc_adjust_impl(arc_state_t *state, uint64_t spa, int64_t bytes,
4137     arc_buf_contents_t type)
4138 {
4139         int64_t delta;
4140
4141         if (bytes > 0 && refcount_count(&state->arcs_esize[type]) > 0) {
4142                 delta = MIN(refcount_count(&state->arcs_esize[type]), bytes);
4143                 return (arc_evict_state(state, spa, delta, type));
4144         }
4145
4146         return (0);
4147 }
4148
4149 /*
4150  * The goal of this function is to evict enough meta data buffers from the
4151  * ARC in order to enforce the arc_meta_limit.  Achieving this is slightly
4152  * more complicated than it appears because it is common for data buffers
4153  * to have holds on meta data buffers.  In addition, dnode meta data buffers
4154  * will be held by the dnodes in the block preventing them from being freed.
4155  * This means we can't simply traverse the ARC and expect to always find
4156  * enough unheld meta data buffer to release.
4157  *
4158  * Therefore, this function has been updated to make alternating passes
4159  * over the ARC releasing data buffers and then newly unheld meta data
4160  * buffers.  This ensures forward progress is maintained and meta_used
4161  * will decrease.  Normally this is sufficient, but if required the ARC
4162  * will call the registered prune callbacks causing dentry and inodes to
4163  * be dropped from the VFS cache.  This will make dnode meta data buffers
4164  * available for reclaim.
4165  */
4166 static uint64_t
4167 arc_adjust_meta_balanced(uint64_t meta_used)
4168 {
4169         int64_t delta, prune = 0, adjustmnt;
4170         uint64_t total_evicted = 0;
4171         arc_buf_contents_t type = ARC_BUFC_DATA;
4172         int restarts = MAX(zfs_arc_meta_adjust_restarts, 0);
4173
4174 restart:
4175         /*
4176          * This slightly differs than the way we evict from the mru in
4177          * arc_adjust because we don't have a "target" value (i.e. no
4178          * "meta" arc_p). As a result, I think we can completely
4179          * cannibalize the metadata in the MRU before we evict the
4180          * metadata from the MFU. I think we probably need to implement a
4181          * "metadata arc_p" value to do this properly.
4182          */
4183         adjustmnt = meta_used - arc_meta_limit;
4184
4185         if (adjustmnt > 0 && refcount_count(&arc_mru->arcs_esize[type]) > 0) {
4186                 delta = MIN(refcount_count(&arc_mru->arcs_esize[type]),
4187                     adjustmnt);
4188                 total_evicted += arc_adjust_impl(arc_mru, 0, delta, type);
4189                 adjustmnt -= delta;
4190         }
4191
4192         /*
4193          * We can't afford to recalculate adjustmnt here. If we do,
4194          * new metadata buffers can sneak into the MRU or ANON lists,
4195          * thus penalize the MFU metadata. Although the fudge factor is
4196          * small, it has been empirically shown to be significant for
4197          * certain workloads (e.g. creating many empty directories). As
4198          * such, we use the original calculation for adjustmnt, and
4199          * simply decrement the amount of data evicted from the MRU.
4200          */
4201
4202         if (adjustmnt > 0 && refcount_count(&arc_mfu->arcs_esize[type]) > 0) {
4203                 delta = MIN(refcount_count(&arc_mfu->arcs_esize[type]),
4204                     adjustmnt);
4205                 total_evicted += arc_adjust_impl(arc_mfu, 0, delta, type);
4206         }
4207
4208         adjustmnt = meta_used - arc_meta_limit;
4209
4210         if (adjustmnt > 0 &&
4211             refcount_count(&arc_mru_ghost->arcs_esize[type]) > 0) {
4212                 delta = MIN(adjustmnt,
4213                     refcount_count(&arc_mru_ghost->arcs_esize[type]));
4214                 total_evicted += arc_adjust_impl(arc_mru_ghost, 0, delta, type);
4215                 adjustmnt -= delta;
4216         }
4217
4218         if (adjustmnt > 0 &&
4219             refcount_count(&arc_mfu_ghost->arcs_esize[type]) > 0) {
4220                 delta = MIN(adjustmnt,
4221                     refcount_count(&arc_mfu_ghost->arcs_esize[type]));
4222                 total_evicted += arc_adjust_impl(arc_mfu_ghost, 0, delta, type);
4223         }
4224
4225         /*
4226          * If after attempting to make the requested adjustment to the ARC
4227          * the meta limit is still being exceeded then request that the
4228          * higher layers drop some cached objects which have holds on ARC
4229          * meta buffers.  Requests to the upper layers will be made with
4230          * increasingly large scan sizes until the ARC is below the limit.
4231          */
4232         if (meta_used > arc_meta_limit) {
4233                 if (type == ARC_BUFC_DATA) {
4234                         type = ARC_BUFC_METADATA;
4235                 } else {
4236                         type = ARC_BUFC_DATA;
4237
4238                         if (zfs_arc_meta_prune) {
4239                                 prune += zfs_arc_meta_prune;
4240                                 arc_prune_async(prune);
4241                         }
4242                 }
4243
4244                 if (restarts > 0) {
4245                         restarts--;
4246                         goto restart;
4247                 }
4248         }
4249         return (total_evicted);
4250 }
4251
4252 /*
4253  * Evict metadata buffers from the cache, such that arc_meta_used is
4254  * capped by the arc_meta_limit tunable.
4255  */
4256 static uint64_t
4257 arc_adjust_meta_only(uint64_t meta_used)
4258 {
4259         uint64_t total_evicted = 0;
4260         int64_t target;
4261
4262         /*
4263          * If we're over the meta limit, we want to evict enough
4264          * metadata to get back under the meta limit. We don't want to
4265          * evict so much that we drop the MRU below arc_p, though. If
4266          * we're over the meta limit more than we're over arc_p, we
4267          * evict some from the MRU here, and some from the MFU below.
4268          */
4269         target = MIN((int64_t)(meta_used - arc_meta_limit),
4270             (int64_t)(refcount_count(&arc_anon->arcs_size) +
4271             refcount_count(&arc_mru->arcs_size) - arc_p));
4272
4273         total_evicted += arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4274
4275         /*
4276          * Similar to the above, we want to evict enough bytes to get us
4277          * below the meta limit, but not so much as to drop us below the
4278          * space allotted to the MFU (which is defined as arc_c - arc_p).
4279          */
4280         target = MIN((int64_t)(meta_used - arc_meta_limit),
4281             (int64_t)(refcount_count(&arc_mfu->arcs_size) -
4282             (arc_c - arc_p)));
4283
4284         total_evicted += arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4285
4286         return (total_evicted);
4287 }
4288
4289 static uint64_t
4290 arc_adjust_meta(uint64_t meta_used)
4291 {
4292         if (zfs_arc_meta_strategy == ARC_STRATEGY_META_ONLY)
4293                 return (arc_adjust_meta_only(meta_used));
4294         else
4295                 return (arc_adjust_meta_balanced(meta_used));
4296 }
4297
4298 /*
4299  * Return the type of the oldest buffer in the given arc state
4300  *
4301  * This function will select a random sublist of type ARC_BUFC_DATA and
4302  * a random sublist of type ARC_BUFC_METADATA. The tail of each sublist
4303  * is compared, and the type which contains the "older" buffer will be
4304  * returned.
4305  */
4306 static arc_buf_contents_t
4307 arc_adjust_type(arc_state_t *state)
4308 {
4309         multilist_t *data_ml = state->arcs_list[ARC_BUFC_DATA];
4310         multilist_t *meta_ml = state->arcs_list[ARC_BUFC_METADATA];
4311         int data_idx = multilist_get_random_index(data_ml);
4312         int meta_idx = multilist_get_random_index(meta_ml);
4313         multilist_sublist_t *data_mls;
4314         multilist_sublist_t *meta_mls;
4315         arc_buf_contents_t type;
4316         arc_buf_hdr_t *data_hdr;
4317         arc_buf_hdr_t *meta_hdr;
4318
4319         /*
4320          * We keep the sublist lock until we're finished, to prevent
4321          * the headers from being destroyed via arc_evict_state().
4322          */
4323         data_mls = multilist_sublist_lock(data_ml, data_idx);
4324         meta_mls = multilist_sublist_lock(meta_ml, meta_idx);
4325
4326         /*
4327          * These two loops are to ensure we skip any markers that
4328          * might be at the tail of the lists due to arc_evict_state().
4329          */
4330
4331         for (data_hdr = multilist_sublist_tail(data_mls); data_hdr != NULL;
4332             data_hdr = multilist_sublist_prev(data_mls, data_hdr)) {
4333                 if (data_hdr->b_spa != 0)
4334                         break;
4335         }
4336
4337         for (meta_hdr = multilist_sublist_tail(meta_mls); meta_hdr != NULL;
4338             meta_hdr = multilist_sublist_prev(meta_mls, meta_hdr)) {
4339                 if (meta_hdr->b_spa != 0)
4340                         break;
4341         }
4342
4343         if (data_hdr == NULL && meta_hdr == NULL) {
4344                 type = ARC_BUFC_DATA;
4345         } else if (data_hdr == NULL) {
4346                 ASSERT3P(meta_hdr, !=, NULL);
4347                 type = ARC_BUFC_METADATA;
4348         } else if (meta_hdr == NULL) {
4349                 ASSERT3P(data_hdr, !=, NULL);
4350                 type = ARC_BUFC_DATA;
4351         } else {
4352                 ASSERT3P(data_hdr, !=, NULL);
4353                 ASSERT3P(meta_hdr, !=, NULL);
4354
4355                 /* The headers can't be on the sublist without an L1 header */
4356                 ASSERT(HDR_HAS_L1HDR(data_hdr));
4357                 ASSERT(HDR_HAS_L1HDR(meta_hdr));
4358
4359                 if (data_hdr->b_l1hdr.b_arc_access <
4360                     meta_hdr->b_l1hdr.b_arc_access) {
4361                         type = ARC_BUFC_DATA;
4362                 } else {
4363                         type = ARC_BUFC_METADATA;
4364                 }
4365         }
4366
4367         multilist_sublist_unlock(meta_mls);
4368         multilist_sublist_unlock(data_mls);
4369
4370         return (type);
4371 }
4372
4373 /*
4374  * Evict buffers from the cache, such that arc_size is capped by arc_c.
4375  */
4376 static uint64_t
4377 arc_adjust(void)
4378 {
4379         uint64_t total_evicted = 0;
4380         uint64_t bytes;
4381         int64_t target;
4382         uint64_t asize = aggsum_value(&arc_size);
4383         uint64_t ameta = aggsum_value(&arc_meta_used);
4384
4385         /*
4386          * If we're over arc_meta_limit, we want to correct that before
4387          * potentially evicting data buffers below.
4388          */
4389         total_evicted += arc_adjust_meta(ameta);
4390
4391         /*
4392          * Adjust MRU size
4393          *
4394          * If we're over the target cache size, we want to evict enough
4395          * from the list to get back to our target size. We don't want
4396          * to evict too much from the MRU, such that it drops below
4397          * arc_p. So, if we're over our target cache size more than
4398          * the MRU is over arc_p, we'll evict enough to get back to
4399          * arc_p here, and then evict more from the MFU below.
4400          */
4401         target = MIN((int64_t)(asize - arc_c),
4402             (int64_t)(refcount_count(&arc_anon->arcs_size) +
4403             refcount_count(&arc_mru->arcs_size) + ameta - arc_p));
4404
4405         /*
4406          * If we're below arc_meta_min, always prefer to evict data.
4407          * Otherwise, try to satisfy the requested number of bytes to
4408          * evict from the type which contains older buffers; in an
4409          * effort to keep newer buffers in the cache regardless of their
4410          * type. If we cannot satisfy the number of bytes from this
4411          * type, spill over into the next type.
4412          */
4413         if (arc_adjust_type(arc_mru) == ARC_BUFC_METADATA &&
4414             ameta > arc_meta_min) {
4415                 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4416                 total_evicted += bytes;
4417
4418                 /*
4419                  * If we couldn't evict our target number of bytes from
4420                  * metadata, we try to get the rest from data.
4421                  */
4422                 target -= bytes;
4423
4424                 total_evicted +=
4425                     arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4426         } else {
4427                 bytes = arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_DATA);
4428                 total_evicted += bytes;
4429
4430                 /*
4431                  * If we couldn't evict our target number of bytes from
4432                  * data, we try to get the rest from metadata.
4433                  */
4434                 target -= bytes;
4435
4436                 total_evicted +=
4437                     arc_adjust_impl(arc_mru, 0, target, ARC_BUFC_METADATA);
4438         }
4439
4440         /*
4441          * Adjust MFU size
4442          *
4443          * Now that we've tried to evict enough from the MRU to get its
4444          * size back to arc_p, if we're still above the target cache
4445          * size, we evict the rest from the MFU.
4446          */
4447         target = asize - arc_c;
4448
4449         if (arc_adjust_type(arc_mfu) == ARC_BUFC_METADATA &&
4450             ameta > arc_meta_min) {
4451                 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4452                 total_evicted += bytes;
4453
4454                 /*
4455                  * If we couldn't evict our target number of bytes from
4456                  * metadata, we try to get the rest from data.
4457                  */
4458                 target -= bytes;
4459
4460                 total_evicted +=
4461                     arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4462         } else {
4463                 bytes = arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_DATA);
4464                 total_evicted += bytes;
4465
4466                 /*
4467                  * If we couldn't evict our target number of bytes from
4468                  * data, we try to get the rest from data.
4469                  */
4470                 target -= bytes;
4471
4472                 total_evicted +=
4473                     arc_adjust_impl(arc_mfu, 0, target, ARC_BUFC_METADATA);
4474         }
4475
4476         /*
4477          * Adjust ghost lists
4478          *
4479          * In addition to the above, the ARC also defines target values
4480          * for the ghost lists. The sum of the mru list and mru ghost
4481          * list should never exceed the target size of the cache, and
4482          * the sum of the mru list, mfu list, mru ghost list, and mfu
4483          * ghost list should never exceed twice the target size of the
4484          * cache. The following logic enforces these limits on the ghost
4485          * caches, and evicts from them as needed.
4486          */
4487         target = refcount_count(&arc_mru->arcs_size) +
4488             refcount_count(&arc_mru_ghost->arcs_size) - arc_c;
4489
4490         bytes = arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_DATA);
4491         total_evicted += bytes;
4492
4493         target -= bytes;
4494
4495         total_evicted +=
4496             arc_adjust_impl(arc_mru_ghost, 0, target, ARC_BUFC_METADATA);
4497
4498         /*
4499          * We assume the sum of the mru list and mfu list is less than
4500          * or equal to arc_c (we enforced this above), which means we
4501          * can use the simpler of the two equations below:
4502          *
4503          *      mru + mfu + mru ghost + mfu ghost <= 2 * arc_c
4504          *                  mru ghost + mfu ghost <= arc_c
4505          */
4506         target = refcount_count(&arc_mru_ghost->arcs_size) +
4507             refcount_count(&arc_mfu_ghost->arcs_size) - arc_c;
4508
4509         bytes = arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_DATA);
4510         total_evicted += bytes;
4511
4512         target -= bytes;
4513
4514         total_evicted +=
4515             arc_adjust_impl(arc_mfu_ghost, 0, target, ARC_BUFC_METADATA);
4516
4517         return (total_evicted);
4518 }
4519
4520 void
4521 arc_flush(spa_t *spa, boolean_t retry)
4522 {
4523         uint64_t guid = 0;
4524
4525         /*
4526          * If retry is B_TRUE, a spa must not be specified since we have
4527          * no good way to determine if all of a spa's buffers have been
4528          * evicted from an arc state.
4529          */
4530         ASSERT(!retry || spa == 0);
4531
4532         if (spa != NULL)
4533                 guid = spa_load_guid(spa);
4534
4535         (void) arc_flush_state(arc_mru, guid, ARC_BUFC_DATA, retry);
4536         (void) arc_flush_state(arc_mru, guid, ARC_BUFC_METADATA, retry);
4537
4538         (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_DATA, retry);
4539         (void) arc_flush_state(arc_mfu, guid, ARC_BUFC_METADATA, retry);
4540
4541         (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_DATA, retry);
4542         (void) arc_flush_state(arc_mru_ghost, guid, ARC_BUFC_METADATA, retry);
4543
4544         (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_DATA, retry);
4545         (void) arc_flush_state(arc_mfu_ghost, guid, ARC_BUFC_METADATA, retry);
4546 }
4547
4548 void
4549 arc_shrink(int64_t to_free)
4550 {
4551         uint64_t asize = aggsum_value(&arc_size);
4552         if (arc_c > arc_c_min) {
4553                 DTRACE_PROBE4(arc__shrink, uint64_t, arc_c, uint64_t,
4554                         arc_c_min, uint64_t, arc_p, uint64_t, to_free);
4555                 if (arc_c > arc_c_min + to_free)
4556                         atomic_add_64(&arc_c, -to_free);
4557                 else
4558                         arc_c = arc_c_min;
4559
4560                 atomic_add_64(&arc_p, -(arc_p >> arc_shrink_shift));
4561                 if (asize < arc_c)
4562                         arc_c = MAX(asize, arc_c_min);
4563                 if (arc_p > arc_c)
4564                         arc_p = (arc_c >> 1);
4565
4566                 DTRACE_PROBE2(arc__shrunk, uint64_t, arc_c, uint64_t,
4567                         arc_p);
4568
4569                 ASSERT(arc_c >= arc_c_min);
4570                 ASSERT((int64_t)arc_p >= 0);
4571         }
4572
4573         if (asize > arc_c) {
4574                 DTRACE_PROBE2(arc__shrink_adjust, uint64_t, asize,
4575                         uint64_t, arc_c);
4576                 (void) arc_adjust();
4577         }
4578 }
4579
4580 typedef enum free_memory_reason_t {
4581         FMR_UNKNOWN,
4582         FMR_NEEDFREE,
4583         FMR_LOTSFREE,
4584         FMR_SWAPFS_MINFREE,
4585         FMR_PAGES_PP_MAXIMUM,
4586         FMR_HEAP_ARENA,
4587         FMR_ZIO_ARENA,
4588 } free_memory_reason_t;
4589
4590 int64_t last_free_memory;
4591 free_memory_reason_t last_free_reason;
4592
4593 /*
4594  * Additional reserve of pages for pp_reserve.
4595  */
4596 int64_t arc_pages_pp_reserve = 64;
4597
4598 /*
4599  * Additional reserve of pages for swapfs.
4600  */
4601 int64_t arc_swapfs_reserve = 64;
4602
4603 /*
4604  * Return the amount of memory that can be consumed before reclaim will be
4605  * needed.  Positive if there is sufficient free memory, negative indicates
4606  * the amount of memory that needs to be freed up.
4607  */
4608 static int64_t
4609 arc_available_memory(void)
4610 {
4611         int64_t lowest = INT64_MAX;
4612         int64_t n;
4613         free_memory_reason_t r = FMR_UNKNOWN;
4614
4615 #ifdef _KERNEL
4616 #ifdef __FreeBSD__
4617         /*
4618          * Cooperate with pagedaemon when it's time for it to scan
4619          * and reclaim some pages.
4620          */
4621         n = PAGESIZE * ((int64_t)freemem - zfs_arc_free_target);
4622         if (n < lowest) {
4623                 lowest = n;
4624                 r = FMR_LOTSFREE;
4625         }
4626
4627 #else
4628         if (needfree > 0) {
4629                 n = PAGESIZE * (-needfree);
4630                 if (n < lowest) {
4631                         lowest = n;
4632                         r = FMR_NEEDFREE;
4633                 }
4634         }
4635
4636         /*
4637          * check that we're out of range of the pageout scanner.  It starts to
4638          * schedule paging if freemem is less than lotsfree and needfree.
4639          * lotsfree is the high-water mark for pageout, and needfree is the
4640          * number of needed free pages.  We add extra pages here to make sure
4641          * the scanner doesn't start up while we're freeing memory.
4642          */
4643         n = PAGESIZE * (freemem - lotsfree - needfree - desfree);
4644         if (n < lowest) {
4645                 lowest = n;
4646                 r = FMR_LOTSFREE;
4647         }
4648
4649         /*
4650          * check to make sure that swapfs has enough space so that anon
4651          * reservations can still succeed. anon_resvmem() checks that the
4652          * availrmem is greater than swapfs_minfree, and the number of reserved
4653          * swap pages.  We also add a bit of extra here just to prevent
4654          * circumstances from getting really dire.
4655          */
4656         n = PAGESIZE * (availrmem - swapfs_minfree - swapfs_reserve -
4657             desfree - arc_swapfs_reserve);
4658         if (n < lowest) {
4659                 lowest = n;
4660                 r = FMR_SWAPFS_MINFREE;
4661         }
4662
4663
4664         /*
4665          * Check that we have enough availrmem that memory locking (e.g., via
4666          * mlock(3C) or memcntl(2)) can still succeed.  (pages_pp_maximum
4667          * stores the number of pages that cannot be locked; when availrmem
4668          * drops below pages_pp_maximum, page locking mechanisms such as
4669          * page_pp_lock() will fail.)
4670          */
4671         n = PAGESIZE * (availrmem - pages_pp_maximum -
4672             arc_pages_pp_reserve);
4673         if (n < lowest) {
4674                 lowest = n;
4675                 r = FMR_PAGES_PP_MAXIMUM;
4676         }
4677
4678 #endif  /* __FreeBSD__ */
4679 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
4680         /*
4681          * If we're on an i386 platform, it's possible that we'll exhaust the
4682          * kernel heap space before we ever run out of available physical
4683          * memory.  Most checks of the size of the heap_area compare against
4684          * tune.t_minarmem, which is the minimum available real memory that we
4685          * can have in the system.  However, this is generally fixed at 25 pages
4686          * which is so low that it's useless.  In this comparison, we seek to
4687          * calculate the total heap-size, and reclaim if more than 3/4ths of the
4688          * heap is allocated.  (Or, in the calculation, if less than 1/4th is
4689          * free)
4690          */
4691         n = uma_avail() - (long)(uma_limit() / 4);
4692         if (n < lowest) {
4693                 lowest = n;
4694                 r = FMR_HEAP_ARENA;
4695         }
4696 #endif
4697
4698         /*
4699          * If zio data pages are being allocated out of a separate heap segment,
4700          * then enforce that the size of available vmem for this arena remains
4701          * above about 1/4th (1/(2^arc_zio_arena_free_shift)) free.
4702          *
4703          * Note that reducing the arc_zio_arena_free_shift keeps more virtual
4704          * memory (in the zio_arena) free, which can avoid memory
4705          * fragmentation issues.
4706          */
4707         if (zio_arena != NULL) {
4708                 n = (int64_t)vmem_size(zio_arena, VMEM_FREE) -
4709                     (vmem_size(zio_arena, VMEM_ALLOC) >>
4710                     arc_zio_arena_free_shift);
4711                 if (n < lowest) {
4712                         lowest = n;
4713                         r = FMR_ZIO_ARENA;
4714                 }
4715         }
4716
4717 #else   /* _KERNEL */
4718         /* Every 100 calls, free a small amount */
4719         if (spa_get_random(100) == 0)
4720                 lowest = -1024;
4721 #endif  /* _KERNEL */
4722
4723         last_free_memory = lowest;
4724         last_free_reason = r;
4725         DTRACE_PROBE2(arc__available_memory, int64_t, lowest, int, r);
4726         return (lowest);
4727 }
4728
4729
4730 /*
4731  * Determine if the system is under memory pressure and is asking
4732  * to reclaim memory. A return value of B_TRUE indicates that the system
4733  * is under memory pressure and that the arc should adjust accordingly.
4734  */
4735 static boolean_t
4736 arc_reclaim_needed(void)
4737 {
4738         return (arc_available_memory() < 0);
4739 }
4740
4741 extern kmem_cache_t     *zio_buf_cache[];
4742 extern kmem_cache_t     *zio_data_buf_cache[];
4743 extern kmem_cache_t     *range_seg_cache;
4744 extern kmem_cache_t     *abd_chunk_cache;
4745
4746 static __noinline void
4747 arc_kmem_reap_now(void)
4748 {
4749         size_t                  i;
4750         kmem_cache_t            *prev_cache = NULL;
4751         kmem_cache_t            *prev_data_cache = NULL;
4752
4753         DTRACE_PROBE(arc__kmem_reap_start);
4754 #ifdef _KERNEL
4755         if (aggsum_compare(&arc_meta_used, arc_meta_limit) >= 0) {
4756                 /*
4757                  * We are exceeding our meta-data cache limit.
4758                  * Purge some DNLC entries to release holds on meta-data.
4759                  */
4760                 dnlc_reduce_cache((void *)(uintptr_t)arc_reduce_dnlc_percent);
4761         }
4762 #if defined(__i386)
4763         /*
4764          * Reclaim unused memory from all kmem caches.
4765          */
4766         kmem_reap();
4767 #endif
4768 #endif
4769
4770         /*
4771          * If a kmem reap is already active, don't schedule more.  We must
4772          * check for this because kmem_cache_reap_soon() won't actually
4773          * block on the cache being reaped (this is to prevent callers from
4774          * becoming implicitly blocked by a system-wide kmem reap -- which,
4775          * on a system with many, many full magazines, can take minutes).
4776          */
4777         if (kmem_cache_reap_active())
4778                 return;
4779
4780         for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
4781                 if (zio_buf_cache[i] != prev_cache) {
4782                         prev_cache = zio_buf_cache[i];
4783                         kmem_cache_reap_soon(zio_buf_cache[i]);
4784                 }
4785                 if (zio_data_buf_cache[i] != prev_data_cache) {
4786                         prev_data_cache = zio_data_buf_cache[i];
4787                         kmem_cache_reap_soon(zio_data_buf_cache[i]);
4788                 }
4789         }
4790         kmem_cache_reap_soon(abd_chunk_cache);
4791         kmem_cache_reap_soon(buf_cache);
4792         kmem_cache_reap_soon(hdr_full_cache);
4793         kmem_cache_reap_soon(hdr_l2only_cache);
4794         kmem_cache_reap_soon(range_seg_cache);
4795
4796 #ifdef illumos
4797         if (zio_arena != NULL) {
4798                 /*
4799                  * Ask the vmem arena to reclaim unused memory from its
4800                  * quantum caches.
4801                  */
4802                 vmem_qcache_reap(zio_arena);
4803         }
4804 #endif
4805         DTRACE_PROBE(arc__kmem_reap_end);
4806 }
4807
4808 /*
4809  * Threads can block in arc_get_data_impl() waiting for this thread to evict
4810  * enough data and signal them to proceed. When this happens, the threads in
4811  * arc_get_data_impl() are sleeping while holding the hash lock for their
4812  * particular arc header. Thus, we must be careful to never sleep on a
4813  * hash lock in this thread. This is to prevent the following deadlock:
4814  *
4815  *  - Thread A sleeps on CV in arc_get_data_impl() holding hash lock "L",
4816  *    waiting for the reclaim thread to signal it.
4817  *
4818  *  - arc_reclaim_thread() tries to acquire hash lock "L" using mutex_enter,
4819  *    fails, and goes to sleep forever.
4820  *
4821  * This possible deadlock is avoided by always acquiring a hash lock
4822  * using mutex_tryenter() from arc_reclaim_thread().
4823  */
4824 /* ARGSUSED */
4825 static void
4826 arc_reclaim_thread(void *unused __unused)
4827 {
4828         hrtime_t                growtime = 0;
4829         hrtime_t                kmem_reap_time = 0;
4830         callb_cpr_t             cpr;
4831
4832         CALLB_CPR_INIT(&cpr, &arc_reclaim_lock, callb_generic_cpr, FTAG);
4833
4834         mutex_enter(&arc_reclaim_lock);
4835         while (!arc_reclaim_thread_exit) {
4836                 uint64_t evicted = 0;
4837
4838                 /*
4839                  * This is necessary in order for the mdb ::arc dcmd to
4840                  * show up to date information. Since the ::arc command
4841                  * does not call the kstat's update function, without
4842                  * this call, the command may show stale stats for the
4843                  * anon, mru, mru_ghost, mfu, and mfu_ghost lists. Even
4844                  * with this change, the data might be up to 1 second
4845                  * out of date; but that should suffice. The arc_state_t
4846                  * structures can be queried directly if more accurate
4847                  * information is needed.
4848                  */
4849                 if (arc_ksp != NULL)
4850                         arc_ksp->ks_update(arc_ksp, KSTAT_READ);
4851
4852                 mutex_exit(&arc_reclaim_lock);
4853
4854                 /*
4855                  * We call arc_adjust() before (possibly) calling
4856                  * arc_kmem_reap_now(), so that we can wake up
4857                  * arc_get_data_impl() sooner.
4858                  */
4859                 evicted = arc_adjust();
4860
4861                 int64_t free_memory = arc_available_memory();
4862                 if (free_memory < 0) {
4863                         hrtime_t curtime = gethrtime();
4864                         arc_no_grow = B_TRUE;
4865                         arc_warm = B_TRUE;
4866
4867                         /*
4868                          * Wait at least zfs_grow_retry (default 60) seconds
4869                          * before considering growing.
4870                          */
4871                         growtime = curtime + SEC2NSEC(arc_grow_retry);
4872
4873                         /*
4874                          * Wait at least arc_kmem_cache_reap_retry_ms
4875                          * between arc_kmem_reap_now() calls. Without
4876                          * this check it is possible to end up in a
4877                          * situation where we spend lots of time
4878                          * reaping caches, while we're near arc_c_min.
4879                          */
4880                         if (curtime >= kmem_reap_time) {
4881                                 arc_kmem_reap_now();
4882                                 kmem_reap_time = gethrtime() +
4883                                     MSEC2NSEC(arc_kmem_cache_reap_retry_ms);
4884                         }
4885
4886                         /*
4887                          * If we are still low on memory, shrink the ARC
4888                          * so that we have arc_shrink_min free space.
4889                          */
4890                         free_memory = arc_available_memory();
4891
4892                         int64_t to_free =
4893                             (arc_c >> arc_shrink_shift) - free_memory;
4894                         if (to_free > 0) {
4895 #ifdef _KERNEL
4896 #ifdef illumos
4897                                 to_free = MAX(to_free, ptob(needfree));
4898 #endif
4899 #endif
4900                                 arc_shrink(to_free);
4901                         }
4902                 } else if (free_memory < arc_c >> arc_no_grow_shift) {
4903                         arc_no_grow = B_TRUE;
4904                 } else if (gethrtime() >= growtime) {
4905                         arc_no_grow = B_FALSE;
4906                 }
4907
4908                 mutex_enter(&arc_reclaim_lock);
4909
4910                 /*
4911                  * If evicted is zero, we couldn't evict anything via
4912                  * arc_adjust(). This could be due to hash lock
4913                  * collisions, but more likely due to the majority of
4914                  * arc buffers being unevictable. Therefore, even if
4915                  * arc_size is above arc_c, another pass is unlikely to
4916                  * be helpful and could potentially cause us to enter an
4917                  * infinite loop.
4918                  */
4919                 if (aggsum_compare(&arc_size, arc_c) <= 0|| evicted == 0) {
4920                         /*
4921                          * We're either no longer overflowing, or we
4922                          * can't evict anything more, so we should wake
4923                          * up any threads before we go to sleep.
4924                          */
4925                         cv_broadcast(&arc_reclaim_waiters_cv);
4926
4927                         /*
4928                          * Block until signaled, or after one second (we
4929                          * might need to perform arc_kmem_reap_now()
4930                          * even if we aren't being signalled)
4931                          */
4932                         CALLB_CPR_SAFE_BEGIN(&cpr);
4933                         (void) cv_timedwait_hires(&arc_reclaim_thread_cv,
4934                             &arc_reclaim_lock, SEC2NSEC(1), MSEC2NSEC(1), 0);
4935                         CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_lock);
4936                 }
4937         }
4938
4939         arc_reclaim_thread_exit = B_FALSE;
4940         cv_broadcast(&arc_reclaim_thread_cv);
4941         CALLB_CPR_EXIT(&cpr);           /* drops arc_reclaim_lock */
4942         thread_exit();
4943 }
4944
4945 static u_int arc_dnlc_evicts_arg;
4946 extern struct vfsops zfs_vfsops;
4947
4948 static void
4949 arc_dnlc_evicts_thread(void *dummy __unused)
4950 {
4951         callb_cpr_t cpr;
4952         u_int percent;
4953
4954         CALLB_CPR_INIT(&cpr, &arc_dnlc_evicts_lock, callb_generic_cpr, FTAG);
4955
4956         mutex_enter(&arc_dnlc_evicts_lock);
4957         while (!arc_dnlc_evicts_thread_exit) {
4958                 CALLB_CPR_SAFE_BEGIN(&cpr);
4959                 (void) cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
4960                 CALLB_CPR_SAFE_END(&cpr, &arc_dnlc_evicts_lock);
4961                 if (arc_dnlc_evicts_arg != 0) {
4962                         percent = arc_dnlc_evicts_arg;
4963                         mutex_exit(&arc_dnlc_evicts_lock);
4964 #ifdef _KERNEL
4965                         vnlru_free(desiredvnodes * percent / 100, &zfs_vfsops);
4966 #endif
4967                         mutex_enter(&arc_dnlc_evicts_lock);
4968                         /*
4969                          * Clear our token only after vnlru_free()
4970                          * pass is done, to avoid false queueing of
4971                          * the requests.
4972                          */
4973                         arc_dnlc_evicts_arg = 0;
4974                 }
4975         }
4976         arc_dnlc_evicts_thread_exit = FALSE;
4977         cv_broadcast(&arc_dnlc_evicts_cv);
4978         CALLB_CPR_EXIT(&cpr);
4979         thread_exit();
4980 }
4981
4982 void
4983 dnlc_reduce_cache(void *arg)
4984 {
4985         u_int percent;
4986
4987         percent = (u_int)(uintptr_t)arg;
4988         mutex_enter(&arc_dnlc_evicts_lock);
4989         if (arc_dnlc_evicts_arg == 0) {
4990                 arc_dnlc_evicts_arg = percent;
4991                 cv_broadcast(&arc_dnlc_evicts_cv);
4992         }
4993         mutex_exit(&arc_dnlc_evicts_lock);
4994 }
4995
4996 /*
4997  * Adapt arc info given the number of bytes we are trying to add and
4998  * the state that we are comming from.  This function is only called
4999  * when we are adding new content to the cache.
5000  */
5001 static void
5002 arc_adapt(int bytes, arc_state_t *state)
5003 {
5004         int mult;
5005         uint64_t arc_p_min = (arc_c >> arc_p_min_shift);
5006         int64_t mrug_size = refcount_count(&arc_mru_ghost->arcs_size);
5007         int64_t mfug_size = refcount_count(&arc_mfu_ghost->arcs_size);
5008
5009         if (state == arc_l2c_only)
5010                 return;
5011
5012         ASSERT(bytes > 0);
5013         /*
5014          * Adapt the target size of the MRU list:
5015          *      - if we just hit in the MRU ghost list, then increase
5016          *        the target size of the MRU list.
5017          *      - if we just hit in the MFU ghost list, then increase
5018          *        the target size of the MFU list by decreasing the
5019          *        target size of the MRU list.
5020          */
5021         if (state == arc_mru_ghost) {
5022                 mult = (mrug_size >= mfug_size) ? 1 : (mfug_size / mrug_size);
5023                 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
5024
5025                 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
5026         } else if (state == arc_mfu_ghost) {
5027                 uint64_t delta;
5028
5029                 mult = (mfug_size >= mrug_size) ? 1 : (mrug_size / mfug_size);
5030                 mult = MIN(mult, 10);
5031
5032                 delta = MIN(bytes * mult, arc_p);
5033                 arc_p = MAX(arc_p_min, arc_p - delta);
5034         }
5035         ASSERT((int64_t)arc_p >= 0);
5036
5037         if (arc_reclaim_needed()) {
5038                 cv_signal(&arc_reclaim_thread_cv);
5039                 return;
5040         }
5041
5042         if (arc_no_grow)
5043                 return;
5044
5045         if (arc_c >= arc_c_max)
5046                 return;
5047
5048         /*
5049          * If we're within (2 * maxblocksize) bytes of the target
5050          * cache size, increment the target cache size
5051          */
5052         if (aggsum_compare(&arc_size, arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) >
5053             0) {
5054                 DTRACE_PROBE1(arc__inc_adapt, int, bytes);
5055                 atomic_add_64(&arc_c, (int64_t)bytes);
5056                 if (arc_c > arc_c_max)
5057                         arc_c = arc_c_max;
5058                 else if (state == arc_anon)
5059                         atomic_add_64(&arc_p, (int64_t)bytes);
5060                 if (arc_p > arc_c)
5061                         arc_p = arc_c;
5062         }
5063         ASSERT((int64_t)arc_p >= 0);
5064 }
5065
5066 /*
5067  * Check if arc_size has grown past our upper threshold, determined by
5068  * zfs_arc_overflow_shift.
5069  */
5070 static boolean_t
5071 arc_is_overflowing(void)
5072 {
5073         /* Always allow at least one block of overflow */
5074         uint64_t overflow = MAX(SPA_MAXBLOCKSIZE,
5075             arc_c >> zfs_arc_overflow_shift);
5076
5077         /*
5078          * We just compare the lower bound here for performance reasons. Our
5079          * primary goals are to make sure that the arc never grows without
5080          * bound, and that it can reach its maximum size. This check
5081          * accomplishes both goals. The maximum amount we could run over by is
5082          * 2 * aggsum_borrow_multiplier * NUM_CPUS * the average size of a block
5083          * in the ARC. In practice, that's in the tens of MB, which is low
5084          * enough to be safe.
5085          */
5086         return (aggsum_lower_bound(&arc_size) >= arc_c + overflow);
5087 }
5088
5089 static abd_t *
5090 arc_get_data_abd(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5091 {
5092         arc_buf_contents_t type = arc_buf_type(hdr);
5093
5094         arc_get_data_impl(hdr, size, tag);
5095         if (type == ARC_BUFC_METADATA) {
5096                 return (abd_alloc(size, B_TRUE));
5097         } else {
5098                 ASSERT(type == ARC_BUFC_DATA);
5099                 return (abd_alloc(size, B_FALSE));
5100         }
5101 }
5102
5103 static void *
5104 arc_get_data_buf(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5105 {
5106         arc_buf_contents_t type = arc_buf_type(hdr);
5107
5108         arc_get_data_impl(hdr, size, tag);
5109         if (type == ARC_BUFC_METADATA) {
5110                 return (zio_buf_alloc(size));
5111         } else {
5112                 ASSERT(type == ARC_BUFC_DATA);
5113                 return (zio_data_buf_alloc(size));
5114         }
5115 }
5116
5117 /*
5118  * Allocate a block and return it to the caller. If we are hitting the
5119  * hard limit for the cache size, we must sleep, waiting for the eviction
5120  * thread to catch up. If we're past the target size but below the hard
5121  * limit, we'll only signal the reclaim thread and continue on.
5122  */
5123 static void
5124 arc_get_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5125 {
5126         arc_state_t *state = hdr->b_l1hdr.b_state;
5127         arc_buf_contents_t type = arc_buf_type(hdr);
5128
5129         arc_adapt(size, state);
5130
5131         /*
5132          * If arc_size is currently overflowing, and has grown past our
5133          * upper limit, we must be adding data faster than the evict
5134          * thread can evict. Thus, to ensure we don't compound the
5135          * problem by adding more data and forcing arc_size to grow even
5136          * further past it's target size, we halt and wait for the
5137          * eviction thread to catch up.
5138          *
5139          * It's also possible that the reclaim thread is unable to evict
5140          * enough buffers to get arc_size below the overflow limit (e.g.
5141          * due to buffers being un-evictable, or hash lock collisions).
5142          * In this case, we want to proceed regardless if we're
5143          * overflowing; thus we don't use a while loop here.
5144          */
5145         if (arc_is_overflowing()) {
5146                 mutex_enter(&arc_reclaim_lock);
5147
5148                 /*
5149                  * Now that we've acquired the lock, we may no longer be
5150                  * over the overflow limit, lets check.
5151                  *
5152                  * We're ignoring the case of spurious wake ups. If that
5153                  * were to happen, it'd let this thread consume an ARC
5154                  * buffer before it should have (i.e. before we're under
5155                  * the overflow limit and were signalled by the reclaim
5156                  * thread). As long as that is a rare occurrence, it
5157                  * shouldn't cause any harm.
5158                  */
5159                 if (arc_is_overflowing()) {
5160                         cv_signal(&arc_reclaim_thread_cv);
5161                         cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
5162                 }
5163
5164                 mutex_exit(&arc_reclaim_lock);
5165         }
5166
5167         VERIFY3U(hdr->b_type, ==, type);
5168         if (type == ARC_BUFC_METADATA) {
5169                 arc_space_consume(size, ARC_SPACE_META);
5170         } else {
5171                 arc_space_consume(size, ARC_SPACE_DATA);
5172         }
5173
5174         /*
5175          * Update the state size.  Note that ghost states have a
5176          * "ghost size" and so don't need to be updated.
5177          */
5178         if (!GHOST_STATE(state)) {
5179
5180                 (void) refcount_add_many(&state->arcs_size, size, tag);
5181
5182                 /*
5183                  * If this is reached via arc_read, the link is
5184                  * protected by the hash lock. If reached via
5185                  * arc_buf_alloc, the header should not be accessed by
5186                  * any other thread. And, if reached via arc_read_done,
5187                  * the hash lock will protect it if it's found in the
5188                  * hash table; otherwise no other thread should be
5189                  * trying to [add|remove]_reference it.
5190                  */
5191                 if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5192                         ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5193                         (void) refcount_add_many(&state->arcs_esize[type],
5194                             size, tag);
5195                 }
5196
5197                 /*
5198                  * If we are growing the cache, and we are adding anonymous
5199                  * data, and we have outgrown arc_p, update arc_p
5200                  */
5201                 if (aggsum_compare(&arc_size, arc_c) < 0 &&
5202                     hdr->b_l1hdr.b_state == arc_anon &&
5203                     (refcount_count(&arc_anon->arcs_size) +
5204                     refcount_count(&arc_mru->arcs_size) > arc_p))
5205                         arc_p = MIN(arc_c, arc_p + size);
5206         }
5207         ARCSTAT_BUMP(arcstat_allocated);
5208 }
5209
5210 static void
5211 arc_free_data_abd(arc_buf_hdr_t *hdr, abd_t *abd, uint64_t size, void *tag)
5212 {
5213         arc_free_data_impl(hdr, size, tag);
5214         abd_free(abd);
5215 }
5216
5217 static void
5218 arc_free_data_buf(arc_buf_hdr_t *hdr, void *buf, uint64_t size, void *tag)
5219 {
5220         arc_buf_contents_t type = arc_buf_type(hdr);
5221
5222         arc_free_data_impl(hdr, size, tag);
5223         if (type == ARC_BUFC_METADATA) {
5224                 zio_buf_free(buf, size);
5225         } else {
5226                 ASSERT(type == ARC_BUFC_DATA);
5227                 zio_data_buf_free(buf, size);
5228         }
5229 }
5230
5231 /*
5232  * Free the arc data buffer.
5233  */
5234 static void
5235 arc_free_data_impl(arc_buf_hdr_t *hdr, uint64_t size, void *tag)
5236 {
5237         arc_state_t *state = hdr->b_l1hdr.b_state;
5238         arc_buf_contents_t type = arc_buf_type(hdr);
5239
5240         /* protected by hash lock, if in the hash table */
5241         if (multilist_link_active(&hdr->b_l1hdr.b_arc_node)) {
5242                 ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5243                 ASSERT(state != arc_anon && state != arc_l2c_only);
5244
5245                 (void) refcount_remove_many(&state->arcs_esize[type],
5246                     size, tag);
5247         }
5248         (void) refcount_remove_many(&state->arcs_size, size, tag);
5249
5250         VERIFY3U(hdr->b_type, ==, type);
5251         if (type == ARC_BUFC_METADATA) {
5252                 arc_space_return(size, ARC_SPACE_META);
5253         } else {
5254                 ASSERT(type == ARC_BUFC_DATA);
5255                 arc_space_return(size, ARC_SPACE_DATA);
5256         }
5257 }
5258
5259 /*
5260  * This routine is called whenever a buffer is accessed.
5261  * NOTE: the hash lock is dropped in this function.
5262  */
5263 static void
5264 arc_access(arc_buf_hdr_t *hdr, kmutex_t *hash_lock)
5265 {
5266         clock_t now;
5267
5268         ASSERT(MUTEX_HELD(hash_lock));
5269         ASSERT(HDR_HAS_L1HDR(hdr));
5270
5271         if (hdr->b_l1hdr.b_state == arc_anon) {
5272                 /*
5273                  * This buffer is not in the cache, and does not
5274                  * appear in our "ghost" list.  Add the new buffer
5275                  * to the MRU state.
5276                  */
5277
5278                 ASSERT0(hdr->b_l1hdr.b_arc_access);
5279                 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5280                 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5281                 arc_change_state(arc_mru, hdr, hash_lock);
5282
5283         } else if (hdr->b_l1hdr.b_state == arc_mru) {
5284                 now = ddi_get_lbolt();
5285
5286                 /*
5287                  * If this buffer is here because of a prefetch, then either:
5288                  * - clear the flag if this is a "referencing" read
5289                  *   (any subsequent access will bump this into the MFU state).
5290                  * or
5291                  * - move the buffer to the head of the list if this is
5292                  *   another prefetch (to make it less likely to be evicted).
5293                  */
5294                 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5295                         if (refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5296                                 /* link protected by hash lock */
5297                                 ASSERT(multilist_link_active(
5298                                     &hdr->b_l1hdr.b_arc_node));
5299                         } else {
5300                                 arc_hdr_clear_flags(hdr,
5301                                     ARC_FLAG_PREFETCH |
5302                                     ARC_FLAG_PRESCIENT_PREFETCH);
5303                                 ARCSTAT_BUMP(arcstat_mru_hits);
5304                         }
5305                         hdr->b_l1hdr.b_arc_access = now;
5306                         return;
5307                 }
5308
5309                 /*
5310                  * This buffer has been "accessed" only once so far,
5311                  * but it is still in the cache. Move it to the MFU
5312                  * state.
5313                  */
5314                 if (now > hdr->b_l1hdr.b_arc_access + ARC_MINTIME) {
5315                         /*
5316                          * More than 125ms have passed since we
5317                          * instantiated this buffer.  Move it to the
5318                          * most frequently used state.
5319                          */
5320                         hdr->b_l1hdr.b_arc_access = now;
5321                         DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5322                         arc_change_state(arc_mfu, hdr, hash_lock);
5323                 }
5324                 atomic_inc_32(&hdr->b_l1hdr.b_mru_hits);
5325                 ARCSTAT_BUMP(arcstat_mru_hits);
5326         } else if (hdr->b_l1hdr.b_state == arc_mru_ghost) {
5327                 arc_state_t     *new_state;
5328                 /*
5329                  * This buffer has been "accessed" recently, but
5330                  * was evicted from the cache.  Move it to the
5331                  * MFU state.
5332                  */
5333
5334                 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5335                         new_state = arc_mru;
5336                         if (refcount_count(&hdr->b_l1hdr.b_refcnt) > 0) {
5337                                 arc_hdr_clear_flags(hdr,
5338                                     ARC_FLAG_PREFETCH |
5339                                     ARC_FLAG_PRESCIENT_PREFETCH);
5340                         }
5341                         DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, hdr);
5342                 } else {
5343                         new_state = arc_mfu;
5344                         DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5345                 }
5346
5347                 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5348                 arc_change_state(new_state, hdr, hash_lock);
5349
5350                 atomic_inc_32(&hdr->b_l1hdr.b_mru_ghost_hits);
5351                 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
5352         } else if (hdr->b_l1hdr.b_state == arc_mfu) {
5353                 /*
5354                  * This buffer has been accessed more than once and is
5355                  * still in the cache.  Keep it in the MFU state.
5356                  *
5357                  * NOTE: an add_reference() that occurred when we did
5358                  * the arc_read() will have kicked this off the list.
5359                  * If it was a prefetch, we will explicitly move it to
5360                  * the head of the list now.
5361                  */
5362
5363                 atomic_inc_32(&hdr->b_l1hdr.b_mfu_hits);
5364                 ARCSTAT_BUMP(arcstat_mfu_hits);
5365                 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5366         } else if (hdr->b_l1hdr.b_state == arc_mfu_ghost) {
5367                 arc_state_t     *new_state = arc_mfu;
5368                 /*
5369                  * This buffer has been accessed more than once but has
5370                  * been evicted from the cache.  Move it back to the
5371                  * MFU state.
5372                  */
5373
5374                 if (HDR_PREFETCH(hdr) || HDR_PRESCIENT_PREFETCH(hdr)) {
5375                         /*
5376                          * This is a prefetch access...
5377                          * move this block back to the MRU state.
5378                          */
5379                         new_state = arc_mru;
5380                 }
5381
5382                 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5383                 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5384                 arc_change_state(new_state, hdr, hash_lock);
5385
5386                 atomic_inc_32(&hdr->b_l1hdr.b_mfu_ghost_hits);
5387                 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
5388         } else if (hdr->b_l1hdr.b_state == arc_l2c_only) {
5389                 /*
5390                  * This buffer is on the 2nd Level ARC.
5391                  */
5392
5393                 hdr->b_l1hdr.b_arc_access = ddi_get_lbolt();
5394                 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, hdr);
5395                 arc_change_state(arc_mfu, hdr, hash_lock);
5396         } else {
5397                 ASSERT(!"invalid arc state");
5398         }
5399 }
5400
5401 /*
5402  * This routine is called by dbuf_hold() to update the arc_access() state
5403  * which otherwise would be skipped for entries in the dbuf cache.
5404  */
5405 void
5406 arc_buf_access(arc_buf_t *buf)
5407 {
5408         mutex_enter(&buf->b_evict_lock);
5409         arc_buf_hdr_t *hdr = buf->b_hdr;
5410
5411         /*
5412          * Avoid taking the hash_lock when possible as an optimization.
5413          * The header must be checked again under the hash_lock in order
5414          * to handle the case where it is concurrently being released.
5415          */
5416         if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5417                 mutex_exit(&buf->b_evict_lock);
5418                 ARCSTAT_BUMP(arcstat_access_skip);
5419                 return;
5420         }
5421
5422         kmutex_t *hash_lock = HDR_LOCK(hdr);
5423         mutex_enter(hash_lock);
5424
5425         if (hdr->b_l1hdr.b_state == arc_anon || HDR_EMPTY(hdr)) {
5426                 mutex_exit(hash_lock);
5427                 mutex_exit(&buf->b_evict_lock);
5428                 ARCSTAT_BUMP(arcstat_access_skip);
5429                 return;
5430         }
5431
5432         mutex_exit(&buf->b_evict_lock);
5433
5434         ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5435             hdr->b_l1hdr.b_state == arc_mfu);
5436
5437         DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5438         arc_access(hdr, hash_lock);
5439         mutex_exit(hash_lock);
5440
5441         ARCSTAT_BUMP(arcstat_hits);
5442         ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5443             demand, prefetch, !HDR_ISTYPE_METADATA(hdr), data, metadata, hits);
5444 }
5445
5446 /* a generic arc_read_done_func_t which you can use */
5447 /* ARGSUSED */
5448 void
5449 arc_bcopy_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5450     arc_buf_t *buf, void *arg)
5451 {
5452         if (buf == NULL)
5453                 return;
5454
5455         bcopy(buf->b_data, arg, arc_buf_size(buf));
5456         arc_buf_destroy(buf, arg);
5457 }
5458
5459 /* a generic arc_read_done_func_t */
5460 /* ARGSUSED */
5461 void
5462 arc_getbuf_func(zio_t *zio, const zbookmark_phys_t *zb, const blkptr_t *bp,
5463     arc_buf_t *buf, void *arg)
5464 {
5465         arc_buf_t **bufp = arg;
5466         if (buf == NULL) {
5467                 ASSERT(zio == NULL || zio->io_error != 0);
5468                 *bufp = NULL;
5469         } else {
5470                 ASSERT(zio == NULL || zio->io_error == 0);
5471                 *bufp = buf;
5472                 ASSERT(buf->b_data != NULL);
5473         }
5474 }
5475
5476 static void
5477 arc_hdr_verify(arc_buf_hdr_t *hdr, blkptr_t *bp)
5478 {
5479         if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp)) {
5480                 ASSERT3U(HDR_GET_PSIZE(hdr), ==, 0);
5481                 ASSERT3U(HDR_GET_COMPRESS(hdr), ==, ZIO_COMPRESS_OFF);
5482         } else {
5483                 if (HDR_COMPRESSION_ENABLED(hdr)) {
5484                         ASSERT3U(HDR_GET_COMPRESS(hdr), ==,
5485                             BP_GET_COMPRESS(bp));
5486                 }
5487                 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(bp));
5488                 ASSERT3U(HDR_GET_PSIZE(hdr), ==, BP_GET_PSIZE(bp));
5489         }
5490 }
5491
5492 static void
5493 arc_read_done(zio_t *zio)
5494 {
5495         arc_buf_hdr_t   *hdr = zio->io_private;
5496         kmutex_t        *hash_lock = NULL;
5497         arc_callback_t  *callback_list;
5498         arc_callback_t  *acb;
5499         boolean_t       freeable = B_FALSE;
5500         boolean_t       no_zio_error = (zio->io_error == 0);
5501
5502         /*
5503          * The hdr was inserted into hash-table and removed from lists
5504          * prior to starting I/O.  We should find this header, since
5505          * it's in the hash table, and it should be legit since it's
5506          * not possible to evict it during the I/O.  The only possible
5507          * reason for it not to be found is if we were freed during the
5508          * read.
5509          */
5510         if (HDR_IN_HASH_TABLE(hdr)) {
5511                 ASSERT3U(hdr->b_birth, ==, BP_PHYSICAL_BIRTH(zio->io_bp));
5512                 ASSERT3U(hdr->b_dva.dva_word[0], ==,
5513                     BP_IDENTITY(zio->io_bp)->dva_word[0]);
5514                 ASSERT3U(hdr->b_dva.dva_word[1], ==,
5515                     BP_IDENTITY(zio->io_bp)->dva_word[1]);
5516
5517                 arc_buf_hdr_t *found = buf_hash_find(hdr->b_spa, zio->io_bp,
5518                     &hash_lock);
5519
5520                 ASSERT((found == hdr &&
5521                     DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
5522                     (found == hdr && HDR_L2_READING(hdr)));
5523                 ASSERT3P(hash_lock, !=, NULL);
5524         }
5525
5526         if (no_zio_error) {
5527                 /* byteswap if necessary */
5528                 if (BP_SHOULD_BYTESWAP(zio->io_bp)) {
5529                         if (BP_GET_LEVEL(zio->io_bp) > 0) {
5530                                 hdr->b_l1hdr.b_byteswap = DMU_BSWAP_UINT64;
5531                         } else {
5532                                 hdr->b_l1hdr.b_byteswap =
5533                                     DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
5534                         }
5535                 } else {
5536                         hdr->b_l1hdr.b_byteswap = DMU_BSWAP_NUMFUNCS;
5537                 }
5538         }
5539
5540         arc_hdr_clear_flags(hdr, ARC_FLAG_L2_EVICTED);
5541         if (l2arc_noprefetch && HDR_PREFETCH(hdr))
5542                 arc_hdr_clear_flags(hdr, ARC_FLAG_L2CACHE);
5543
5544         callback_list = hdr->b_l1hdr.b_acb;
5545         ASSERT3P(callback_list, !=, NULL);
5546
5547         if (hash_lock && no_zio_error && hdr->b_l1hdr.b_state == arc_anon) {
5548                 /*
5549                  * Only call arc_access on anonymous buffers.  This is because
5550                  * if we've issued an I/O for an evicted buffer, we've already
5551                  * called arc_access (to prevent any simultaneous readers from
5552                  * getting confused).
5553                  */
5554                 arc_access(hdr, hash_lock);
5555         }
5556
5557         /*
5558          * If a read request has a callback (i.e. acb_done is not NULL), then we
5559          * make a buf containing the data according to the parameters which were
5560          * passed in. The implementation of arc_buf_alloc_impl() ensures that we
5561          * aren't needlessly decompressing the data multiple times.
5562          */
5563         int callback_cnt = 0;
5564         for (acb = callback_list; acb != NULL; acb = acb->acb_next) {
5565                 if (!acb->acb_done)
5566                         continue;
5567
5568                 callback_cnt++;
5569
5570                 if (no_zio_error) {
5571                         int error = arc_buf_alloc_impl(hdr, acb->acb_private,
5572                             acb->acb_compressed, zio->io_error == 0,
5573                             &acb->acb_buf);
5574                         if (error != 0) {
5575                                 /*
5576                                  * Decompression failed.  Set io_error
5577                                  * so that when we call acb_done (below),
5578                                  * we will indicate that the read failed.
5579                                  * Note that in the unusual case where one
5580                                  * callback is compressed and another
5581                                  * uncompressed, we will mark all of them
5582                                  * as failed, even though the uncompressed
5583                                  * one can't actually fail.  In this case,
5584                                  * the hdr will not be anonymous, because
5585                                  * if there are multiple callbacks, it's
5586                                  * because multiple threads found the same
5587                                  * arc buf in the hash table.
5588                                  */
5589                                 zio->io_error = error;
5590                         }
5591                 }
5592         }
5593         /*
5594          * If there are multiple callbacks, we must have the hash lock,
5595          * because the only way for multiple threads to find this hdr is
5596          * in the hash table.  This ensures that if there are multiple
5597          * callbacks, the hdr is not anonymous.  If it were anonymous,
5598          * we couldn't use arc_buf_destroy() in the error case below.
5599          */
5600         ASSERT(callback_cnt < 2 || hash_lock != NULL);
5601
5602         hdr->b_l1hdr.b_acb = NULL;
5603         arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5604         if (callback_cnt == 0) {
5605                 ASSERT(HDR_PREFETCH(hdr));
5606                 ASSERT0(hdr->b_l1hdr.b_bufcnt);
5607                 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5608         }
5609
5610         ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt) ||
5611             callback_list != NULL);
5612
5613         if (no_zio_error) {
5614                 arc_hdr_verify(hdr, zio->io_bp);
5615         } else {
5616                 arc_hdr_set_flags(hdr, ARC_FLAG_IO_ERROR);
5617                 if (hdr->b_l1hdr.b_state != arc_anon)
5618                         arc_change_state(arc_anon, hdr, hash_lock);
5619                 if (HDR_IN_HASH_TABLE(hdr))
5620                         buf_hash_remove(hdr);
5621                 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5622         }
5623
5624         /*
5625          * Broadcast before we drop the hash_lock to avoid the possibility
5626          * that the hdr (and hence the cv) might be freed before we get to
5627          * the cv_broadcast().
5628          */
5629         cv_broadcast(&hdr->b_l1hdr.b_cv);
5630
5631         if (hash_lock != NULL) {
5632                 mutex_exit(hash_lock);
5633         } else {
5634                 /*
5635                  * This block was freed while we waited for the read to
5636                  * complete.  It has been removed from the hash table and
5637                  * moved to the anonymous state (so that it won't show up
5638                  * in the cache).
5639                  */
5640                 ASSERT3P(hdr->b_l1hdr.b_state, ==, arc_anon);
5641                 freeable = refcount_is_zero(&hdr->b_l1hdr.b_refcnt);
5642         }
5643
5644         /* execute each callback and free its structure */
5645         while ((acb = callback_list) != NULL) {
5646                 if (acb->acb_done != NULL) {
5647                         if (zio->io_error != 0 && acb->acb_buf != NULL) {
5648                                 /*
5649                                  * If arc_buf_alloc_impl() fails during
5650                                  * decompression, the buf will still be
5651                                  * allocated, and needs to be freed here.
5652                                  */
5653                                 arc_buf_destroy(acb->acb_buf, acb->acb_private);
5654                                 acb->acb_buf = NULL;
5655                         }
5656                         acb->acb_done(zio, &zio->io_bookmark, zio->io_bp,
5657                             acb->acb_buf, acb->acb_private);
5658                 }
5659
5660                 if (acb->acb_zio_dummy != NULL) {
5661                         acb->acb_zio_dummy->io_error = zio->io_error;
5662                         zio_nowait(acb->acb_zio_dummy);
5663                 }
5664
5665                 callback_list = acb->acb_next;
5666                 kmem_free(acb, sizeof (arc_callback_t));
5667         }
5668
5669         if (freeable)
5670                 arc_hdr_destroy(hdr);
5671 }
5672
5673 /*
5674  * "Read" the block at the specified DVA (in bp) via the
5675  * cache.  If the block is found in the cache, invoke the provided
5676  * callback immediately and return.  Note that the `zio' parameter
5677  * in the callback will be NULL in this case, since no IO was
5678  * required.  If the block is not in the cache pass the read request
5679  * on to the spa with a substitute callback function, so that the
5680  * requested block will be added to the cache.
5681  *
5682  * If a read request arrives for a block that has a read in-progress,
5683  * either wait for the in-progress read to complete (and return the
5684  * results); or, if this is a read with a "done" func, add a record
5685  * to the read to invoke the "done" func when the read completes,
5686  * and return; or just return.
5687  *
5688  * arc_read_done() will invoke all the requested "done" functions
5689  * for readers of this block.
5690  */
5691 int
5692 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_read_done_func_t *done,
5693     void *private, zio_priority_t priority, int zio_flags,
5694     arc_flags_t *arc_flags, const zbookmark_phys_t *zb)
5695 {
5696         arc_buf_hdr_t *hdr = NULL;
5697         kmutex_t *hash_lock = NULL;
5698         zio_t *rzio;
5699         uint64_t guid = spa_load_guid(spa);
5700         boolean_t compressed_read = (zio_flags & ZIO_FLAG_RAW) != 0;
5701         int rc = 0;
5702         
5703         ASSERT(!BP_IS_EMBEDDED(bp) ||
5704             BPE_GET_ETYPE(bp) == BP_EMBEDDED_TYPE_DATA);
5705
5706 top:
5707         if (!BP_IS_EMBEDDED(bp)) {
5708                 /*
5709                  * Embedded BP's have no DVA and require no I/O to "read".
5710                  * Create an anonymous arc buf to back it.
5711                  */
5712                 hdr = buf_hash_find(guid, bp, &hash_lock);
5713         }
5714
5715         if (hdr != NULL && HDR_HAS_L1HDR(hdr) && hdr->b_l1hdr.b_pabd != NULL) {
5716                 arc_buf_t *buf = NULL;
5717                 *arc_flags |= ARC_FLAG_CACHED;
5718
5719                 if (HDR_IO_IN_PROGRESS(hdr)) {
5720                         zio_t *head_zio = hdr->b_l1hdr.b_acb->acb_zio_head;
5721
5722                         ASSERT3P(head_zio, !=, NULL);
5723                         if ((hdr->b_flags & ARC_FLAG_PRIO_ASYNC_READ) &&
5724                             priority == ZIO_PRIORITY_SYNC_READ) {
5725                                 /*
5726                                  * This is a sync read that needs to wait for
5727                                  * an in-flight async read. Request that the
5728                                  * zio have its priority upgraded.
5729                                  */
5730                                 zio_change_priority(head_zio, priority);
5731                                 DTRACE_PROBE1(arc__async__upgrade__sync,
5732                                     arc_buf_hdr_t *, hdr);
5733                                 ARCSTAT_BUMP(arcstat_async_upgrade_sync);
5734                         }
5735                         if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5736                                 arc_hdr_clear_flags(hdr,
5737                                     ARC_FLAG_PREDICTIVE_PREFETCH);
5738                         }
5739
5740                         if (*arc_flags & ARC_FLAG_WAIT) {
5741                                 cv_wait(&hdr->b_l1hdr.b_cv, hash_lock);
5742                                 mutex_exit(hash_lock);
5743                                 goto top;
5744                         }
5745                         ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
5746
5747                         if (done) {
5748                                 arc_callback_t *acb = NULL;
5749
5750                                 acb = kmem_zalloc(sizeof (arc_callback_t),
5751                                     KM_SLEEP);
5752                                 acb->acb_done = done;
5753                                 acb->acb_private = private;
5754                                 acb->acb_compressed = compressed_read;
5755                                 if (pio != NULL)
5756                                         acb->acb_zio_dummy = zio_null(pio,
5757                                             spa, NULL, NULL, NULL, zio_flags);
5758
5759                                 ASSERT3P(acb->acb_done, !=, NULL);
5760                                 acb->acb_zio_head = head_zio;
5761                                 acb->acb_next = hdr->b_l1hdr.b_acb;
5762                                 hdr->b_l1hdr.b_acb = acb;
5763                                 mutex_exit(hash_lock);
5764                                 return (0);
5765                         }
5766                         mutex_exit(hash_lock);
5767                         return (0);
5768                 }
5769
5770                 ASSERT(hdr->b_l1hdr.b_state == arc_mru ||
5771                     hdr->b_l1hdr.b_state == arc_mfu);
5772
5773                 if (done) {
5774                         if (hdr->b_flags & ARC_FLAG_PREDICTIVE_PREFETCH) {
5775                                 /*
5776                                  * This is a demand read which does not have to
5777                                  * wait for i/o because we did a predictive
5778                                  * prefetch i/o for it, which has completed.
5779                                  */
5780                                 DTRACE_PROBE1(
5781                                     arc__demand__hit__predictive__prefetch,
5782                                     arc_buf_hdr_t *, hdr);
5783                                 ARCSTAT_BUMP(
5784                                     arcstat_demand_hit_predictive_prefetch);
5785                                 arc_hdr_clear_flags(hdr,
5786                                     ARC_FLAG_PREDICTIVE_PREFETCH);
5787                         }
5788
5789                         if (hdr->b_flags & ARC_FLAG_PRESCIENT_PREFETCH) {
5790                                 ARCSTAT_BUMP(
5791                                     arcstat_demand_hit_prescient_prefetch);
5792                                 arc_hdr_clear_flags(hdr,
5793                                     ARC_FLAG_PRESCIENT_PREFETCH);
5794                         }
5795
5796                         ASSERT(!BP_IS_EMBEDDED(bp) || !BP_IS_HOLE(bp));
5797                         /* Get a buf with the desired data in it. */
5798                         rc = arc_buf_alloc_impl(hdr, private,
5799                            compressed_read, B_TRUE, &buf);
5800                         if (rc != 0) {
5801                                 arc_buf_destroy(buf, private);
5802                                 buf = NULL;
5803                         }
5804                         ASSERT((zio_flags & ZIO_FLAG_SPECULATIVE) ||
5805                             rc == 0 || rc != ENOENT);
5806                 } else if (*arc_flags & ARC_FLAG_PREFETCH &&
5807                     refcount_count(&hdr->b_l1hdr.b_refcnt) == 0) {
5808                         arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5809                 }
5810                 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
5811                 arc_access(hdr, hash_lock);
5812                 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5813                         arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5814                 if (*arc_flags & ARC_FLAG_L2CACHE)
5815                         arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5816                 mutex_exit(hash_lock);
5817                 ARCSTAT_BUMP(arcstat_hits);
5818                 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5819                     demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5820                     data, metadata, hits);
5821
5822                 if (done)
5823                         done(NULL, zb, bp, buf, private);
5824         } else {
5825                 uint64_t lsize = BP_GET_LSIZE(bp);
5826                 uint64_t psize = BP_GET_PSIZE(bp);
5827                 arc_callback_t *acb;
5828                 vdev_t *vd = NULL;
5829                 uint64_t addr = 0;
5830                 boolean_t devw = B_FALSE;
5831                 uint64_t size;
5832
5833                 if (hdr == NULL) {
5834                         /* this block is not in the cache */
5835                         arc_buf_hdr_t *exists = NULL;
5836                         arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
5837                         hdr = arc_hdr_alloc(spa_load_guid(spa), psize, lsize,
5838                             BP_GET_COMPRESS(bp), type);
5839
5840                         if (!BP_IS_EMBEDDED(bp)) {
5841                                 hdr->b_dva = *BP_IDENTITY(bp);
5842                                 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
5843                                 exists = buf_hash_insert(hdr, &hash_lock);
5844                         }
5845                         if (exists != NULL) {
5846                                 /* somebody beat us to the hash insert */
5847                                 mutex_exit(hash_lock);
5848                                 buf_discard_identity(hdr);
5849                                 arc_hdr_destroy(hdr);
5850                                 goto top; /* restart the IO request */
5851                         }
5852                 } else {
5853                         /*
5854                          * This block is in the ghost cache. If it was L2-only
5855                          * (and thus didn't have an L1 hdr), we realloc the
5856                          * header to add an L1 hdr.
5857                          */
5858                         if (!HDR_HAS_L1HDR(hdr)) {
5859                                 hdr = arc_hdr_realloc(hdr, hdr_l2only_cache,
5860                                     hdr_full_cache);
5861                         }
5862                         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
5863                         ASSERT(GHOST_STATE(hdr->b_l1hdr.b_state));
5864                         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
5865                         ASSERT(refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
5866                         ASSERT3P(hdr->b_l1hdr.b_buf, ==, NULL);
5867                         ASSERT3P(hdr->b_l1hdr.b_freeze_cksum, ==, NULL);
5868
5869                         /*
5870                          * This is a delicate dance that we play here.
5871                          * This hdr is in the ghost list so we access it
5872                          * to move it out of the ghost list before we
5873                          * initiate the read. If it's a prefetch then
5874                          * it won't have a callback so we'll remove the
5875                          * reference that arc_buf_alloc_impl() created. We
5876                          * do this after we've called arc_access() to
5877                          * avoid hitting an assert in remove_reference().
5878                          */
5879                         arc_access(hdr, hash_lock);
5880                         arc_hdr_alloc_pabd(hdr);
5881                 }
5882                 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
5883                 size = arc_hdr_size(hdr);
5884
5885                 /*
5886                  * If compression is enabled on the hdr, then will do
5887                  * RAW I/O and will store the compressed data in the hdr's
5888                  * data block. Otherwise, the hdr's data block will contain
5889                  * the uncompressed data.
5890                  */
5891                 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
5892                         zio_flags |= ZIO_FLAG_RAW;
5893                 }
5894
5895                 if (*arc_flags & ARC_FLAG_PREFETCH)
5896                         arc_hdr_set_flags(hdr, ARC_FLAG_PREFETCH);
5897                 if (*arc_flags & ARC_FLAG_PRESCIENT_PREFETCH)
5898                         arc_hdr_set_flags(hdr, ARC_FLAG_PRESCIENT_PREFETCH);
5899
5900                 if (*arc_flags & ARC_FLAG_L2CACHE)
5901                         arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
5902                 if (BP_GET_LEVEL(bp) > 0)
5903                         arc_hdr_set_flags(hdr, ARC_FLAG_INDIRECT);
5904                 if (*arc_flags & ARC_FLAG_PREDICTIVE_PREFETCH)
5905                         arc_hdr_set_flags(hdr, ARC_FLAG_PREDICTIVE_PREFETCH);
5906                 ASSERT(!GHOST_STATE(hdr->b_l1hdr.b_state));
5907
5908                 acb = kmem_zalloc(sizeof (arc_callback_t), KM_SLEEP);
5909                 acb->acb_done = done;
5910                 acb->acb_private = private;
5911                 acb->acb_compressed = compressed_read;
5912
5913                 ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
5914                 hdr->b_l1hdr.b_acb = acb;
5915                 arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
5916
5917                 if (HDR_HAS_L2HDR(hdr) &&
5918                     (vd = hdr->b_l2hdr.b_dev->l2ad_vdev) != NULL) {
5919                         devw = hdr->b_l2hdr.b_dev->l2ad_writing;
5920                         addr = hdr->b_l2hdr.b_daddr;
5921                         /*
5922                          * Lock out L2ARC device removal.
5923                          */
5924                         if (vdev_is_dead(vd) ||
5925                             !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
5926                                 vd = NULL;
5927                 }
5928
5929                 /*
5930                  * We count both async reads and scrub IOs as asynchronous so
5931                  * that both can be upgraded in the event of a cache hit while
5932                  * the read IO is still in-flight.
5933                  */
5934                 if (priority == ZIO_PRIORITY_ASYNC_READ ||
5935                     priority == ZIO_PRIORITY_SCRUB)
5936                         arc_hdr_set_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5937                 else
5938                         arc_hdr_clear_flags(hdr, ARC_FLAG_PRIO_ASYNC_READ);
5939
5940                 /*
5941                  * At this point, we have a level 1 cache miss.  Try again in
5942                  * L2ARC if possible.
5943                  */
5944                 ASSERT3U(HDR_GET_LSIZE(hdr), ==, lsize);
5945
5946                 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
5947                     uint64_t, lsize, zbookmark_phys_t *, zb);
5948                 ARCSTAT_BUMP(arcstat_misses);
5949                 ARCSTAT_CONDSTAT(!HDR_PREFETCH(hdr),
5950                     demand, prefetch, !HDR_ISTYPE_METADATA(hdr),
5951                     data, metadata, misses);
5952 #ifdef _KERNEL
5953 #ifdef RACCT
5954                 if (racct_enable) {
5955                         PROC_LOCK(curproc);
5956                         racct_add_force(curproc, RACCT_READBPS, size);
5957                         racct_add_force(curproc, RACCT_READIOPS, 1);
5958                         PROC_UNLOCK(curproc);
5959                 }
5960 #endif /* RACCT */
5961                 curthread->td_ru.ru_inblock++;
5962 #endif
5963
5964                 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
5965                         /*
5966                          * Read from the L2ARC if the following are true:
5967                          * 1. The L2ARC vdev was previously cached.
5968                          * 2. This buffer still has L2ARC metadata.
5969                          * 3. This buffer isn't currently writing to the L2ARC.
5970                          * 4. The L2ARC entry wasn't evicted, which may
5971                          *    also have invalidated the vdev.
5972                          * 5. This isn't prefetch and l2arc_noprefetch is set.
5973                          */
5974                         if (HDR_HAS_L2HDR(hdr) &&
5975                             !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
5976                             !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
5977                                 l2arc_read_callback_t *cb;
5978                                 abd_t *abd;
5979                                 uint64_t asize;
5980
5981                                 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
5982                                 ARCSTAT_BUMP(arcstat_l2_hits);
5983                                 atomic_inc_32(&hdr->b_l2hdr.b_hits);
5984
5985                                 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
5986                                     KM_SLEEP);
5987                                 cb->l2rcb_hdr = hdr;
5988                                 cb->l2rcb_bp = *bp;
5989                                 cb->l2rcb_zb = *zb;
5990                                 cb->l2rcb_flags = zio_flags;
5991
5992                                 asize = vdev_psize_to_asize(vd, size);
5993                                 if (asize != size) {
5994                                         abd = abd_alloc_for_io(asize,
5995                                             HDR_ISTYPE_METADATA(hdr));
5996                                         cb->l2rcb_abd = abd;
5997                                 } else {
5998                                         abd = hdr->b_l1hdr.b_pabd;
5999                                 }
6000
6001                                 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
6002                                     addr + asize <= vd->vdev_psize -
6003                                     VDEV_LABEL_END_SIZE);
6004
6005                                 /*
6006                                  * l2arc read.  The SCL_L2ARC lock will be
6007                                  * released by l2arc_read_done().
6008                                  * Issue a null zio if the underlying buffer
6009                                  * was squashed to zero size by compression.
6010                                  */
6011                                 ASSERT3U(HDR_GET_COMPRESS(hdr), !=,
6012                                     ZIO_COMPRESS_EMPTY);
6013                                 rzio = zio_read_phys(pio, vd, addr,
6014                                     asize, abd,
6015                                     ZIO_CHECKSUM_OFF,
6016                                     l2arc_read_done, cb, priority,
6017                                     zio_flags | ZIO_FLAG_DONT_CACHE |
6018                                     ZIO_FLAG_CANFAIL |
6019                                     ZIO_FLAG_DONT_PROPAGATE |
6020                                     ZIO_FLAG_DONT_RETRY, B_FALSE);
6021                                 acb->acb_zio_head = rzio;
6022
6023                                 if (hash_lock != NULL)
6024                                         mutex_exit(hash_lock);
6025
6026                                 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
6027                                     zio_t *, rzio);
6028                                 ARCSTAT_INCR(arcstat_l2_read_bytes, size);
6029
6030                                 if (*arc_flags & ARC_FLAG_NOWAIT) {
6031                                         zio_nowait(rzio);
6032                                         return (0);
6033                                 }
6034
6035                                 ASSERT(*arc_flags & ARC_FLAG_WAIT);
6036                                 if (zio_wait(rzio) == 0)
6037                                         return (0);
6038
6039                                 /* l2arc read error; goto zio_read() */
6040                                 if (hash_lock != NULL)
6041                                         mutex_enter(hash_lock);
6042                         } else {
6043                                 DTRACE_PROBE1(l2arc__miss,
6044                                     arc_buf_hdr_t *, hdr);
6045                                 ARCSTAT_BUMP(arcstat_l2_misses);
6046                                 if (HDR_L2_WRITING(hdr))
6047                                         ARCSTAT_BUMP(arcstat_l2_rw_clash);
6048                                 spa_config_exit(spa, SCL_L2ARC, vd);
6049                         }
6050                 } else {
6051                         if (vd != NULL)
6052                                 spa_config_exit(spa, SCL_L2ARC, vd);
6053                         if (l2arc_ndev != 0) {
6054                                 DTRACE_PROBE1(l2arc__miss,
6055                                     arc_buf_hdr_t *, hdr);
6056                                 ARCSTAT_BUMP(arcstat_l2_misses);
6057                         }
6058                 }
6059
6060                 rzio = zio_read(pio, spa, bp, hdr->b_l1hdr.b_pabd, size,
6061                     arc_read_done, hdr, priority, zio_flags, zb);
6062                 acb->acb_zio_head = rzio;
6063
6064                 if (hash_lock != NULL)
6065                         mutex_exit(hash_lock);
6066
6067                 if (*arc_flags & ARC_FLAG_WAIT)
6068                         return (zio_wait(rzio));
6069
6070                 ASSERT(*arc_flags & ARC_FLAG_NOWAIT);
6071                 zio_nowait(rzio);
6072         }
6073         return (0);
6074 }
6075
6076 arc_prune_t *
6077 arc_add_prune_callback(arc_prune_func_t *func, void *private)
6078 {
6079         arc_prune_t *p;
6080
6081         p = kmem_alloc(sizeof (*p), KM_SLEEP);
6082         p->p_pfunc = func;
6083         p->p_private = private;
6084         list_link_init(&p->p_node);
6085         refcount_create(&p->p_refcnt);
6086
6087         mutex_enter(&arc_prune_mtx);
6088         refcount_add(&p->p_refcnt, &arc_prune_list);
6089         list_insert_head(&arc_prune_list, p);
6090         mutex_exit(&arc_prune_mtx);
6091
6092         return (p);
6093 }
6094
6095 void
6096 arc_remove_prune_callback(arc_prune_t *p)
6097 {
6098         boolean_t wait = B_FALSE;
6099         mutex_enter(&arc_prune_mtx);
6100         list_remove(&arc_prune_list, p);
6101         if (refcount_remove(&p->p_refcnt, &arc_prune_list) > 0)
6102                 wait = B_TRUE;
6103         mutex_exit(&arc_prune_mtx);
6104
6105         /* wait for arc_prune_task to finish */
6106         if (wait)
6107                 taskq_wait(arc_prune_taskq);
6108         ASSERT0(refcount_count(&p->p_refcnt));
6109         refcount_destroy(&p->p_refcnt);
6110         kmem_free(p, sizeof (*p));
6111 }
6112
6113 /*
6114  * Notify the arc that a block was freed, and thus will never be used again.
6115  */
6116 void
6117 arc_freed(spa_t *spa, const blkptr_t *bp)
6118 {
6119         arc_buf_hdr_t *hdr;
6120         kmutex_t *hash_lock;
6121         uint64_t guid = spa_load_guid(spa);
6122
6123         ASSERT(!BP_IS_EMBEDDED(bp));
6124
6125         hdr = buf_hash_find(guid, bp, &hash_lock);
6126         if (hdr == NULL)
6127                 return;
6128
6129         /*
6130          * We might be trying to free a block that is still doing I/O
6131          * (i.e. prefetch) or has a reference (i.e. a dedup-ed,
6132          * dmu_sync-ed block). If this block is being prefetched, then it
6133          * would still have the ARC_FLAG_IO_IN_PROGRESS flag set on the hdr
6134          * until the I/O completes. A block may also have a reference if it is
6135          * part of a dedup-ed, dmu_synced write. The dmu_sync() function would
6136          * have written the new block to its final resting place on disk but
6137          * without the dedup flag set. This would have left the hdr in the MRU
6138          * state and discoverable. When the txg finally syncs it detects that
6139          * the block was overridden in open context and issues an override I/O.
6140          * Since this is a dedup block, the override I/O will determine if the
6141          * block is already in the DDT. If so, then it will replace the io_bp
6142          * with the bp from the DDT and allow the I/O to finish. When the I/O
6143          * reaches the done callback, dbuf_write_override_done, it will
6144          * check to see if the io_bp and io_bp_override are identical.
6145          * If they are not, then it indicates that the bp was replaced with
6146          * the bp in the DDT and the override bp is freed. This allows
6147          * us to arrive here with a reference on a block that is being
6148          * freed. So if we have an I/O in progress, or a reference to
6149          * this hdr, then we don't destroy the hdr.
6150          */
6151         if (!HDR_HAS_L1HDR(hdr) || (!HDR_IO_IN_PROGRESS(hdr) &&
6152             refcount_is_zero(&hdr->b_l1hdr.b_refcnt))) {
6153                 arc_change_state(arc_anon, hdr, hash_lock);
6154                 arc_hdr_destroy(hdr);
6155                 mutex_exit(hash_lock);
6156         } else {
6157                 mutex_exit(hash_lock);
6158         }
6159
6160 }
6161
6162 /*
6163  * Release this buffer from the cache, making it an anonymous buffer.  This
6164  * must be done after a read and prior to modifying the buffer contents.
6165  * If the buffer has more than one reference, we must make
6166  * a new hdr for the buffer.
6167  */
6168 void
6169 arc_release(arc_buf_t *buf, void *tag)
6170 {
6171         arc_buf_hdr_t *hdr = buf->b_hdr;
6172
6173         /*
6174          * It would be nice to assert that if it's DMU metadata (level >
6175          * 0 || it's the dnode file), then it must be syncing context.
6176          * But we don't know that information at this level.
6177          */
6178
6179         mutex_enter(&buf->b_evict_lock);
6180
6181         ASSERT(HDR_HAS_L1HDR(hdr));
6182
6183         /*
6184          * We don't grab the hash lock prior to this check, because if
6185          * the buffer's header is in the arc_anon state, it won't be
6186          * linked into the hash table.
6187          */
6188         if (hdr->b_l1hdr.b_state == arc_anon) {
6189                 mutex_exit(&buf->b_evict_lock);
6190                 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6191                 ASSERT(!HDR_IN_HASH_TABLE(hdr));
6192                 ASSERT(!HDR_HAS_L2HDR(hdr));
6193                 ASSERT(HDR_EMPTY(hdr));
6194                 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6195                 ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), ==, 1);
6196                 ASSERT(!list_link_active(&hdr->b_l1hdr.b_arc_node));
6197
6198                 hdr->b_l1hdr.b_arc_access = 0;
6199
6200                 /*
6201                  * If the buf is being overridden then it may already
6202                  * have a hdr that is not empty.
6203                  */
6204                 buf_discard_identity(hdr);
6205                 arc_buf_thaw(buf);
6206
6207                 return;
6208         }
6209
6210         kmutex_t *hash_lock = HDR_LOCK(hdr);
6211         mutex_enter(hash_lock);
6212
6213         /*
6214          * This assignment is only valid as long as the hash_lock is
6215          * held, we must be careful not to reference state or the
6216          * b_state field after dropping the lock.
6217          */
6218         arc_state_t *state = hdr->b_l1hdr.b_state;
6219         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
6220         ASSERT3P(state, !=, arc_anon);
6221
6222         /* this buffer is not on any list */
6223         ASSERT3S(refcount_count(&hdr->b_l1hdr.b_refcnt), >, 0);
6224
6225         if (HDR_HAS_L2HDR(hdr)) {
6226                 mutex_enter(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6227
6228                 /*
6229                  * We have to recheck this conditional again now that
6230                  * we're holding the l2ad_mtx to prevent a race with
6231                  * another thread which might be concurrently calling
6232                  * l2arc_evict(). In that case, l2arc_evict() might have
6233                  * destroyed the header's L2 portion as we were waiting
6234                  * to acquire the l2ad_mtx.
6235                  */
6236                 if (HDR_HAS_L2HDR(hdr)) {
6237                         l2arc_trim(hdr);
6238                         arc_hdr_l2hdr_destroy(hdr);
6239                 }
6240
6241                 mutex_exit(&hdr->b_l2hdr.b_dev->l2ad_mtx);
6242         }
6243
6244         /*
6245          * Do we have more than one buf?
6246          */
6247         if (hdr->b_l1hdr.b_bufcnt > 1) {
6248                 arc_buf_hdr_t *nhdr;
6249                 uint64_t spa = hdr->b_spa;
6250                 uint64_t psize = HDR_GET_PSIZE(hdr);
6251                 uint64_t lsize = HDR_GET_LSIZE(hdr);
6252                 enum zio_compress compress = HDR_GET_COMPRESS(hdr);
6253                 arc_buf_contents_t type = arc_buf_type(hdr);
6254                 VERIFY3U(hdr->b_type, ==, type);
6255
6256                 ASSERT(hdr->b_l1hdr.b_buf != buf || buf->b_next != NULL);
6257                 (void) remove_reference(hdr, hash_lock, tag);
6258
6259                 if (arc_buf_is_shared(buf) && !ARC_BUF_COMPRESSED(buf)) {
6260                         ASSERT3P(hdr->b_l1hdr.b_buf, !=, buf);
6261                         ASSERT(ARC_BUF_LAST(buf));
6262                 }
6263
6264                 /*
6265                  * Pull the data off of this hdr and attach it to
6266                  * a new anonymous hdr. Also find the last buffer
6267                  * in the hdr's buffer list.
6268                  */
6269                 arc_buf_t *lastbuf = arc_buf_remove(hdr, buf);
6270                 ASSERT3P(lastbuf, !=, NULL);
6271
6272                 /*
6273                  * If the current arc_buf_t and the hdr are sharing their data
6274                  * buffer, then we must stop sharing that block.
6275                  */
6276                 if (arc_buf_is_shared(buf)) {
6277                         VERIFY(!arc_buf_is_shared(lastbuf));
6278
6279                         /*
6280                          * First, sever the block sharing relationship between
6281                          * buf and the arc_buf_hdr_t.
6282                          */
6283                         arc_unshare_buf(hdr, buf);
6284
6285                         /*
6286                          * Now we need to recreate the hdr's b_pabd. Since we
6287                          * have lastbuf handy, we try to share with it, but if
6288                          * we can't then we allocate a new b_pabd and copy the
6289                          * data from buf into it.
6290                          */
6291                         if (arc_can_share(hdr, lastbuf)) {
6292                                 arc_share_buf(hdr, lastbuf);
6293                         } else {
6294                                 arc_hdr_alloc_pabd(hdr);
6295                                 abd_copy_from_buf(hdr->b_l1hdr.b_pabd,
6296                                     buf->b_data, psize);
6297                         }
6298                         VERIFY3P(lastbuf->b_data, !=, NULL);
6299                 } else if (HDR_SHARED_DATA(hdr)) {
6300                         /*
6301                          * Uncompressed shared buffers are always at the end
6302                          * of the list. Compressed buffers don't have the
6303                          * same requirements. This makes it hard to
6304                          * simply assert that the lastbuf is shared so
6305                          * we rely on the hdr's compression flags to determine
6306                          * if we have a compressed, shared buffer.
6307                          */
6308                         ASSERT(arc_buf_is_shared(lastbuf) ||
6309                             HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF);
6310                         ASSERT(!ARC_BUF_SHARED(buf));
6311                 }
6312                 ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
6313                 ASSERT3P(state, !=, arc_l2c_only);
6314
6315                 (void) refcount_remove_many(&state->arcs_size,
6316                     arc_buf_size(buf), buf);
6317
6318                 if (refcount_is_zero(&hdr->b_l1hdr.b_refcnt)) {
6319                         ASSERT3P(state, !=, arc_l2c_only);
6320                         (void) refcount_remove_many(&state->arcs_esize[type],
6321                             arc_buf_size(buf), buf);
6322                 }
6323
6324                 hdr->b_l1hdr.b_bufcnt -= 1;
6325                 arc_cksum_verify(buf);
6326 #ifdef illumos
6327                 arc_buf_unwatch(buf);
6328 #endif
6329
6330                 mutex_exit(hash_lock);
6331
6332                 /*
6333                  * Allocate a new hdr. The new hdr will contain a b_pabd
6334                  * buffer which will be freed in arc_write().
6335                  */
6336                 nhdr = arc_hdr_alloc(spa, psize, lsize, compress, type);
6337                 ASSERT3P(nhdr->b_l1hdr.b_buf, ==, NULL);
6338                 ASSERT0(nhdr->b_l1hdr.b_bufcnt);
6339                 ASSERT0(refcount_count(&nhdr->b_l1hdr.b_refcnt));
6340                 VERIFY3U(nhdr->b_type, ==, type);
6341                 ASSERT(!HDR_SHARED_DATA(nhdr));
6342
6343                 nhdr->b_l1hdr.b_buf = buf;
6344                 nhdr->b_l1hdr.b_bufcnt = 1;
6345                 (void) refcount_add(&nhdr->b_l1hdr.b_refcnt, tag);
6346                 buf->b_hdr = nhdr;
6347
6348                 mutex_exit(&buf->b_evict_lock);
6349                 (void) refcount_add_many(&arc_anon->arcs_size,
6350                     arc_buf_size(buf), buf);
6351         } else {
6352                 mutex_exit(&buf->b_evict_lock);
6353                 ASSERT(refcount_count(&hdr->b_l1hdr.b_refcnt) == 1);
6354                 /* protected by hash lock, or hdr is on arc_anon */
6355                 ASSERT(!multilist_link_active(&hdr->b_l1hdr.b_arc_node));
6356                 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6357                 arc_change_state(arc_anon, hdr, hash_lock);
6358                 hdr->b_l1hdr.b_arc_access = 0;
6359                 mutex_exit(hash_lock);
6360
6361                 buf_discard_identity(hdr);
6362                 arc_buf_thaw(buf);
6363         }
6364 }
6365
6366 int
6367 arc_released(arc_buf_t *buf)
6368 {
6369         int released;
6370
6371         mutex_enter(&buf->b_evict_lock);
6372         released = (buf->b_data != NULL &&
6373             buf->b_hdr->b_l1hdr.b_state == arc_anon);
6374         mutex_exit(&buf->b_evict_lock);
6375         return (released);
6376 }
6377
6378 #ifdef ZFS_DEBUG
6379 int
6380 arc_referenced(arc_buf_t *buf)
6381 {
6382         int referenced;
6383
6384         mutex_enter(&buf->b_evict_lock);
6385         referenced = (refcount_count(&buf->b_hdr->b_l1hdr.b_refcnt));
6386         mutex_exit(&buf->b_evict_lock);
6387         return (referenced);
6388 }
6389 #endif
6390
6391 static void
6392 arc_write_ready(zio_t *zio)
6393 {
6394         arc_write_callback_t *callback = zio->io_private;
6395         arc_buf_t *buf = callback->awcb_buf;
6396         arc_buf_hdr_t *hdr = buf->b_hdr;
6397         uint64_t psize = BP_IS_HOLE(zio->io_bp) ? 0 : BP_GET_PSIZE(zio->io_bp);
6398
6399         ASSERT(HDR_HAS_L1HDR(hdr));
6400         ASSERT(!refcount_is_zero(&buf->b_hdr->b_l1hdr.b_refcnt));
6401         ASSERT(hdr->b_l1hdr.b_bufcnt > 0);
6402
6403         /*
6404          * If we're reexecuting this zio because the pool suspended, then
6405          * cleanup any state that was previously set the first time the
6406          * callback was invoked.
6407          */
6408         if (zio->io_flags & ZIO_FLAG_REEXECUTED) {
6409                 arc_cksum_free(hdr);
6410 #ifdef illumos
6411                 arc_buf_unwatch(buf);
6412 #endif
6413                 if (hdr->b_l1hdr.b_pabd != NULL) {
6414                         if (arc_buf_is_shared(buf)) {
6415                                 arc_unshare_buf(hdr, buf);
6416                         } else {
6417                                 arc_hdr_free_pabd(hdr);
6418                         }
6419                 }
6420         }
6421         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6422         ASSERT(!HDR_SHARED_DATA(hdr));
6423         ASSERT(!arc_buf_is_shared(buf));
6424
6425         callback->awcb_ready(zio, buf, callback->awcb_private);
6426
6427         if (HDR_IO_IN_PROGRESS(hdr))
6428                 ASSERT(zio->io_flags & ZIO_FLAG_REEXECUTED);
6429
6430         arc_cksum_compute(buf);
6431         arc_hdr_set_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6432
6433         enum zio_compress compress;
6434         if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6435                 compress = ZIO_COMPRESS_OFF;
6436         } else {
6437                 ASSERT3U(HDR_GET_LSIZE(hdr), ==, BP_GET_LSIZE(zio->io_bp));
6438                 compress = BP_GET_COMPRESS(zio->io_bp);
6439         }
6440         HDR_SET_PSIZE(hdr, psize);
6441         arc_hdr_set_compress(hdr, compress);
6442
6443
6444         /*
6445          * Fill the hdr with data. If the hdr is compressed, the data we want
6446          * is available from the zio, otherwise we can take it from the buf.
6447          *
6448          * We might be able to share the buf's data with the hdr here. However,
6449          * doing so would cause the ARC to be full of linear ABDs if we write a
6450          * lot of shareable data. As a compromise, we check whether scattered
6451          * ABDs are allowed, and assume that if they are then the user wants
6452          * the ARC to be primarily filled with them regardless of the data being
6453          * written. Therefore, if they're allowed then we allocate one and copy
6454          * the data into it; otherwise, we share the data directly if we can.
6455          */
6456         if (zfs_abd_scatter_enabled || !arc_can_share(hdr, buf)) {
6457                 arc_hdr_alloc_pabd(hdr);
6458
6459                 /*
6460                  * Ideally, we would always copy the io_abd into b_pabd, but the
6461                  * user may have disabled compressed ARC, thus we must check the
6462                  * hdr's compression setting rather than the io_bp's.
6463                  */
6464                 if (HDR_GET_COMPRESS(hdr) != ZIO_COMPRESS_OFF) {
6465                         ASSERT3U(BP_GET_COMPRESS(zio->io_bp), !=,
6466                             ZIO_COMPRESS_OFF);
6467                         ASSERT3U(psize, >, 0);
6468
6469                         abd_copy(hdr->b_l1hdr.b_pabd, zio->io_abd, psize);
6470                 } else {
6471                         ASSERT3U(zio->io_orig_size, ==, arc_hdr_size(hdr));
6472
6473                         abd_copy_from_buf(hdr->b_l1hdr.b_pabd, buf->b_data,
6474                             arc_buf_size(buf));
6475                 }
6476         } else {
6477                 ASSERT3P(buf->b_data, ==, abd_to_buf(zio->io_orig_abd));
6478                 ASSERT3U(zio->io_orig_size, ==, arc_buf_size(buf));
6479                 ASSERT3U(hdr->b_l1hdr.b_bufcnt, ==, 1);
6480
6481                 arc_share_buf(hdr, buf);
6482         }
6483
6484         arc_hdr_verify(hdr, zio->io_bp);
6485 }
6486
6487 static void
6488 arc_write_children_ready(zio_t *zio)
6489 {
6490         arc_write_callback_t *callback = zio->io_private;
6491         arc_buf_t *buf = callback->awcb_buf;
6492
6493         callback->awcb_children_ready(zio, buf, callback->awcb_private);
6494 }
6495
6496 /*
6497  * The SPA calls this callback for each physical write that happens on behalf
6498  * of a logical write.  See the comment in dbuf_write_physdone() for details.
6499  */
6500 static void
6501 arc_write_physdone(zio_t *zio)
6502 {
6503         arc_write_callback_t *cb = zio->io_private;
6504         if (cb->awcb_physdone != NULL)
6505                 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
6506 }
6507
6508 static void
6509 arc_write_done(zio_t *zio)
6510 {
6511         arc_write_callback_t *callback = zio->io_private;
6512         arc_buf_t *buf = callback->awcb_buf;
6513         arc_buf_hdr_t *hdr = buf->b_hdr;
6514
6515         ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6516
6517         if (zio->io_error == 0) {
6518                 arc_hdr_verify(hdr, zio->io_bp);
6519
6520                 if (BP_IS_HOLE(zio->io_bp) || BP_IS_EMBEDDED(zio->io_bp)) {
6521                         buf_discard_identity(hdr);
6522                 } else {
6523                         hdr->b_dva = *BP_IDENTITY(zio->io_bp);
6524                         hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
6525                 }
6526         } else {
6527                 ASSERT(HDR_EMPTY(hdr));
6528         }
6529
6530         /*
6531          * If the block to be written was all-zero or compressed enough to be
6532          * embedded in the BP, no write was performed so there will be no
6533          * dva/birth/checksum.  The buffer must therefore remain anonymous
6534          * (and uncached).
6535          */
6536         if (!HDR_EMPTY(hdr)) {
6537                 arc_buf_hdr_t *exists;
6538                 kmutex_t *hash_lock;
6539
6540                 ASSERT3U(zio->io_error, ==, 0);
6541
6542                 arc_cksum_verify(buf);
6543
6544                 exists = buf_hash_insert(hdr, &hash_lock);
6545                 if (exists != NULL) {
6546                         /*
6547                          * This can only happen if we overwrite for
6548                          * sync-to-convergence, because we remove
6549                          * buffers from the hash table when we arc_free().
6550                          */
6551                         if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
6552                                 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6553                                         panic("bad overwrite, hdr=%p exists=%p",
6554                                             (void *)hdr, (void *)exists);
6555                                 ASSERT(refcount_is_zero(
6556                                     &exists->b_l1hdr.b_refcnt));
6557                                 arc_change_state(arc_anon, exists, hash_lock);
6558                                 mutex_exit(hash_lock);
6559                                 arc_hdr_destroy(exists);
6560                                 exists = buf_hash_insert(hdr, &hash_lock);
6561                                 ASSERT3P(exists, ==, NULL);
6562                         } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
6563                                 /* nopwrite */
6564                                 ASSERT(zio->io_prop.zp_nopwrite);
6565                                 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
6566                                         panic("bad nopwrite, hdr=%p exists=%p",
6567                                             (void *)hdr, (void *)exists);
6568                         } else {
6569                                 /* Dedup */
6570                                 ASSERT(hdr->b_l1hdr.b_bufcnt == 1);
6571                                 ASSERT(hdr->b_l1hdr.b_state == arc_anon);
6572                                 ASSERT(BP_GET_DEDUP(zio->io_bp));
6573                                 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
6574                         }
6575                 }
6576                 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6577                 /* if it's not anon, we are doing a scrub */
6578                 if (exists == NULL && hdr->b_l1hdr.b_state == arc_anon)
6579                         arc_access(hdr, hash_lock);
6580                 mutex_exit(hash_lock);
6581         } else {
6582                 arc_hdr_clear_flags(hdr, ARC_FLAG_IO_IN_PROGRESS);
6583         }
6584
6585         ASSERT(!refcount_is_zero(&hdr->b_l1hdr.b_refcnt));
6586         callback->awcb_done(zio, buf, callback->awcb_private);
6587
6588         abd_put(zio->io_abd);
6589         kmem_free(callback, sizeof (arc_write_callback_t));
6590 }
6591
6592 zio_t *
6593 arc_write(zio_t *pio, spa_t *spa, uint64_t txg, blkptr_t *bp, arc_buf_t *buf,
6594     boolean_t l2arc, const zio_prop_t *zp, arc_write_done_func_t *ready,
6595     arc_write_done_func_t *children_ready, arc_write_done_func_t *physdone,
6596     arc_write_done_func_t *done, void *private, zio_priority_t priority,
6597     int zio_flags, const zbookmark_phys_t *zb)
6598 {
6599         arc_buf_hdr_t *hdr = buf->b_hdr;
6600         arc_write_callback_t *callback;
6601         zio_t *zio;
6602         zio_prop_t localprop = *zp;
6603
6604         ASSERT3P(ready, !=, NULL);
6605         ASSERT3P(done, !=, NULL);
6606         ASSERT(!HDR_IO_ERROR(hdr));
6607         ASSERT(!HDR_IO_IN_PROGRESS(hdr));
6608         ASSERT3P(hdr->b_l1hdr.b_acb, ==, NULL);
6609         ASSERT3U(hdr->b_l1hdr.b_bufcnt, >, 0);
6610         if (l2arc)
6611                 arc_hdr_set_flags(hdr, ARC_FLAG_L2CACHE);
6612         if (ARC_BUF_COMPRESSED(buf)) {
6613                 /*
6614                  * We're writing a pre-compressed buffer.  Make the
6615                  * compression algorithm requested by the zio_prop_t match
6616                  * the pre-compressed buffer's compression algorithm.
6617                  */
6618                 localprop.zp_compress = HDR_GET_COMPRESS(hdr);
6619
6620                 ASSERT3U(HDR_GET_LSIZE(hdr), !=, arc_buf_size(buf));
6621                 zio_flags |= ZIO_FLAG_RAW;
6622         }
6623         callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_SLEEP);
6624         callback->awcb_ready = ready;
6625         callback->awcb_children_ready = children_ready;
6626         callback->awcb_physdone = physdone;
6627         callback->awcb_done = done;
6628         callback->awcb_private = private;
6629         callback->awcb_buf = buf;
6630
6631         /*
6632          * The hdr's b_pabd is now stale, free it now. A new data block
6633          * will be allocated when the zio pipeline calls arc_write_ready().
6634          */
6635         if (hdr->b_l1hdr.b_pabd != NULL) {
6636                 /*
6637                  * If the buf is currently sharing the data block with
6638                  * the hdr then we need to break that relationship here.
6639                  * The hdr will remain with a NULL data pointer and the
6640                  * buf will take sole ownership of the block.
6641                  */
6642                 if (arc_buf_is_shared(buf)) {
6643                         arc_unshare_buf(hdr, buf);
6644                 } else {
6645                         arc_hdr_free_pabd(hdr);
6646                 }
6647                 VERIFY3P(buf->b_data, !=, NULL);
6648                 arc_hdr_set_compress(hdr, ZIO_COMPRESS_OFF);
6649         }
6650         ASSERT(!arc_buf_is_shared(buf));
6651         ASSERT3P(hdr->b_l1hdr.b_pabd, ==, NULL);
6652
6653         zio = zio_write(pio, spa, txg, bp,
6654             abd_get_from_buf(buf->b_data, HDR_GET_LSIZE(hdr)),
6655             HDR_GET_LSIZE(hdr), arc_buf_size(buf), &localprop, arc_write_ready,
6656             (children_ready != NULL) ? arc_write_children_ready : NULL,
6657             arc_write_physdone, arc_write_done, callback,
6658             priority, zio_flags, zb);
6659
6660         return (zio);
6661 }
6662
6663 static int
6664 arc_memory_throttle(spa_t *spa, uint64_t reserve, uint64_t txg)
6665 {
6666 #ifdef _KERNEL
6667         uint64_t available_memory = ptob(freemem);
6668
6669 #if defined(__i386) || !defined(UMA_MD_SMALL_ALLOC)
6670         available_memory = MIN(available_memory, uma_avail());
6671 #endif
6672
6673         if (freemem > (uint64_t)physmem * arc_lotsfree_percent / 100)
6674                 return (0);
6675
6676         if (txg > spa->spa_lowmem_last_txg) {
6677                 spa->spa_lowmem_last_txg = txg;
6678                 spa->spa_lowmem_page_load = 0;
6679         }
6680         /*
6681          * If we are in pageout, we know that memory is already tight,
6682          * the arc is already going to be evicting, so we just want to
6683          * continue to let page writes occur as quickly as possible.
6684          */
6685         if (curproc == pageproc) {
6686                 if (spa->spa_lowmem_page_load >
6687                     MAX(ptob(minfree), available_memory) / 4)
6688                         return (SET_ERROR(ERESTART));
6689                 /* Note: reserve is inflated, so we deflate */
6690                 atomic_add_64(&spa->spa_lowmem_page_load, reserve / 8);
6691                 return (0);
6692         } else if (spa->spa_lowmem_page_load > 0 && arc_reclaim_needed()) {
6693                 /* memory is low, delay before restarting */
6694                 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
6695                 return (SET_ERROR(EAGAIN));
6696         }
6697         spa->spa_lowmem_page_load = 0;
6698 #endif /* _KERNEL */
6699         return (0);
6700 }
6701
6702 void
6703 arc_tempreserve_clear(uint64_t reserve)
6704 {
6705         atomic_add_64(&arc_tempreserve, -reserve);
6706         ASSERT((int64_t)arc_tempreserve >= 0);
6707 }
6708
6709 int
6710 arc_tempreserve_space(spa_t *spa, uint64_t reserve, uint64_t txg)
6711 {
6712         int error;
6713         uint64_t anon_size;
6714
6715         if (reserve > arc_c/4 && !arc_no_grow) {
6716                 arc_c = MIN(arc_c_max, reserve * 4);
6717                 DTRACE_PROBE1(arc__set_reserve, uint64_t, arc_c);
6718         }
6719         if (reserve > arc_c)
6720                 return (SET_ERROR(ENOMEM));
6721
6722         /*
6723          * Don't count loaned bufs as in flight dirty data to prevent long
6724          * network delays from blocking transactions that are ready to be
6725          * assigned to a txg.
6726          */
6727
6728         /* assert that it has not wrapped around */
6729         ASSERT3S(atomic_add_64_nv(&arc_loaned_bytes, 0), >=, 0);
6730
6731         anon_size = MAX((int64_t)(refcount_count(&arc_anon->arcs_size) -
6732             arc_loaned_bytes), 0);
6733
6734         /*
6735          * Writes will, almost always, require additional memory allocations
6736          * in order to compress/encrypt/etc the data.  We therefore need to
6737          * make sure that there is sufficient available memory for this.
6738          */
6739         error = arc_memory_throttle(spa, reserve, txg);
6740         if (error != 0)
6741                 return (error);
6742
6743         /*
6744          * Throttle writes when the amount of dirty data in the cache
6745          * gets too large.  We try to keep the cache less than half full
6746          * of dirty blocks so that our sync times don't grow too large.
6747          *
6748          * In the case of one pool being built on another pool, we want
6749          * to make sure we don't end up throttling the lower (backing)
6750          * pool when the upper pool is the majority contributor to dirty
6751          * data. To insure we make forward progress during throttling, we
6752          * also check the current pool's net dirty data and only throttle
6753          * if it exceeds zfs_arc_pool_dirty_percent of the anonymous dirty
6754          * data in the cache.
6755          *
6756          * Note: if two requests come in concurrently, we might let them
6757          * both succeed, when one of them should fail.  Not a huge deal.
6758          */
6759         uint64_t total_dirty = reserve + arc_tempreserve + anon_size;
6760         uint64_t spa_dirty_anon = spa_dirty_data(spa);
6761
6762         if (total_dirty > arc_c * zfs_arc_dirty_limit_percent / 100 &&
6763             anon_size > arc_c * zfs_arc_anon_limit_percent / 100 &&
6764             spa_dirty_anon > anon_size * zfs_arc_pool_dirty_percent / 100) {
6765                 uint64_t meta_esize =
6766                     refcount_count(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6767                 uint64_t data_esize =
6768                     refcount_count(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6769                 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
6770                     "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
6771                     arc_tempreserve >> 10, meta_esize >> 10,
6772                     data_esize >> 10, reserve >> 10, arc_c >> 10);
6773                 return (SET_ERROR(ERESTART));
6774         }
6775         atomic_add_64(&arc_tempreserve, reserve);
6776         return (0);
6777 }
6778
6779 static void
6780 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
6781     kstat_named_t *evict_data, kstat_named_t *evict_metadata)
6782 {
6783         size->value.ui64 = refcount_count(&state->arcs_size);
6784         evict_data->value.ui64 =
6785             refcount_count(&state->arcs_esize[ARC_BUFC_DATA]);
6786         evict_metadata->value.ui64 =
6787             refcount_count(&state->arcs_esize[ARC_BUFC_METADATA]);
6788 }
6789
6790 static int
6791 arc_kstat_update(kstat_t *ksp, int rw)
6792 {
6793         arc_stats_t *as = ksp->ks_data;
6794
6795         if (rw == KSTAT_WRITE) {
6796                 return (EACCES);
6797         } else {
6798                 arc_kstat_update_state(arc_anon,
6799                     &as->arcstat_anon_size,
6800                     &as->arcstat_anon_evictable_data,
6801                     &as->arcstat_anon_evictable_metadata);
6802                 arc_kstat_update_state(arc_mru,
6803                     &as->arcstat_mru_size,
6804                     &as->arcstat_mru_evictable_data,
6805                     &as->arcstat_mru_evictable_metadata);
6806                 arc_kstat_update_state(arc_mru_ghost,
6807                     &as->arcstat_mru_ghost_size,
6808                     &as->arcstat_mru_ghost_evictable_data,
6809                     &as->arcstat_mru_ghost_evictable_metadata);
6810                 arc_kstat_update_state(arc_mfu,
6811                     &as->arcstat_mfu_size,
6812                     &as->arcstat_mfu_evictable_data,
6813                     &as->arcstat_mfu_evictable_metadata);
6814                 arc_kstat_update_state(arc_mfu_ghost,
6815                     &as->arcstat_mfu_ghost_size,
6816                     &as->arcstat_mfu_ghost_evictable_data,
6817                     &as->arcstat_mfu_ghost_evictable_metadata);
6818
6819                 ARCSTAT(arcstat_size) = aggsum_value(&arc_size);
6820                 ARCSTAT(arcstat_meta_used) = aggsum_value(&arc_meta_used);
6821                 ARCSTAT(arcstat_data_size) = aggsum_value(&astat_data_size);
6822                 ARCSTAT(arcstat_metadata_size) =
6823                     aggsum_value(&astat_metadata_size);
6824                 ARCSTAT(arcstat_hdr_size) = aggsum_value(&astat_hdr_size);
6825                 ARCSTAT(arcstat_bonus_size) = aggsum_value(&astat_bonus_size);
6826                 ARCSTAT(arcstat_dnode_size) = aggsum_value(&astat_dnode_size);
6827                 ARCSTAT(arcstat_dbuf_size) = aggsum_value(&astat_dbuf_size);
6828                 ARCSTAT(arcstat_l2_hdr_size) = aggsum_value(&astat_l2_hdr_size);
6829         }
6830
6831         return (0);
6832 }
6833
6834 /*
6835  * This function *must* return indices evenly distributed between all
6836  * sublists of the multilist. This is needed due to how the ARC eviction
6837  * code is laid out; arc_evict_state() assumes ARC buffers are evenly
6838  * distributed between all sublists and uses this assumption when
6839  * deciding which sublist to evict from and how much to evict from it.
6840  */
6841 unsigned int
6842 arc_state_multilist_index_func(multilist_t *ml, void *obj)
6843 {
6844         arc_buf_hdr_t *hdr = obj;
6845
6846         /*
6847          * We rely on b_dva to generate evenly distributed index
6848          * numbers using buf_hash below. So, as an added precaution,
6849          * let's make sure we never add empty buffers to the arc lists.
6850          */
6851         ASSERT(!HDR_EMPTY(hdr));
6852
6853         /*
6854          * The assumption here, is the hash value for a given
6855          * arc_buf_hdr_t will remain constant throughout it's lifetime
6856          * (i.e. it's b_spa, b_dva, and b_birth fields don't change).
6857          * Thus, we don't need to store the header's sublist index
6858          * on insertion, as this index can be recalculated on removal.
6859          *
6860          * Also, the low order bits of the hash value are thought to be
6861          * distributed evenly. Otherwise, in the case that the multilist
6862          * has a power of two number of sublists, each sublists' usage
6863          * would not be evenly distributed.
6864          */
6865         return (buf_hash(hdr->b_spa, &hdr->b_dva, hdr->b_birth) %
6866             multilist_get_num_sublists(ml));
6867 }
6868
6869 #ifdef _KERNEL
6870 static eventhandler_tag arc_event_lowmem = NULL;
6871
6872 static void
6873 arc_lowmem(void *arg __unused, int howto __unused)
6874 {
6875
6876         mutex_enter(&arc_reclaim_lock);
6877         DTRACE_PROBE1(arc__needfree, int64_t, ((int64_t)freemem - zfs_arc_free_target) * PAGESIZE);
6878         cv_signal(&arc_reclaim_thread_cv);
6879
6880         /*
6881          * It is unsafe to block here in arbitrary threads, because we can come
6882          * here from ARC itself and may hold ARC locks and thus risk a deadlock
6883          * with ARC reclaim thread.
6884          */
6885         if (curproc == pageproc)
6886                 (void) cv_wait(&arc_reclaim_waiters_cv, &arc_reclaim_lock);
6887         mutex_exit(&arc_reclaim_lock);
6888 }
6889 #endif
6890
6891 static void
6892 arc_state_init(void)
6893 {
6894         arc_anon = &ARC_anon;
6895         arc_mru = &ARC_mru;
6896         arc_mru_ghost = &ARC_mru_ghost;
6897         arc_mfu = &ARC_mfu;
6898         arc_mfu_ghost = &ARC_mfu_ghost;
6899         arc_l2c_only = &ARC_l2c_only;
6900
6901         arc_mru->arcs_list[ARC_BUFC_METADATA] =
6902             multilist_create(sizeof (arc_buf_hdr_t),
6903             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6904             arc_state_multilist_index_func);
6905         arc_mru->arcs_list[ARC_BUFC_DATA] =
6906             multilist_create(sizeof (arc_buf_hdr_t),
6907             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6908             arc_state_multilist_index_func);
6909         arc_mru_ghost->arcs_list[ARC_BUFC_METADATA] =
6910             multilist_create(sizeof (arc_buf_hdr_t),
6911             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6912             arc_state_multilist_index_func);
6913         arc_mru_ghost->arcs_list[ARC_BUFC_DATA] =
6914             multilist_create(sizeof (arc_buf_hdr_t),
6915             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6916             arc_state_multilist_index_func);
6917         arc_mfu->arcs_list[ARC_BUFC_METADATA] =
6918             multilist_create(sizeof (arc_buf_hdr_t),
6919             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6920             arc_state_multilist_index_func);
6921         arc_mfu->arcs_list[ARC_BUFC_DATA] =
6922             multilist_create(sizeof (arc_buf_hdr_t),
6923             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6924             arc_state_multilist_index_func);
6925         arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA] =
6926             multilist_create(sizeof (arc_buf_hdr_t),
6927             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6928             arc_state_multilist_index_func);
6929         arc_mfu_ghost->arcs_list[ARC_BUFC_DATA] =
6930             multilist_create(sizeof (arc_buf_hdr_t),
6931             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6932             arc_state_multilist_index_func);
6933         arc_l2c_only->arcs_list[ARC_BUFC_METADATA] =
6934             multilist_create(sizeof (arc_buf_hdr_t),
6935             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6936             arc_state_multilist_index_func);
6937         arc_l2c_only->arcs_list[ARC_BUFC_DATA] =
6938             multilist_create(sizeof (arc_buf_hdr_t),
6939             offsetof(arc_buf_hdr_t, b_l1hdr.b_arc_node),
6940             arc_state_multilist_index_func);
6941
6942         refcount_create(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6943         refcount_create(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6944         refcount_create(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6945         refcount_create(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6946         refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6947         refcount_create(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6948         refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6949         refcount_create(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6950         refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6951         refcount_create(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6952         refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6953         refcount_create(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6954
6955         refcount_create(&arc_anon->arcs_size);
6956         refcount_create(&arc_mru->arcs_size);
6957         refcount_create(&arc_mru_ghost->arcs_size);
6958         refcount_create(&arc_mfu->arcs_size);
6959         refcount_create(&arc_mfu_ghost->arcs_size);
6960         refcount_create(&arc_l2c_only->arcs_size);
6961
6962         aggsum_init(&arc_meta_used, 0);
6963         aggsum_init(&arc_size, 0);
6964         aggsum_init(&astat_data_size, 0);
6965         aggsum_init(&astat_metadata_size, 0);
6966         aggsum_init(&astat_hdr_size, 0);
6967         aggsum_init(&astat_bonus_size, 0);
6968         aggsum_init(&astat_dnode_size, 0);
6969         aggsum_init(&astat_dbuf_size, 0);
6970         aggsum_init(&astat_l2_hdr_size, 0);
6971 }
6972
6973 static void
6974 arc_state_fini(void)
6975 {
6976         refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_METADATA]);
6977         refcount_destroy(&arc_anon->arcs_esize[ARC_BUFC_DATA]);
6978         refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_METADATA]);
6979         refcount_destroy(&arc_mru->arcs_esize[ARC_BUFC_DATA]);
6980         refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_METADATA]);
6981         refcount_destroy(&arc_mru_ghost->arcs_esize[ARC_BUFC_DATA]);
6982         refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_METADATA]);
6983         refcount_destroy(&arc_mfu->arcs_esize[ARC_BUFC_DATA]);
6984         refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_METADATA]);
6985         refcount_destroy(&arc_mfu_ghost->arcs_esize[ARC_BUFC_DATA]);
6986         refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_METADATA]);
6987         refcount_destroy(&arc_l2c_only->arcs_esize[ARC_BUFC_DATA]);
6988
6989         refcount_destroy(&arc_anon->arcs_size);
6990         refcount_destroy(&arc_mru->arcs_size);
6991         refcount_destroy(&arc_mru_ghost->arcs_size);
6992         refcount_destroy(&arc_mfu->arcs_size);
6993         refcount_destroy(&arc_mfu_ghost->arcs_size);
6994         refcount_destroy(&arc_l2c_only->arcs_size);
6995
6996         multilist_destroy(arc_mru->arcs_list[ARC_BUFC_METADATA]);
6997         multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
6998         multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_METADATA]);
6999         multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
7000         multilist_destroy(arc_mru->arcs_list[ARC_BUFC_DATA]);
7001         multilist_destroy(arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
7002         multilist_destroy(arc_mfu->arcs_list[ARC_BUFC_DATA]);
7003         multilist_destroy(arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
7004 }
7005
7006 uint64_t
7007 arc_max_bytes(void)
7008 {
7009         return (arc_c_max);
7010 }
7011
7012 void
7013 arc_init(void)
7014 {
7015         int i, prefetch_tunable_set = 0;
7016
7017         /*
7018          * allmem is "all memory that we could possibly use".
7019          */
7020 #ifdef illumos
7021 #ifdef _KERNEL
7022         uint64_t allmem = ptob(physmem - swapfs_minfree);
7023 #else
7024         uint64_t allmem = (physmem * PAGESIZE) / 2;
7025 #endif
7026 #else
7027         uint64_t allmem = kmem_size();
7028 #endif
7029
7030
7031         mutex_init(&arc_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
7032         cv_init(&arc_reclaim_thread_cv, NULL, CV_DEFAULT, NULL);
7033         cv_init(&arc_reclaim_waiters_cv, NULL, CV_DEFAULT, NULL);
7034
7035         mutex_init(&arc_dnlc_evicts_lock, NULL, MUTEX_DEFAULT, NULL);
7036         cv_init(&arc_dnlc_evicts_cv, NULL, CV_DEFAULT, NULL);
7037
7038         /* set min cache to 1/32 of all memory, or arc_abs_min, whichever is more */
7039         arc_c_min = MAX(allmem / 32, arc_abs_min);
7040         /* set max to 5/8 of all memory, or all but 1GB, whichever is more */
7041         if (allmem >= 1 << 30)
7042                 arc_c_max = allmem - (1 << 30);
7043         else
7044                 arc_c_max = arc_c_min;
7045         arc_c_max = MAX(allmem * 5 / 8, arc_c_max);
7046
7047         /*
7048          * In userland, there's only the memory pressure that we artificially
7049          * create (see arc_available_memory()).  Don't let arc_c get too
7050          * small, because it can cause transactions to be larger than
7051          * arc_c, causing arc_tempreserve_space() to fail.
7052          */
7053 #ifndef _KERNEL
7054         arc_c_min = arc_c_max / 2;
7055 #endif
7056
7057 #ifdef _KERNEL
7058         /*
7059          * Allow the tunables to override our calculations if they are
7060          * reasonable.
7061          */
7062         if (zfs_arc_max > arc_abs_min && zfs_arc_max < allmem) {
7063                 arc_c_max = zfs_arc_max;
7064                 arc_c_min = MIN(arc_c_min, arc_c_max);
7065         }
7066         if (zfs_arc_min > arc_abs_min && zfs_arc_min <= arc_c_max)
7067                 arc_c_min = zfs_arc_min;
7068 #endif
7069
7070         arc_c = arc_c_max;
7071         arc_p = (arc_c >> 1);
7072
7073         /* limit meta-data to 1/4 of the arc capacity */
7074         arc_meta_limit = arc_c_max / 4;
7075
7076 #ifdef _KERNEL
7077         /*
7078          * Metadata is stored in the kernel's heap.  Don't let us
7079          * use more than half the heap for the ARC.
7080          */
7081 #ifdef __FreeBSD__
7082         arc_meta_limit = MIN(arc_meta_limit, uma_limit() / 2);
7083         arc_dnode_limit = arc_meta_limit / 10;
7084 #else
7085         arc_meta_limit = MIN(arc_meta_limit,
7086             vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 2);
7087 #endif
7088 #endif
7089
7090         /* Allow the tunable to override if it is reasonable */
7091         if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
7092                 arc_meta_limit = zfs_arc_meta_limit;
7093
7094         if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
7095                 arc_c_min = arc_meta_limit / 2;
7096
7097         if (zfs_arc_meta_min > 0) {
7098                 arc_meta_min = zfs_arc_meta_min;
7099         } else {
7100                 arc_meta_min = arc_c_min / 2;
7101         }
7102
7103         /* Valid range: <arc_meta_min> - <arc_c_max> */
7104         if ((zfs_arc_dnode_limit) && (zfs_arc_dnode_limit != arc_dnode_limit) &&
7105             (zfs_arc_dnode_limit >= zfs_arc_meta_min) &&
7106             (zfs_arc_dnode_limit <= arc_c_max))
7107                 arc_dnode_limit = zfs_arc_dnode_limit;
7108
7109         if (zfs_arc_grow_retry > 0)
7110                 arc_grow_retry = zfs_arc_grow_retry;
7111
7112         if (zfs_arc_shrink_shift > 0)
7113                 arc_shrink_shift = zfs_arc_shrink_shift;
7114
7115         if (zfs_arc_no_grow_shift > 0)
7116                 arc_no_grow_shift = zfs_arc_no_grow_shift;
7117         /*
7118          * Ensure that arc_no_grow_shift is less than arc_shrink_shift.
7119          */
7120         if (arc_no_grow_shift >= arc_shrink_shift)
7121                 arc_no_grow_shift = arc_shrink_shift - 1;
7122
7123         if (zfs_arc_p_min_shift > 0)
7124                 arc_p_min_shift = zfs_arc_p_min_shift;
7125
7126         /* if kmem_flags are set, lets try to use less memory */
7127         if (kmem_debugging())
7128                 arc_c = arc_c / 2;
7129         if (arc_c < arc_c_min)
7130                 arc_c = arc_c_min;
7131
7132         zfs_arc_min = arc_c_min;
7133         zfs_arc_max = arc_c_max;
7134
7135         arc_state_init();
7136         buf_init();
7137
7138         list_create(&arc_prune_list, sizeof (arc_prune_t),
7139             offsetof(arc_prune_t, p_node));
7140         mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
7141
7142         arc_prune_taskq = taskq_create("arc_prune", max_ncpus, minclsyspri,
7143             max_ncpus, INT_MAX, TASKQ_PREPOPULATE | TASKQ_DYNAMIC);
7144
7145         arc_reclaim_thread_exit = B_FALSE;
7146         arc_dnlc_evicts_thread_exit = FALSE;
7147
7148         arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
7149             sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
7150
7151         if (arc_ksp != NULL) {
7152                 arc_ksp->ks_data = &arc_stats;
7153                 arc_ksp->ks_update = arc_kstat_update;
7154                 kstat_install(arc_ksp);
7155         }
7156
7157         (void) thread_create(NULL, 0, arc_reclaim_thread, NULL, 0, &p0,
7158             TS_RUN, minclsyspri);
7159
7160 #ifdef _KERNEL
7161         arc_event_lowmem = EVENTHANDLER_REGISTER(vm_lowmem, arc_lowmem, NULL,
7162             EVENTHANDLER_PRI_FIRST);
7163 #endif
7164
7165         (void) thread_create(NULL, 0, arc_dnlc_evicts_thread, NULL, 0, &p0,
7166             TS_RUN, minclsyspri);
7167
7168         arc_dead = B_FALSE;
7169         arc_warm = B_FALSE;
7170
7171         /*
7172          * Calculate maximum amount of dirty data per pool.
7173          *
7174          * If it has been set by /etc/system, take that.
7175          * Otherwise, use a percentage of physical memory defined by
7176          * zfs_dirty_data_max_percent (default 10%) with a cap at
7177          * zfs_dirty_data_max_max (default 4GB).
7178          */
7179         if (zfs_dirty_data_max == 0) {
7180                 zfs_dirty_data_max = ptob(physmem) *
7181                     zfs_dirty_data_max_percent / 100;
7182                 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
7183                     zfs_dirty_data_max_max);
7184         }
7185
7186 #ifdef _KERNEL
7187         if (TUNABLE_INT_FETCH("vfs.zfs.prefetch_disable", &zfs_prefetch_disable))
7188                 prefetch_tunable_set = 1;
7189
7190 #ifdef __i386__
7191         if (prefetch_tunable_set == 0) {
7192                 printf("ZFS NOTICE: Prefetch is disabled by default on i386 "
7193                     "-- to enable,\n");
7194                 printf("            add \"vfs.zfs.prefetch_disable=0\" "
7195                     "to /boot/loader.conf.\n");
7196                 zfs_prefetch_disable = 1;
7197         }
7198 #else
7199         if ((((uint64_t)physmem * PAGESIZE) < (1ULL << 32)) &&
7200             prefetch_tunable_set == 0) {
7201                 printf("ZFS NOTICE: Prefetch is disabled by default if less "
7202                     "than 4GB of RAM is present;\n"
7203                     "            to enable, add \"vfs.zfs.prefetch_disable=0\" "
7204                     "to /boot/loader.conf.\n");
7205                 zfs_prefetch_disable = 1;
7206         }
7207 #endif
7208         /* Warn about ZFS memory and address space requirements. */
7209         if (((uint64_t)physmem * PAGESIZE) < (256 + 128 + 64) * (1 << 20)) {
7210                 printf("ZFS WARNING: Recommended minimum RAM size is 512MB; "
7211                     "expect unstable behavior.\n");
7212         }
7213         if (allmem < 512 * (1 << 20)) {
7214                 printf("ZFS WARNING: Recommended minimum kmem_size is 512MB; "
7215                     "expect unstable behavior.\n");
7216                 printf("             Consider tuning vm.kmem_size and "
7217                     "vm.kmem_size_max\n");
7218                 printf("             in /boot/loader.conf.\n");
7219         }
7220 #endif
7221 }
7222
7223 void
7224 arc_fini(void)
7225 {
7226         arc_prune_t *p;
7227
7228 #ifdef _KERNEL
7229         if (arc_event_lowmem != NULL)
7230                 EVENTHANDLER_DEREGISTER(vm_lowmem, arc_event_lowmem);
7231 #endif
7232
7233         mutex_enter(&arc_reclaim_lock);
7234         arc_reclaim_thread_exit = B_TRUE;
7235         /*
7236          * The reclaim thread will set arc_reclaim_thread_exit back to
7237          * B_FALSE when it is finished exiting; we're waiting for that.
7238          */
7239         while (arc_reclaim_thread_exit) {
7240                 cv_signal(&arc_reclaim_thread_cv);
7241                 cv_wait(&arc_reclaim_thread_cv, &arc_reclaim_lock);
7242         }
7243         mutex_exit(&arc_reclaim_lock);
7244
7245         /* Use B_TRUE to ensure *all* buffers are evicted */
7246         arc_flush(NULL, B_TRUE);
7247
7248         mutex_enter(&arc_dnlc_evicts_lock);
7249         arc_dnlc_evicts_thread_exit = TRUE;
7250         /*
7251          * The user evicts thread will set arc_user_evicts_thread_exit
7252          * to FALSE when it is finished exiting; we're waiting for that.
7253          */
7254         while (arc_dnlc_evicts_thread_exit) {
7255                 cv_signal(&arc_dnlc_evicts_cv);
7256                 cv_wait(&arc_dnlc_evicts_cv, &arc_dnlc_evicts_lock);
7257         }
7258         mutex_exit(&arc_dnlc_evicts_lock);
7259
7260         arc_dead = B_TRUE;
7261
7262         if (arc_ksp != NULL) {
7263                 kstat_delete(arc_ksp);
7264                 arc_ksp = NULL;
7265         }
7266
7267         taskq_wait(arc_prune_taskq);
7268         taskq_destroy(arc_prune_taskq);
7269
7270         mutex_enter(&arc_prune_mtx);
7271         while ((p = list_head(&arc_prune_list)) != NULL) {
7272                 list_remove(&arc_prune_list, p);
7273                 refcount_remove(&p->p_refcnt, &arc_prune_list);
7274                 refcount_destroy(&p->p_refcnt);
7275                 kmem_free(p, sizeof (*p));
7276         }
7277         mutex_exit(&arc_prune_mtx);
7278
7279         list_destroy(&arc_prune_list);
7280         mutex_destroy(&arc_prune_mtx);
7281         mutex_destroy(&arc_reclaim_lock);
7282         cv_destroy(&arc_reclaim_thread_cv);
7283         cv_destroy(&arc_reclaim_waiters_cv);
7284
7285         mutex_destroy(&arc_dnlc_evicts_lock);
7286         cv_destroy(&arc_dnlc_evicts_cv);
7287
7288         arc_state_fini();
7289         buf_fini();
7290
7291         ASSERT0(arc_loaned_bytes);
7292 }
7293
7294 /*
7295  * Level 2 ARC
7296  *
7297  * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
7298  * It uses dedicated storage devices to hold cached data, which are populated
7299  * using large infrequent writes.  The main role of this cache is to boost
7300  * the performance of random read workloads.  The intended L2ARC devices
7301  * include short-stroked disks, solid state disks, and other media with
7302  * substantially faster read latency than disk.
7303  *
7304  *                 +-----------------------+
7305  *                 |         ARC           |
7306  *                 +-----------------------+
7307  *                    |         ^     ^
7308  *                    |         |     |
7309  *      l2arc_feed_thread()    arc_read()
7310  *                    |         |     |
7311  *                    |  l2arc read   |
7312  *                    V         |     |
7313  *               +---------------+    |
7314  *               |     L2ARC     |    |
7315  *               +---------------+    |
7316  *                   |    ^           |
7317  *          l2arc_write() |           |
7318  *                   |    |           |
7319  *                   V    |           |
7320  *                 +-------+      +-------+
7321  *                 | vdev  |      | vdev  |
7322  *                 | cache |      | cache |
7323  *                 +-------+      +-------+
7324  *                 +=========+     .-----.
7325  *                 :  L2ARC  :    |-_____-|
7326  *                 : devices :    | Disks |
7327  *                 +=========+    `-_____-'
7328  *
7329  * Read requests are satisfied from the following sources, in order:
7330  *
7331  *      1) ARC
7332  *      2) vdev cache of L2ARC devices
7333  *      3) L2ARC devices
7334  *      4) vdev cache of disks
7335  *      5) disks
7336  *
7337  * Some L2ARC device types exhibit extremely slow write performance.
7338  * To accommodate for this there are some significant differences between
7339  * the L2ARC and traditional cache design:
7340  *
7341  * 1. There is no eviction path from the ARC to the L2ARC.  Evictions from
7342  * the ARC behave as usual, freeing buffers and placing headers on ghost
7343  * lists.  The ARC does not send buffers to the L2ARC during eviction as
7344  * this would add inflated write latencies for all ARC memory pressure.
7345  *
7346  * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
7347  * It does this by periodically scanning buffers from the eviction-end of
7348  * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
7349  * not already there. It scans until a headroom of buffers is satisfied,
7350  * which itself is a buffer for ARC eviction. If a compressible buffer is
7351  * found during scanning and selected for writing to an L2ARC device, we
7352  * temporarily boost scanning headroom during the next scan cycle to make
7353  * sure we adapt to compression effects (which might significantly reduce
7354  * the data volume we write to L2ARC). The thread that does this is
7355  * l2arc_feed_thread(), illustrated below; example sizes are included to
7356  * provide a better sense of ratio than this diagram:
7357  *
7358  *             head -->                        tail
7359  *              +---------------------+----------+
7360  *      ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->.   # already on L2ARC
7361  *              +---------------------+----------+   |   o L2ARC eligible
7362  *      ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->|   : ARC buffer
7363  *              +---------------------+----------+   |
7364  *                   15.9 Gbytes      ^ 32 Mbytes    |
7365  *                                 headroom          |
7366  *                                            l2arc_feed_thread()
7367  *                                                   |
7368  *                       l2arc write hand <--[oooo]--'
7369  *                               |           8 Mbyte
7370  *                               |          write max
7371  *                               V
7372  *                +==============================+
7373  *      L2ARC dev |####|#|###|###|    |####| ... |
7374  *                +==============================+
7375  *                           32 Gbytes
7376  *
7377  * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
7378  * evicted, then the L2ARC has cached a buffer much sooner than it probably
7379  * needed to, potentially wasting L2ARC device bandwidth and storage.  It is
7380  * safe to say that this is an uncommon case, since buffers at the end of
7381  * the ARC lists have moved there due to inactivity.
7382  *
7383  * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
7384  * then the L2ARC simply misses copying some buffers.  This serves as a
7385  * pressure valve to prevent heavy read workloads from both stalling the ARC
7386  * with waits and clogging the L2ARC with writes.  This also helps prevent
7387  * the potential for the L2ARC to churn if it attempts to cache content too
7388  * quickly, such as during backups of the entire pool.
7389  *
7390  * 5. After system boot and before the ARC has filled main memory, there are
7391  * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
7392  * lists can remain mostly static.  Instead of searching from tail of these
7393  * lists as pictured, the l2arc_feed_thread() will search from the list heads
7394  * for eligible buffers, greatly increasing its chance of finding them.
7395  *
7396  * The L2ARC device write speed is also boosted during this time so that
7397  * the L2ARC warms up faster.  Since there have been no ARC evictions yet,
7398  * there are no L2ARC reads, and no fear of degrading read performance
7399  * through increased writes.
7400  *
7401  * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
7402  * the vdev queue can aggregate them into larger and fewer writes.  Each
7403  * device is written to in a rotor fashion, sweeping writes through
7404  * available space then repeating.
7405  *
7406  * 7. The L2ARC does not store dirty content.  It never needs to flush
7407  * write buffers back to disk based storage.
7408  *
7409  * 8. If an ARC buffer is written (and dirtied) which also exists in the
7410  * L2ARC, the now stale L2ARC buffer is immediately dropped.
7411  *
7412  * The performance of the L2ARC can be tweaked by a number of tunables, which
7413  * may be necessary for different workloads:
7414  *
7415  *      l2arc_write_max         max write bytes per interval
7416  *      l2arc_write_boost       extra write bytes during device warmup
7417  *      l2arc_noprefetch        skip caching prefetched buffers
7418  *      l2arc_headroom          number of max device writes to precache
7419  *      l2arc_headroom_boost    when we find compressed buffers during ARC
7420  *                              scanning, we multiply headroom by this
7421  *                              percentage factor for the next scan cycle,
7422  *                              since more compressed buffers are likely to
7423  *                              be present
7424  *      l2arc_feed_secs         seconds between L2ARC writing
7425  *
7426  * Tunables may be removed or added as future performance improvements are
7427  * integrated, and also may become zpool properties.
7428  *
7429  * There are three key functions that control how the L2ARC warms up:
7430  *
7431  *      l2arc_write_eligible()  check if a buffer is eligible to cache
7432  *      l2arc_write_size()      calculate how much to write
7433  *      l2arc_write_interval()  calculate sleep delay between writes
7434  *
7435  * These three functions determine what to write, how much, and how quickly
7436  * to send writes.
7437  */
7438
7439 static boolean_t
7440 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *hdr)
7441 {
7442         /*
7443          * A buffer is *not* eligible for the L2ARC if it:
7444          * 1. belongs to a different spa.
7445          * 2. is already cached on the L2ARC.
7446          * 3. has an I/O in progress (it may be an incomplete read).
7447          * 4. is flagged not eligible (zfs property).
7448          */
7449         if (hdr->b_spa != spa_guid) {
7450                 ARCSTAT_BUMP(arcstat_l2_write_spa_mismatch);
7451                 return (B_FALSE);
7452         }
7453         if (HDR_HAS_L2HDR(hdr)) {
7454                 ARCSTAT_BUMP(arcstat_l2_write_in_l2);
7455                 return (B_FALSE);
7456         }
7457         if (HDR_IO_IN_PROGRESS(hdr)) {
7458                 ARCSTAT_BUMP(arcstat_l2_write_hdr_io_in_progress);
7459                 return (B_FALSE);
7460         }
7461         if (!HDR_L2CACHE(hdr)) {
7462                 ARCSTAT_BUMP(arcstat_l2_write_not_cacheable);
7463                 return (B_FALSE);
7464         }
7465
7466         return (B_TRUE);
7467 }
7468
7469 static uint64_t
7470 l2arc_write_size(void)
7471 {
7472         uint64_t size;
7473
7474         /*
7475          * Make sure our globals have meaningful values in case the user
7476          * altered them.
7477          */
7478         size = l2arc_write_max;
7479         if (size == 0) {
7480                 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
7481                     "be greater than zero, resetting it to the default (%d)",
7482                     L2ARC_WRITE_SIZE);
7483                 size = l2arc_write_max = L2ARC_WRITE_SIZE;
7484         }
7485
7486         if (arc_warm == B_FALSE)
7487                 size += l2arc_write_boost;
7488
7489         return (size);
7490
7491 }
7492
7493 static clock_t
7494 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
7495 {
7496         clock_t interval, next, now;
7497
7498         /*
7499          * If the ARC lists are busy, increase our write rate; if the
7500          * lists are stale, idle back.  This is achieved by checking
7501          * how much we previously wrote - if it was more than half of
7502          * what we wanted, schedule the next write much sooner.
7503          */
7504         if (l2arc_feed_again && wrote > (wanted / 2))
7505                 interval = (hz * l2arc_feed_min_ms) / 1000;
7506         else
7507                 interval = hz * l2arc_feed_secs;
7508
7509         now = ddi_get_lbolt();
7510         next = MAX(now, MIN(now + interval, began + interval));
7511
7512         return (next);
7513 }
7514
7515 /*
7516  * Cycle through L2ARC devices.  This is how L2ARC load balances.
7517  * If a device is returned, this also returns holding the spa config lock.
7518  */
7519 static l2arc_dev_t *
7520 l2arc_dev_get_next(void)
7521 {
7522         l2arc_dev_t *first, *next = NULL;
7523
7524         /*
7525          * Lock out the removal of spas (spa_namespace_lock), then removal
7526          * of cache devices (l2arc_dev_mtx).  Once a device has been selected,
7527          * both locks will be dropped and a spa config lock held instead.
7528          */
7529         mutex_enter(&spa_namespace_lock);
7530         mutex_enter(&l2arc_dev_mtx);
7531
7532         /* if there are no vdevs, there is nothing to do */
7533         if (l2arc_ndev == 0)
7534                 goto out;
7535
7536         first = NULL;
7537         next = l2arc_dev_last;
7538         do {
7539                 /* loop around the list looking for a non-faulted vdev */
7540                 if (next == NULL) {
7541                         next = list_head(l2arc_dev_list);
7542                 } else {
7543                         next = list_next(l2arc_dev_list, next);
7544                         if (next == NULL)
7545                                 next = list_head(l2arc_dev_list);
7546                 }
7547
7548                 /* if we have come back to the start, bail out */
7549                 if (first == NULL)
7550                         first = next;
7551                 else if (next == first)
7552                         break;
7553
7554         } while (vdev_is_dead(next->l2ad_vdev));
7555
7556         /* if we were unable to find any usable vdevs, return NULL */
7557         if (vdev_is_dead(next->l2ad_vdev))
7558                 next = NULL;
7559
7560         l2arc_dev_last = next;
7561
7562 out:
7563         mutex_exit(&l2arc_dev_mtx);
7564
7565         /*
7566          * Grab the config lock to prevent the 'next' device from being
7567          * removed while we are writing to it.
7568          */
7569         if (next != NULL)
7570                 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
7571         mutex_exit(&spa_namespace_lock);
7572
7573         return (next);
7574 }
7575
7576 /*
7577  * Free buffers that were tagged for destruction.
7578  */
7579 static void
7580 l2arc_do_free_on_write()
7581 {
7582         list_t *buflist;
7583         l2arc_data_free_t *df, *df_prev;
7584
7585         mutex_enter(&l2arc_free_on_write_mtx);
7586         buflist = l2arc_free_on_write;
7587
7588         for (df = list_tail(buflist); df; df = df_prev) {
7589                 df_prev = list_prev(buflist, df);
7590                 ASSERT3P(df->l2df_abd, !=, NULL);
7591                 abd_free(df->l2df_abd);
7592                 list_remove(buflist, df);
7593                 kmem_free(df, sizeof (l2arc_data_free_t));
7594         }
7595
7596         mutex_exit(&l2arc_free_on_write_mtx);
7597 }
7598
7599 /*
7600  * A write to a cache device has completed.  Update all headers to allow
7601  * reads from these buffers to begin.
7602  */
7603 static void
7604 l2arc_write_done(zio_t *zio)
7605 {
7606         l2arc_write_callback_t *cb;
7607         l2arc_dev_t *dev;
7608         list_t *buflist;
7609         arc_buf_hdr_t *head, *hdr, *hdr_prev;
7610         kmutex_t *hash_lock;
7611         int64_t bytes_dropped = 0;
7612
7613         cb = zio->io_private;
7614         ASSERT3P(cb, !=, NULL);
7615         dev = cb->l2wcb_dev;
7616         ASSERT3P(dev, !=, NULL);
7617         head = cb->l2wcb_head;
7618         ASSERT3P(head, !=, NULL);
7619         buflist = &dev->l2ad_buflist;
7620         ASSERT3P(buflist, !=, NULL);
7621         DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
7622             l2arc_write_callback_t *, cb);
7623
7624         if (zio->io_error != 0)
7625                 ARCSTAT_BUMP(arcstat_l2_writes_error);
7626
7627         /*
7628          * All writes completed, or an error was hit.
7629          */
7630 top:
7631         mutex_enter(&dev->l2ad_mtx);
7632         for (hdr = list_prev(buflist, head); hdr; hdr = hdr_prev) {
7633                 hdr_prev = list_prev(buflist, hdr);
7634
7635                 hash_lock = HDR_LOCK(hdr);
7636
7637                 /*
7638                  * We cannot use mutex_enter or else we can deadlock
7639                  * with l2arc_write_buffers (due to swapping the order
7640                  * the hash lock and l2ad_mtx are taken).
7641                  */
7642                 if (!mutex_tryenter(hash_lock)) {
7643                         /*
7644                          * Missed the hash lock. We must retry so we
7645                          * don't leave the ARC_FLAG_L2_WRITING bit set.
7646                          */
7647                         ARCSTAT_BUMP(arcstat_l2_writes_lock_retry);
7648
7649                         /*
7650                          * We don't want to rescan the headers we've
7651                          * already marked as having been written out, so
7652                          * we reinsert the head node so we can pick up
7653                          * where we left off.
7654                          */
7655                         list_remove(buflist, head);
7656                         list_insert_after(buflist, hdr, head);
7657
7658                         mutex_exit(&dev->l2ad_mtx);
7659
7660                         /*
7661                          * We wait for the hash lock to become available
7662                          * to try and prevent busy waiting, and increase
7663                          * the chance we'll be able to acquire the lock
7664                          * the next time around.
7665                          */
7666                         mutex_enter(hash_lock);
7667                         mutex_exit(hash_lock);
7668                         goto top;
7669                 }
7670
7671                 /*
7672                  * We could not have been moved into the arc_l2c_only
7673                  * state while in-flight due to our ARC_FLAG_L2_WRITING
7674                  * bit being set. Let's just ensure that's being enforced.
7675                  */
7676                 ASSERT(HDR_HAS_L1HDR(hdr));
7677
7678                 if (zio->io_error != 0) {
7679                         /*
7680                          * Error - drop L2ARC entry.
7681                          */
7682                         list_remove(buflist, hdr);
7683                         l2arc_trim(hdr);
7684                         arc_hdr_clear_flags(hdr, ARC_FLAG_HAS_L2HDR);
7685
7686                         ARCSTAT_INCR(arcstat_l2_psize, -arc_hdr_size(hdr));
7687                         ARCSTAT_INCR(arcstat_l2_lsize, -HDR_GET_LSIZE(hdr));
7688
7689                         bytes_dropped += arc_hdr_size(hdr);
7690                         (void) refcount_remove_many(&dev->l2ad_alloc,
7691                             arc_hdr_size(hdr), hdr);
7692                 }
7693
7694                 /*
7695                  * Allow ARC to begin reads and ghost list evictions to
7696                  * this L2ARC entry.
7697                  */
7698                 arc_hdr_clear_flags(hdr, ARC_FLAG_L2_WRITING);
7699
7700                 mutex_exit(hash_lock);
7701         }
7702
7703         atomic_inc_64(&l2arc_writes_done);
7704         list_remove(buflist, head);
7705         ASSERT(!HDR_HAS_L1HDR(head));
7706         kmem_cache_free(hdr_l2only_cache, head);
7707         mutex_exit(&dev->l2ad_mtx);
7708
7709         vdev_space_update(dev->l2ad_vdev, -bytes_dropped, 0, 0);
7710
7711         l2arc_do_free_on_write();
7712
7713         kmem_free(cb, sizeof (l2arc_write_callback_t));
7714 }
7715
7716 /*
7717  * A read to a cache device completed.  Validate buffer contents before
7718  * handing over to the regular ARC routines.
7719  */
7720 static void
7721 l2arc_read_done(zio_t *zio)
7722 {
7723         l2arc_read_callback_t *cb;
7724         arc_buf_hdr_t *hdr;
7725         kmutex_t *hash_lock;
7726         boolean_t valid_cksum;
7727
7728         ASSERT3P(zio->io_vd, !=, NULL);
7729         ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
7730
7731         spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
7732
7733         cb = zio->io_private;
7734         ASSERT3P(cb, !=, NULL);
7735         hdr = cb->l2rcb_hdr;
7736         ASSERT3P(hdr, !=, NULL);
7737
7738         hash_lock = HDR_LOCK(hdr);
7739         mutex_enter(hash_lock);
7740         ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
7741
7742         /*
7743          * If the data was read into a temporary buffer,
7744          * move it and free the buffer.
7745          */
7746         if (cb->l2rcb_abd != NULL) {
7747                 ASSERT3U(arc_hdr_size(hdr), <, zio->io_size);
7748                 if (zio->io_error == 0) {
7749                         abd_copy(hdr->b_l1hdr.b_pabd, cb->l2rcb_abd,
7750                             arc_hdr_size(hdr));
7751                 }
7752
7753                 /*
7754                  * The following must be done regardless of whether
7755                  * there was an error:
7756                  * - free the temporary buffer
7757                  * - point zio to the real ARC buffer
7758                  * - set zio size accordingly
7759                  * These are required because zio is either re-used for
7760                  * an I/O of the block in the case of the error
7761                  * or the zio is passed to arc_read_done() and it
7762                  * needs real data.
7763                  */
7764                 abd_free(cb->l2rcb_abd);
7765                 zio->io_size = zio->io_orig_size = arc_hdr_size(hdr);
7766                 zio->io_abd = zio->io_orig_abd = hdr->b_l1hdr.b_pabd;
7767         }
7768
7769         ASSERT3P(zio->io_abd, !=, NULL);
7770
7771         /*
7772          * Check this survived the L2ARC journey.
7773          */
7774         ASSERT3P(zio->io_abd, ==, hdr->b_l1hdr.b_pabd);
7775         zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
7776         zio->io_bp = &zio->io_bp_copy;  /* XXX fix in L2ARC 2.0 */
7777
7778         valid_cksum = arc_cksum_is_equal(hdr, zio);
7779         if (valid_cksum && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
7780                 mutex_exit(hash_lock);
7781                 zio->io_private = hdr;
7782                 arc_read_done(zio);
7783         } else {
7784                 mutex_exit(hash_lock);
7785                 /*
7786                  * Buffer didn't survive caching.  Increment stats and
7787                  * reissue to the original storage device.
7788                  */
7789                 if (zio->io_error != 0) {
7790                         ARCSTAT_BUMP(arcstat_l2_io_error);
7791                 } else {
7792                         zio->io_error = SET_ERROR(EIO);
7793                 }
7794                 if (!valid_cksum)
7795                         ARCSTAT_BUMP(arcstat_l2_cksum_bad);
7796
7797                 /*
7798                  * If there's no waiter, issue an async i/o to the primary
7799                  * storage now.  If there *is* a waiter, the caller must
7800                  * issue the i/o in a context where it's OK to block.
7801                  */
7802                 if (zio->io_waiter == NULL) {
7803                         zio_t *pio = zio_unique_parent(zio);
7804
7805                         ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
7806
7807                         zio_nowait(zio_read(pio, zio->io_spa, zio->io_bp,
7808                             hdr->b_l1hdr.b_pabd, zio->io_size, arc_read_done,
7809                             hdr, zio->io_priority, cb->l2rcb_flags,
7810                             &cb->l2rcb_zb));
7811                 }
7812         }
7813
7814         kmem_free(cb, sizeof (l2arc_read_callback_t));
7815 }
7816
7817 /*
7818  * This is the list priority from which the L2ARC will search for pages to
7819  * cache.  This is used within loops (0..3) to cycle through lists in the
7820  * desired order.  This order can have a significant effect on cache
7821  * performance.
7822  *
7823  * Currently the metadata lists are hit first, MFU then MRU, followed by
7824  * the data lists.  This function returns a locked list, and also returns
7825  * the lock pointer.
7826  */
7827 static multilist_sublist_t *
7828 l2arc_sublist_lock(int list_num)
7829 {
7830         multilist_t *ml = NULL;
7831         unsigned int idx;
7832
7833         ASSERT(list_num >= 0 && list_num <= 3);
7834
7835         switch (list_num) {
7836         case 0:
7837                 ml = arc_mfu->arcs_list[ARC_BUFC_METADATA];
7838                 break;
7839         case 1:
7840                 ml = arc_mru->arcs_list[ARC_BUFC_METADATA];
7841                 break;
7842         case 2:
7843                 ml = arc_mfu->arcs_list[ARC_BUFC_DATA];
7844                 break;
7845         case 3:
7846                 ml = arc_mru->arcs_list[ARC_BUFC_DATA];
7847                 break;
7848         }
7849
7850         /*
7851          * Return a randomly-selected sublist. This is acceptable
7852          * because the caller feeds only a little bit of data for each
7853          * call (8MB). Subsequent calls will result in different
7854          * sublists being selected.
7855          */
7856         idx = multilist_get_random_index(ml);
7857         return (multilist_sublist_lock(ml, idx));
7858 }
7859
7860 /*
7861  * Evict buffers from the device write hand to the distance specified in
7862  * bytes.  This distance may span populated buffers, it may span nothing.
7863  * This is clearing a region on the L2ARC device ready for writing.
7864  * If the 'all' boolean is set, every buffer is evicted.
7865  */
7866 static void
7867 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
7868 {
7869         list_t *buflist;
7870         arc_buf_hdr_t *hdr, *hdr_prev;
7871         kmutex_t *hash_lock;
7872         uint64_t taddr;
7873
7874         buflist = &dev->l2ad_buflist;
7875
7876         if (!all && dev->l2ad_first) {
7877                 /*
7878                  * This is the first sweep through the device.  There is
7879                  * nothing to evict.
7880                  */
7881                 return;
7882         }
7883
7884         if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
7885                 /*
7886                  * When nearing the end of the device, evict to the end
7887                  * before the device write hand jumps to the start.
7888                  */
7889                 taddr = dev->l2ad_end;
7890         } else {
7891                 taddr = dev->l2ad_hand + distance;
7892         }
7893         DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
7894             uint64_t, taddr, boolean_t, all);
7895
7896 top:
7897         mutex_enter(&dev->l2ad_mtx);
7898         for (hdr = list_tail(buflist); hdr; hdr = hdr_prev) {
7899                 hdr_prev = list_prev(buflist, hdr);
7900
7901                 hash_lock = HDR_LOCK(hdr);
7902
7903                 /*
7904                  * We cannot use mutex_enter or else we can deadlock
7905                  * with l2arc_write_buffers (due to swapping the order
7906                  * the hash lock and l2ad_mtx are taken).
7907                  */
7908                 if (!mutex_tryenter(hash_lock)) {
7909                         /*
7910                          * Missed the hash lock.  Retry.
7911                          */
7912                         ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
7913                         mutex_exit(&dev->l2ad_mtx);
7914                         mutex_enter(hash_lock);
7915                         mutex_exit(hash_lock);
7916                         goto top;
7917                 }
7918
7919                 /*
7920                  * A header can't be on this list if it doesn't have L2 header.
7921                  */
7922                 ASSERT(HDR_HAS_L2HDR(hdr));
7923
7924                 /* Ensure this header has finished being written. */
7925                 ASSERT(!HDR_L2_WRITING(hdr));
7926                 ASSERT(!HDR_L2_WRITE_HEAD(hdr));
7927
7928                 if (!all && (hdr->b_l2hdr.b_daddr >= taddr ||
7929                     hdr->b_l2hdr.b_daddr < dev->l2ad_hand)) {
7930                         /*
7931                          * We've evicted to the target address,
7932                          * or the end of the device.
7933                          */
7934                         mutex_exit(hash_lock);
7935                         break;
7936                 }
7937
7938                 if (!HDR_HAS_L1HDR(hdr)) {
7939                         ASSERT(!HDR_L2_READING(hdr));
7940                         /*
7941                          * This doesn't exist in the ARC.  Destroy.
7942                          * arc_hdr_destroy() will call list_remove()
7943                          * and decrement arcstat_l2_lsize.
7944                          */
7945                         arc_change_state(arc_anon, hdr, hash_lock);
7946                         arc_hdr_destroy(hdr);
7947                 } else {
7948                         ASSERT(hdr->b_l1hdr.b_state != arc_l2c_only);
7949                         ARCSTAT_BUMP(arcstat_l2_evict_l1cached);
7950                         /*
7951                          * Invalidate issued or about to be issued
7952                          * reads, since we may be about to write
7953                          * over this location.
7954                          */
7955                         if (HDR_L2_READING(hdr)) {
7956                                 ARCSTAT_BUMP(arcstat_l2_evict_reading);
7957                                 arc_hdr_set_flags(hdr, ARC_FLAG_L2_EVICTED);
7958                         }
7959
7960                         arc_hdr_l2hdr_destroy(hdr);
7961                 }
7962                 mutex_exit(hash_lock);
7963         }
7964         mutex_exit(&dev->l2ad_mtx);
7965 }
7966
7967 /*
7968  * Find and write ARC buffers to the L2ARC device.
7969  *
7970  * An ARC_FLAG_L2_WRITING flag is set so that the L2ARC buffers are not valid
7971  * for reading until they have completed writing.
7972  * The headroom_boost is an in-out parameter used to maintain headroom boost
7973  * state between calls to this function.
7974  *
7975  * Returns the number of bytes actually written (which may be smaller than
7976  * the delta by which the device hand has changed due to alignment).
7977  */
7978 static uint64_t
7979 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz)
7980 {
7981         arc_buf_hdr_t *hdr, *hdr_prev, *head;
7982         uint64_t write_asize, write_psize, write_lsize, headroom;
7983         boolean_t full;
7984         l2arc_write_callback_t *cb;
7985         zio_t *pio, *wzio;
7986         uint64_t guid = spa_load_guid(spa);
7987         int try;
7988
7989         ASSERT3P(dev->l2ad_vdev, !=, NULL);
7990
7991         pio = NULL;
7992         write_lsize = write_asize = write_psize = 0;
7993         full = B_FALSE;
7994         head = kmem_cache_alloc(hdr_l2only_cache, KM_PUSHPAGE);
7995         arc_hdr_set_flags(head, ARC_FLAG_L2_WRITE_HEAD | ARC_FLAG_HAS_L2HDR);
7996
7997         ARCSTAT_BUMP(arcstat_l2_write_buffer_iter);
7998         /*
7999          * Copy buffers for L2ARC writing.
8000          */
8001         for (try = 0; try <= 3; try++) {
8002                 multilist_sublist_t *mls = l2arc_sublist_lock(try);
8003                 uint64_t passed_sz = 0;
8004
8005                 ARCSTAT_BUMP(arcstat_l2_write_buffer_list_iter);
8006
8007                 /*
8008                  * L2ARC fast warmup.
8009                  *
8010                  * Until the ARC is warm and starts to evict, read from the
8011                  * head of the ARC lists rather than the tail.
8012                  */
8013                 if (arc_warm == B_FALSE)
8014                         hdr = multilist_sublist_head(mls);
8015                 else
8016                         hdr = multilist_sublist_tail(mls);
8017                 if (hdr == NULL)
8018                         ARCSTAT_BUMP(arcstat_l2_write_buffer_list_null_iter);
8019
8020                 headroom = target_sz * l2arc_headroom;
8021                 if (zfs_compressed_arc_enabled)
8022                         headroom = (headroom * l2arc_headroom_boost) / 100;
8023
8024                 for (; hdr; hdr = hdr_prev) {
8025                         kmutex_t *hash_lock;
8026
8027                         if (arc_warm == B_FALSE)
8028                                 hdr_prev = multilist_sublist_next(mls, hdr);
8029                         else
8030                                 hdr_prev = multilist_sublist_prev(mls, hdr);
8031                         ARCSTAT_INCR(arcstat_l2_write_buffer_bytes_scanned,
8032                             HDR_GET_LSIZE(hdr));
8033
8034                         hash_lock = HDR_LOCK(hdr);
8035                         if (!mutex_tryenter(hash_lock)) {
8036                                 ARCSTAT_BUMP(arcstat_l2_write_trylock_fail);
8037                                 /*
8038                                  * Skip this buffer rather than waiting.
8039                                  */
8040                                 continue;
8041                         }
8042
8043                         passed_sz += HDR_GET_LSIZE(hdr);
8044                         if (passed_sz > headroom) {
8045                                 /*
8046                                  * Searched too far.
8047                                  */
8048                                 mutex_exit(hash_lock);
8049                                 ARCSTAT_BUMP(arcstat_l2_write_passed_headroom);
8050                                 break;
8051                         }
8052
8053                         if (!l2arc_write_eligible(guid, hdr)) {
8054                                 mutex_exit(hash_lock);
8055                                 continue;
8056                         }
8057
8058                         /*
8059                          * We rely on the L1 portion of the header below, so
8060                          * it's invalid for this header to have been evicted out
8061                          * of the ghost cache, prior to being written out. The
8062                          * ARC_FLAG_L2_WRITING bit ensures this won't happen.
8063                          */
8064                         ASSERT(HDR_HAS_L1HDR(hdr));
8065
8066                         ASSERT3U(HDR_GET_PSIZE(hdr), >, 0);
8067                         ASSERT3P(hdr->b_l1hdr.b_pabd, !=, NULL);
8068                         ASSERT3U(arc_hdr_size(hdr), >, 0);
8069                         uint64_t psize = arc_hdr_size(hdr);
8070                         uint64_t asize = vdev_psize_to_asize(dev->l2ad_vdev,
8071                             psize);
8072
8073                         if ((write_asize + asize) > target_sz) {
8074                                 full = B_TRUE;
8075                                 mutex_exit(hash_lock);
8076                                 ARCSTAT_BUMP(arcstat_l2_write_full);
8077                                 break;
8078                         }
8079
8080                         if (pio == NULL) {
8081                                 /*
8082                                  * Insert a dummy header on the buflist so
8083                                  * l2arc_write_done() can find where the
8084                                  * write buffers begin without searching.
8085                                  */
8086                                 mutex_enter(&dev->l2ad_mtx);
8087                                 list_insert_head(&dev->l2ad_buflist, head);
8088                                 mutex_exit(&dev->l2ad_mtx);
8089
8090                                 cb = kmem_alloc(
8091                                     sizeof (l2arc_write_callback_t), KM_SLEEP);
8092                                 cb->l2wcb_dev = dev;
8093                                 cb->l2wcb_head = head;
8094                                 pio = zio_root(spa, l2arc_write_done, cb,
8095                                     ZIO_FLAG_CANFAIL);
8096                                 ARCSTAT_BUMP(arcstat_l2_write_pios);
8097                         }
8098
8099                         hdr->b_l2hdr.b_dev = dev;
8100                         hdr->b_l2hdr.b_daddr = dev->l2ad_hand;
8101                         arc_hdr_set_flags(hdr,
8102                             ARC_FLAG_L2_WRITING | ARC_FLAG_HAS_L2HDR);
8103
8104                         mutex_enter(&dev->l2ad_mtx);
8105                         list_insert_head(&dev->l2ad_buflist, hdr);
8106                         mutex_exit(&dev->l2ad_mtx);
8107
8108                         (void) refcount_add_many(&dev->l2ad_alloc, psize, hdr);
8109
8110                         /*
8111                          * Normally the L2ARC can use the hdr's data, but if
8112                          * we're sharing data between the hdr and one of its
8113                          * bufs, L2ARC needs its own copy of the data so that
8114                          * the ZIO below can't race with the buf consumer.
8115                          * Another case where we need to create a copy of the
8116                          * data is when the buffer size is not device-aligned
8117                          * and we need to pad the block to make it such.
8118                          * That also keeps the clock hand suitably aligned.
8119                          *
8120                          * To ensure that the copy will be available for the
8121                          * lifetime of the ZIO and be cleaned up afterwards, we
8122                          * add it to the l2arc_free_on_write queue.
8123                          */
8124                         abd_t *to_write;
8125                         if (!HDR_SHARED_DATA(hdr) && psize == asize) {
8126                                 to_write = hdr->b_l1hdr.b_pabd;
8127                         } else {
8128                                 to_write = abd_alloc_for_io(asize,
8129                                     HDR_ISTYPE_METADATA(hdr));
8130                                 abd_copy(to_write, hdr->b_l1hdr.b_pabd, psize);
8131                                 if (asize != psize) {
8132                                         abd_zero_off(to_write, psize,
8133                                             asize - psize);
8134                                 }
8135                                 l2arc_free_abd_on_write(to_write, asize,
8136                                     arc_buf_type(hdr));
8137                         }
8138                         wzio = zio_write_phys(pio, dev->l2ad_vdev,
8139                             hdr->b_l2hdr.b_daddr, asize, to_write,
8140                             ZIO_CHECKSUM_OFF, NULL, hdr,
8141                             ZIO_PRIORITY_ASYNC_WRITE,
8142                             ZIO_FLAG_CANFAIL, B_FALSE);
8143
8144                         write_lsize += HDR_GET_LSIZE(hdr);
8145                         DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
8146                             zio_t *, wzio);
8147
8148                         write_psize += psize;
8149                         write_asize += asize;
8150                         dev->l2ad_hand += asize;
8151
8152                         mutex_exit(hash_lock);
8153
8154                         (void) zio_nowait(wzio);
8155                 }
8156
8157                 multilist_sublist_unlock(mls);
8158
8159                 if (full == B_TRUE)
8160                         break;
8161         }
8162
8163         /* No buffers selected for writing? */
8164         if (pio == NULL) {
8165                 ASSERT0(write_lsize);
8166                 ASSERT(!HDR_HAS_L1HDR(head));
8167                 kmem_cache_free(hdr_l2only_cache, head);
8168                 return (0);
8169         }
8170
8171         ASSERT3U(write_psize, <=, target_sz);
8172         ARCSTAT_BUMP(arcstat_l2_writes_sent);
8173         ARCSTAT_INCR(arcstat_l2_write_bytes, write_psize);
8174         ARCSTAT_INCR(arcstat_l2_lsize, write_lsize);
8175         ARCSTAT_INCR(arcstat_l2_psize, write_psize);
8176         vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
8177
8178         /*
8179          * Bump device hand to the device start if it is approaching the end.
8180          * l2arc_evict() will already have evicted ahead for this case.
8181          */
8182         if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
8183                 dev->l2ad_hand = dev->l2ad_start;
8184                 dev->l2ad_first = B_FALSE;
8185         }
8186
8187         dev->l2ad_writing = B_TRUE;
8188         (void) zio_wait(pio);
8189         dev->l2ad_writing = B_FALSE;
8190
8191         return (write_asize);
8192 }
8193
8194 /*
8195  * This thread feeds the L2ARC at regular intervals.  This is the beating
8196  * heart of the L2ARC.
8197  */
8198 /* ARGSUSED */
8199 static void
8200 l2arc_feed_thread(void *unused __unused)
8201 {
8202         callb_cpr_t cpr;
8203         l2arc_dev_t *dev;
8204         spa_t *spa;
8205         uint64_t size, wrote;
8206         clock_t begin, next = ddi_get_lbolt();
8207
8208         CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
8209
8210         mutex_enter(&l2arc_feed_thr_lock);
8211
8212         while (l2arc_thread_exit == 0) {
8213                 CALLB_CPR_SAFE_BEGIN(&cpr);
8214                 (void) cv_timedwait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock,
8215                     next - ddi_get_lbolt());
8216                 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
8217                 next = ddi_get_lbolt() + hz;
8218
8219                 /*
8220                  * Quick check for L2ARC devices.
8221                  */
8222                 mutex_enter(&l2arc_dev_mtx);
8223                 if (l2arc_ndev == 0) {
8224                         mutex_exit(&l2arc_dev_mtx);
8225                         continue;
8226                 }
8227                 mutex_exit(&l2arc_dev_mtx);
8228                 begin = ddi_get_lbolt();
8229
8230                 /*
8231                  * This selects the next l2arc device to write to, and in
8232                  * doing so the next spa to feed from: dev->l2ad_spa.   This
8233                  * will return NULL if there are now no l2arc devices or if
8234                  * they are all faulted.
8235                  *
8236                  * If a device is returned, its spa's config lock is also
8237                  * held to prevent device removal.  l2arc_dev_get_next()
8238                  * will grab and release l2arc_dev_mtx.
8239                  */
8240                 if ((dev = l2arc_dev_get_next()) == NULL)
8241                         continue;
8242
8243                 spa = dev->l2ad_spa;
8244                 ASSERT3P(spa, !=, NULL);
8245
8246                 /*
8247                  * If the pool is read-only then force the feed thread to
8248                  * sleep a little longer.
8249                  */
8250                 if (!spa_writeable(spa)) {
8251                         next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
8252                         spa_config_exit(spa, SCL_L2ARC, dev);
8253                         continue;
8254                 }
8255
8256                 /*
8257                  * Avoid contributing to memory pressure.
8258                  */
8259                 if (arc_reclaim_needed()) {
8260                         ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
8261                         spa_config_exit(spa, SCL_L2ARC, dev);
8262                         continue;
8263                 }
8264
8265                 ARCSTAT_BUMP(arcstat_l2_feeds);
8266
8267                 size = l2arc_write_size();
8268
8269                 /*
8270                  * Evict L2ARC buffers that will be overwritten.
8271                  */
8272                 l2arc_evict(dev, size, B_FALSE);
8273
8274                 /*
8275                  * Write ARC buffers.
8276                  */
8277                 wrote = l2arc_write_buffers(spa, dev, size);
8278
8279                 /*
8280                  * Calculate interval between writes.
8281                  */
8282                 next = l2arc_write_interval(begin, size, wrote);
8283                 spa_config_exit(spa, SCL_L2ARC, dev);
8284         }
8285
8286         l2arc_thread_exit = 0;
8287         cv_broadcast(&l2arc_feed_thr_cv);
8288         CALLB_CPR_EXIT(&cpr);           /* drops l2arc_feed_thr_lock */
8289         thread_exit();
8290 }
8291
8292 boolean_t
8293 l2arc_vdev_present(vdev_t *vd)
8294 {
8295         l2arc_dev_t *dev;
8296
8297         mutex_enter(&l2arc_dev_mtx);
8298         for (dev = list_head(l2arc_dev_list); dev != NULL;
8299             dev = list_next(l2arc_dev_list, dev)) {
8300                 if (dev->l2ad_vdev == vd)
8301                         break;
8302         }
8303         mutex_exit(&l2arc_dev_mtx);
8304
8305         return (dev != NULL);
8306 }
8307
8308 /*
8309  * Add a vdev for use by the L2ARC.  By this point the spa has already
8310  * validated the vdev and opened it.
8311  */
8312 void
8313 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
8314 {
8315         l2arc_dev_t *adddev;
8316
8317         ASSERT(!l2arc_vdev_present(vd));
8318
8319         vdev_ashift_optimize(vd);
8320
8321         /*
8322          * Create a new l2arc device entry.
8323          */
8324         adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
8325         adddev->l2ad_spa = spa;
8326         adddev->l2ad_vdev = vd;
8327         adddev->l2ad_start = VDEV_LABEL_START_SIZE;
8328         adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
8329         adddev->l2ad_hand = adddev->l2ad_start;
8330         adddev->l2ad_first = B_TRUE;
8331         adddev->l2ad_writing = B_FALSE;
8332
8333         mutex_init(&adddev->l2ad_mtx, NULL, MUTEX_DEFAULT, NULL);
8334         /*
8335          * This is a list of all ARC buffers that are still valid on the
8336          * device.
8337          */
8338         list_create(&adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
8339             offsetof(arc_buf_hdr_t, b_l2hdr.b_l2node));
8340
8341         vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
8342         refcount_create(&adddev->l2ad_alloc);
8343
8344         /*
8345          * Add device to global list
8346          */
8347         mutex_enter(&l2arc_dev_mtx);
8348         list_insert_head(l2arc_dev_list, adddev);
8349         atomic_inc_64(&l2arc_ndev);
8350         mutex_exit(&l2arc_dev_mtx);
8351 }
8352
8353 /*
8354  * Remove a vdev from the L2ARC.
8355  */
8356 void
8357 l2arc_remove_vdev(vdev_t *vd)
8358 {
8359         l2arc_dev_t *dev, *nextdev, *remdev = NULL;
8360
8361         /*
8362          * Find the device by vdev
8363          */
8364         mutex_enter(&l2arc_dev_mtx);
8365         for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
8366                 nextdev = list_next(l2arc_dev_list, dev);
8367                 if (vd == dev->l2ad_vdev) {
8368                         remdev = dev;
8369                         break;
8370                 }
8371         }
8372         ASSERT3P(remdev, !=, NULL);
8373
8374         /*
8375          * Remove device from global list
8376          */
8377         list_remove(l2arc_dev_list, remdev);
8378         l2arc_dev_last = NULL;          /* may have been invalidated */
8379         atomic_dec_64(&l2arc_ndev);
8380         mutex_exit(&l2arc_dev_mtx);
8381
8382         /*
8383          * Clear all buflists and ARC references.  L2ARC device flush.
8384          */
8385         l2arc_evict(remdev, 0, B_TRUE);
8386         list_destroy(&remdev->l2ad_buflist);
8387         mutex_destroy(&remdev->l2ad_mtx);
8388         refcount_destroy(&remdev->l2ad_alloc);
8389         kmem_free(remdev, sizeof (l2arc_dev_t));
8390 }
8391
8392 void
8393 l2arc_init(void)
8394 {
8395         l2arc_thread_exit = 0;
8396         l2arc_ndev = 0;
8397         l2arc_writes_sent = 0;
8398         l2arc_writes_done = 0;
8399
8400         mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
8401         cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
8402         mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
8403         mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
8404
8405         l2arc_dev_list = &L2ARC_dev_list;
8406         l2arc_free_on_write = &L2ARC_free_on_write;
8407         list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
8408             offsetof(l2arc_dev_t, l2ad_node));
8409         list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
8410             offsetof(l2arc_data_free_t, l2df_list_node));
8411 }
8412
8413 void
8414 l2arc_fini(void)
8415 {
8416         /*
8417          * This is called from dmu_fini(), which is called from spa_fini();
8418          * Because of this, we can assume that all l2arc devices have
8419          * already been removed when the pools themselves were removed.
8420          */
8421
8422         l2arc_do_free_on_write();
8423
8424         mutex_destroy(&l2arc_feed_thr_lock);
8425         cv_destroy(&l2arc_feed_thr_cv);
8426         mutex_destroy(&l2arc_dev_mtx);
8427         mutex_destroy(&l2arc_free_on_write_mtx);
8428
8429         list_destroy(l2arc_dev_list);
8430         list_destroy(l2arc_free_on_write);
8431 }
8432
8433 void
8434 l2arc_start(void)
8435 {
8436         if (!(spa_mode_global & FWRITE))
8437                 return;
8438
8439         (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
8440             TS_RUN, minclsyspri);
8441 }
8442
8443 void
8444 l2arc_stop(void)
8445 {
8446         if (!(spa_mode_global & FWRITE))
8447                 return;
8448
8449         mutex_enter(&l2arc_feed_thr_lock);
8450         cv_signal(&l2arc_feed_thr_cv);  /* kick thread out of startup */
8451         l2arc_thread_exit = 1;
8452         while (l2arc_thread_exit != 0)
8453                 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
8454         mutex_exit(&l2arc_feed_thr_lock);
8455 }