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