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