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