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