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