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