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