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