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