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