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