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