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