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