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