]> git.proxmox.com Git - mirror_zfs.git/blob - module/zfs/arc.c
cstyle: Resolve C style issues
[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 2011 Nexenta Systems, Inc. All rights reserved.
24 * Copyright (c) 2013 by Delphix. All rights reserved.
25 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26 */
27
28 /*
29 * DVA-based Adjustable Replacement Cache
30 *
31 * While much of the theory of operation used here is
32 * based on the self-tuning, low overhead replacement cache
33 * presented by Megiddo and Modha at FAST 2003, there are some
34 * significant differences:
35 *
36 * 1. The Megiddo and Modha model assumes any page is evictable.
37 * Pages in its cache cannot be "locked" into memory. This makes
38 * the eviction algorithm simple: evict the last page in the list.
39 * This also make the performance characteristics easy to reason
40 * about. Our cache is not so simple. At any given moment, some
41 * subset of the blocks in the cache are un-evictable because we
42 * have handed out a reference to them. Blocks are only evictable
43 * when there are no external references active. This makes
44 * eviction far more problematic: we choose to evict the evictable
45 * blocks that are the "lowest" in the list.
46 *
47 * There are times when it is not possible to evict the requested
48 * space. In these circumstances we are unable to adjust the cache
49 * size. To prevent the cache growing unbounded at these times we
50 * implement a "cache throttle" that slows the flow of new data
51 * into the cache until we can make space available.
52 *
53 * 2. The Megiddo and Modha model assumes a fixed cache size.
54 * Pages are evicted when the cache is full and there is a cache
55 * miss. Our model has a variable sized cache. It grows with
56 * high use, but also tries to react to memory pressure from the
57 * operating system: decreasing its size when system memory is
58 * tight.
59 *
60 * 3. The Megiddo and Modha model assumes a fixed page size. All
61 * elements of the cache are therefore exactly the same size. So
62 * when adjusting the cache size following a cache miss, its simply
63 * a matter of choosing a single page to evict. In our model, we
64 * have variable sized cache blocks (rangeing from 512 bytes to
65 * 128K bytes). We therefore choose a set of blocks to evict to make
66 * space for a cache miss that approximates as closely as possible
67 * the space used by the new block.
68 *
69 * See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
70 * by N. Megiddo & D. Modha, FAST 2003
71 */
72
73 /*
74 * The locking model:
75 *
76 * A new reference to a cache buffer can be obtained in two
77 * ways: 1) via a hash table lookup using the DVA as a key,
78 * or 2) via one of the ARC lists. The arc_read() interface
79 * uses method 1, while the internal arc algorithms for
80 * adjusting the cache use method 2. We therefore provide two
81 * types of locks: 1) the hash table lock array, and 2) the
82 * arc list locks.
83 *
84 * Buffers do not have their own mutexes, rather they rely on the
85 * hash table mutexes for the bulk of their protection (i.e. most
86 * fields in the arc_buf_hdr_t are protected by these mutexes).
87 *
88 * buf_hash_find() returns the appropriate mutex (held) when it
89 * locates the requested buffer in the hash table. It returns
90 * NULL for the mutex if the buffer was not in the table.
91 *
92 * buf_hash_remove() expects the appropriate hash mutex to be
93 * already held before it is invoked.
94 *
95 * Each arc state also has a mutex which is used to protect the
96 * buffer list associated with the state. When attempting to
97 * obtain a hash table lock while holding an arc list lock you
98 * must use: mutex_tryenter() to avoid deadlock. Also note that
99 * the active state mutex must be held before the ghost state mutex.
100 *
101 * Arc buffers may have an associated eviction callback function.
102 * This function will be invoked prior to removing the buffer (e.g.
103 * in arc_do_user_evicts()). Note however that the data associated
104 * with the buffer may be evicted prior to the callback. The callback
105 * must be made with *no locks held* (to prevent deadlock). Additionally,
106 * the users of callbacks must ensure that their private data is
107 * protected from simultaneous callbacks from arc_buf_evict()
108 * and arc_do_user_evicts().
109 *
110 * It as also possible to register a callback which is run when the
111 * arc_meta_limit is reached and no buffers can be safely evicted. In
112 * this case the arc user should drop a reference on some arc buffers so
113 * they can be reclaimed and the arc_meta_limit honored. For example,
114 * when using the ZPL each dentry holds a references on a znode. These
115 * dentries must be pruned before the arc buffer holding the znode can
116 * be safely evicted.
117 *
118 * Note that the majority of the performance stats are manipulated
119 * with atomic operations.
120 *
121 * The L2ARC uses the l2arc_buflist_mtx global mutex for the following:
122 *
123 * - L2ARC buflist creation
124 * - L2ARC buflist eviction
125 * - L2ARC write completion, which walks L2ARC buflists
126 * - ARC header destruction, as it removes from L2ARC buflists
127 * - ARC header release, as it removes from L2ARC buflists
128 */
129
130 #include <sys/spa.h>
131 #include <sys/zio.h>
132 #include <sys/zio_compress.h>
133 #include <sys/zfs_context.h>
134 #include <sys/arc.h>
135 #include <sys/vdev.h>
136 #include <sys/vdev_impl.h>
137 #include <sys/dsl_pool.h>
138 #ifdef _KERNEL
139 #include <sys/vmsystm.h>
140 #include <vm/anon.h>
141 #include <sys/fs/swapnode.h>
142 #include <sys/zpl.h>
143 #endif
144 #include <sys/callb.h>
145 #include <sys/kstat.h>
146 #include <sys/dmu_tx.h>
147 #include <zfs_fletcher.h>
148
149 #ifndef _KERNEL
150 /* set with ZFS_DEBUG=watch, to enable watchpoints on frozen buffers */
151 boolean_t arc_watch = B_FALSE;
152 #endif
153
154 static kmutex_t arc_reclaim_thr_lock;
155 static kcondvar_t arc_reclaim_thr_cv; /* used to signal reclaim thr */
156 static uint8_t arc_thread_exit;
157
158 /* number of bytes to prune from caches when at arc_meta_limit is reached */
159 int zfs_arc_meta_prune = 1048576;
160
161 typedef enum arc_reclaim_strategy {
162 ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
163 ARC_RECLAIM_CONS /* Conservative reclaim strategy */
164 } arc_reclaim_strategy_t;
165
166 /*
167 * The number of iterations through arc_evict_*() before we
168 * drop & reacquire the lock.
169 */
170 int arc_evict_iterations = 100;
171
172 /* number of seconds before growing cache again */
173 int zfs_arc_grow_retry = 5;
174
175 /* shift of arc_c for calculating both min and max arc_p */
176 int zfs_arc_p_min_shift = 4;
177
178 /* log2(fraction of arc to reclaim) */
179 int zfs_arc_shrink_shift = 5;
180
181 /*
182 * minimum lifespan of a prefetch block in clock ticks
183 * (initialized in arc_init())
184 */
185 int zfs_arc_min_prefetch_lifespan = HZ;
186
187 /* disable arc proactive arc throttle due to low memory */
188 int zfs_arc_memory_throttle_disable = 1;
189
190 /* disable duplicate buffer eviction */
191 int zfs_disable_dup_eviction = 0;
192
193 /*
194 * If this percent of memory is free, don't throttle.
195 */
196 int arc_lotsfree_percent = 10;
197
198 static int arc_dead;
199
200 /* expiration time for arc_no_grow */
201 static clock_t arc_grow_time = 0;
202
203 /*
204 * The arc has filled available memory and has now warmed up.
205 */
206 static boolean_t arc_warm;
207
208 /*
209 * These tunables are for performance analysis.
210 */
211 unsigned long zfs_arc_max = 0;
212 unsigned long zfs_arc_min = 0;
213 unsigned long zfs_arc_meta_limit = 0;
214
215 /*
216 * Note that buffers can be in one of 6 states:
217 * ARC_anon - anonymous (discussed below)
218 * ARC_mru - recently used, currently cached
219 * ARC_mru_ghost - recentely used, no longer in cache
220 * ARC_mfu - frequently used, currently cached
221 * ARC_mfu_ghost - frequently used, no longer in cache
222 * ARC_l2c_only - exists in L2ARC but not other states
223 * When there are no active references to the buffer, they are
224 * are linked onto a list in one of these arc states. These are
225 * the only buffers that can be evicted or deleted. Within each
226 * state there are multiple lists, one for meta-data and one for
227 * non-meta-data. Meta-data (indirect blocks, blocks of dnodes,
228 * etc.) is tracked separately so that it can be managed more
229 * explicitly: favored over data, limited explicitly.
230 *
231 * Anonymous buffers are buffers that are not associated with
232 * a DVA. These are buffers that hold dirty block copies
233 * before they are written to stable storage. By definition,
234 * they are "ref'd" and are considered part of arc_mru
235 * that cannot be freed. Generally, they will aquire a DVA
236 * as they are written and migrate onto the arc_mru list.
237 *
238 * The ARC_l2c_only state is for buffers that are in the second
239 * level ARC but no longer in any of the ARC_m* lists. The second
240 * level ARC itself may also contain buffers that are in any of
241 * the ARC_m* states - meaning that a buffer can exist in two
242 * places. The reason for the ARC_l2c_only state is to keep the
243 * buffer header in the hash table, so that reads that hit the
244 * second level ARC benefit from these fast lookups.
245 */
246
247 typedef struct arc_state {
248 list_t arcs_list[ARC_BUFC_NUMTYPES]; /* list of evictable buffers */
249 uint64_t arcs_lsize[ARC_BUFC_NUMTYPES]; /* amount of evictable data */
250 uint64_t arcs_size; /* total amount of data in this state */
251 kmutex_t arcs_mtx;
252 arc_state_type_t arcs_state;
253 } arc_state_t;
254
255 /* The 6 states: */
256 static arc_state_t ARC_anon;
257 static arc_state_t ARC_mru;
258 static arc_state_t ARC_mru_ghost;
259 static arc_state_t ARC_mfu;
260 static arc_state_t ARC_mfu_ghost;
261 static arc_state_t ARC_l2c_only;
262
263 typedef struct arc_stats {
264 kstat_named_t arcstat_hits;
265 kstat_named_t arcstat_misses;
266 kstat_named_t arcstat_demand_data_hits;
267 kstat_named_t arcstat_demand_data_misses;
268 kstat_named_t arcstat_demand_metadata_hits;
269 kstat_named_t arcstat_demand_metadata_misses;
270 kstat_named_t arcstat_prefetch_data_hits;
271 kstat_named_t arcstat_prefetch_data_misses;
272 kstat_named_t arcstat_prefetch_metadata_hits;
273 kstat_named_t arcstat_prefetch_metadata_misses;
274 kstat_named_t arcstat_mru_hits;
275 kstat_named_t arcstat_mru_ghost_hits;
276 kstat_named_t arcstat_mfu_hits;
277 kstat_named_t arcstat_mfu_ghost_hits;
278 kstat_named_t arcstat_deleted;
279 kstat_named_t arcstat_recycle_miss;
280 /*
281 * Number of buffers that could not be evicted because the hash lock
282 * was held by another thread. The lock may not necessarily be held
283 * by something using the same buffer, since hash locks are shared
284 * by multiple buffers.
285 */
286 kstat_named_t arcstat_mutex_miss;
287 /*
288 * Number of buffers skipped because they have I/O in progress, are
289 * indrect prefetch buffers that have not lived long enough, or are
290 * not from the spa we're trying to evict from.
291 */
292 kstat_named_t arcstat_evict_skip;
293 kstat_named_t arcstat_evict_l2_cached;
294 kstat_named_t arcstat_evict_l2_eligible;
295 kstat_named_t arcstat_evict_l2_ineligible;
296 kstat_named_t arcstat_hash_elements;
297 kstat_named_t arcstat_hash_elements_max;
298 kstat_named_t arcstat_hash_collisions;
299 kstat_named_t arcstat_hash_chains;
300 kstat_named_t arcstat_hash_chain_max;
301 kstat_named_t arcstat_p;
302 kstat_named_t arcstat_c;
303 kstat_named_t arcstat_c_min;
304 kstat_named_t arcstat_c_max;
305 kstat_named_t arcstat_size;
306 kstat_named_t arcstat_hdr_size;
307 kstat_named_t arcstat_data_size;
308 kstat_named_t arcstat_other_size;
309 kstat_named_t arcstat_anon_size;
310 kstat_named_t arcstat_anon_evict_data;
311 kstat_named_t arcstat_anon_evict_metadata;
312 kstat_named_t arcstat_mru_size;
313 kstat_named_t arcstat_mru_evict_data;
314 kstat_named_t arcstat_mru_evict_metadata;
315 kstat_named_t arcstat_mru_ghost_size;
316 kstat_named_t arcstat_mru_ghost_evict_data;
317 kstat_named_t arcstat_mru_ghost_evict_metadata;
318 kstat_named_t arcstat_mfu_size;
319 kstat_named_t arcstat_mfu_evict_data;
320 kstat_named_t arcstat_mfu_evict_metadata;
321 kstat_named_t arcstat_mfu_ghost_size;
322 kstat_named_t arcstat_mfu_ghost_evict_data;
323 kstat_named_t arcstat_mfu_ghost_evict_metadata;
324 kstat_named_t arcstat_l2_hits;
325 kstat_named_t arcstat_l2_misses;
326 kstat_named_t arcstat_l2_feeds;
327 kstat_named_t arcstat_l2_rw_clash;
328 kstat_named_t arcstat_l2_read_bytes;
329 kstat_named_t arcstat_l2_write_bytes;
330 kstat_named_t arcstat_l2_writes_sent;
331 kstat_named_t arcstat_l2_writes_done;
332 kstat_named_t arcstat_l2_writes_error;
333 kstat_named_t arcstat_l2_writes_hdr_miss;
334 kstat_named_t arcstat_l2_evict_lock_retry;
335 kstat_named_t arcstat_l2_evict_reading;
336 kstat_named_t arcstat_l2_free_on_write;
337 kstat_named_t arcstat_l2_abort_lowmem;
338 kstat_named_t arcstat_l2_cksum_bad;
339 kstat_named_t arcstat_l2_io_error;
340 kstat_named_t arcstat_l2_size;
341 kstat_named_t arcstat_l2_asize;
342 kstat_named_t arcstat_l2_hdr_size;
343 kstat_named_t arcstat_l2_compress_successes;
344 kstat_named_t arcstat_l2_compress_zeros;
345 kstat_named_t arcstat_l2_compress_failures;
346 kstat_named_t arcstat_memory_throttle_count;
347 kstat_named_t arcstat_duplicate_buffers;
348 kstat_named_t arcstat_duplicate_buffers_size;
349 kstat_named_t arcstat_duplicate_reads;
350 kstat_named_t arcstat_memory_direct_count;
351 kstat_named_t arcstat_memory_indirect_count;
352 kstat_named_t arcstat_no_grow;
353 kstat_named_t arcstat_tempreserve;
354 kstat_named_t arcstat_loaned_bytes;
355 kstat_named_t arcstat_prune;
356 kstat_named_t arcstat_meta_used;
357 kstat_named_t arcstat_meta_limit;
358 kstat_named_t arcstat_meta_max;
359 } arc_stats_t;
360
361 static arc_stats_t arc_stats = {
362 { "hits", KSTAT_DATA_UINT64 },
363 { "misses", KSTAT_DATA_UINT64 },
364 { "demand_data_hits", KSTAT_DATA_UINT64 },
365 { "demand_data_misses", KSTAT_DATA_UINT64 },
366 { "demand_metadata_hits", KSTAT_DATA_UINT64 },
367 { "demand_metadata_misses", KSTAT_DATA_UINT64 },
368 { "prefetch_data_hits", KSTAT_DATA_UINT64 },
369 { "prefetch_data_misses", KSTAT_DATA_UINT64 },
370 { "prefetch_metadata_hits", KSTAT_DATA_UINT64 },
371 { "prefetch_metadata_misses", KSTAT_DATA_UINT64 },
372 { "mru_hits", KSTAT_DATA_UINT64 },
373 { "mru_ghost_hits", KSTAT_DATA_UINT64 },
374 { "mfu_hits", KSTAT_DATA_UINT64 },
375 { "mfu_ghost_hits", KSTAT_DATA_UINT64 },
376 { "deleted", KSTAT_DATA_UINT64 },
377 { "recycle_miss", KSTAT_DATA_UINT64 },
378 { "mutex_miss", KSTAT_DATA_UINT64 },
379 { "evict_skip", KSTAT_DATA_UINT64 },
380 { "evict_l2_cached", KSTAT_DATA_UINT64 },
381 { "evict_l2_eligible", KSTAT_DATA_UINT64 },
382 { "evict_l2_ineligible", KSTAT_DATA_UINT64 },
383 { "hash_elements", KSTAT_DATA_UINT64 },
384 { "hash_elements_max", KSTAT_DATA_UINT64 },
385 { "hash_collisions", KSTAT_DATA_UINT64 },
386 { "hash_chains", KSTAT_DATA_UINT64 },
387 { "hash_chain_max", KSTAT_DATA_UINT64 },
388 { "p", KSTAT_DATA_UINT64 },
389 { "c", KSTAT_DATA_UINT64 },
390 { "c_min", KSTAT_DATA_UINT64 },
391 { "c_max", KSTAT_DATA_UINT64 },
392 { "size", KSTAT_DATA_UINT64 },
393 { "hdr_size", KSTAT_DATA_UINT64 },
394 { "data_size", KSTAT_DATA_UINT64 },
395 { "other_size", KSTAT_DATA_UINT64 },
396 { "anon_size", KSTAT_DATA_UINT64 },
397 { "anon_evict_data", KSTAT_DATA_UINT64 },
398 { "anon_evict_metadata", KSTAT_DATA_UINT64 },
399 { "mru_size", KSTAT_DATA_UINT64 },
400 { "mru_evict_data", KSTAT_DATA_UINT64 },
401 { "mru_evict_metadata", KSTAT_DATA_UINT64 },
402 { "mru_ghost_size", KSTAT_DATA_UINT64 },
403 { "mru_ghost_evict_data", KSTAT_DATA_UINT64 },
404 { "mru_ghost_evict_metadata", KSTAT_DATA_UINT64 },
405 { "mfu_size", KSTAT_DATA_UINT64 },
406 { "mfu_evict_data", KSTAT_DATA_UINT64 },
407 { "mfu_evict_metadata", KSTAT_DATA_UINT64 },
408 { "mfu_ghost_size", KSTAT_DATA_UINT64 },
409 { "mfu_ghost_evict_data", KSTAT_DATA_UINT64 },
410 { "mfu_ghost_evict_metadata", KSTAT_DATA_UINT64 },
411 { "l2_hits", KSTAT_DATA_UINT64 },
412 { "l2_misses", KSTAT_DATA_UINT64 },
413 { "l2_feeds", KSTAT_DATA_UINT64 },
414 { "l2_rw_clash", KSTAT_DATA_UINT64 },
415 { "l2_read_bytes", KSTAT_DATA_UINT64 },
416 { "l2_write_bytes", KSTAT_DATA_UINT64 },
417 { "l2_writes_sent", KSTAT_DATA_UINT64 },
418 { "l2_writes_done", KSTAT_DATA_UINT64 },
419 { "l2_writes_error", KSTAT_DATA_UINT64 },
420 { "l2_writes_hdr_miss", KSTAT_DATA_UINT64 },
421 { "l2_evict_lock_retry", KSTAT_DATA_UINT64 },
422 { "l2_evict_reading", KSTAT_DATA_UINT64 },
423 { "l2_free_on_write", KSTAT_DATA_UINT64 },
424 { "l2_abort_lowmem", KSTAT_DATA_UINT64 },
425 { "l2_cksum_bad", KSTAT_DATA_UINT64 },
426 { "l2_io_error", KSTAT_DATA_UINT64 },
427 { "l2_size", KSTAT_DATA_UINT64 },
428 { "l2_asize", KSTAT_DATA_UINT64 },
429 { "l2_hdr_size", KSTAT_DATA_UINT64 },
430 { "l2_compress_successes", KSTAT_DATA_UINT64 },
431 { "l2_compress_zeros", KSTAT_DATA_UINT64 },
432 { "l2_compress_failures", KSTAT_DATA_UINT64 },
433 { "memory_throttle_count", KSTAT_DATA_UINT64 },
434 { "duplicate_buffers", KSTAT_DATA_UINT64 },
435 { "duplicate_buffers_size", KSTAT_DATA_UINT64 },
436 { "duplicate_reads", KSTAT_DATA_UINT64 },
437 { "memory_direct_count", KSTAT_DATA_UINT64 },
438 { "memory_indirect_count", KSTAT_DATA_UINT64 },
439 { "arc_no_grow", KSTAT_DATA_UINT64 },
440 { "arc_tempreserve", KSTAT_DATA_UINT64 },
441 { "arc_loaned_bytes", KSTAT_DATA_UINT64 },
442 { "arc_prune", KSTAT_DATA_UINT64 },
443 { "arc_meta_used", KSTAT_DATA_UINT64 },
444 { "arc_meta_limit", KSTAT_DATA_UINT64 },
445 { "arc_meta_max", KSTAT_DATA_UINT64 },
446 };
447
448 #define ARCSTAT(stat) (arc_stats.stat.value.ui64)
449
450 #define ARCSTAT_INCR(stat, val) \
451 atomic_add_64(&arc_stats.stat.value.ui64, (val))
452
453 #define ARCSTAT_BUMP(stat) ARCSTAT_INCR(stat, 1)
454 #define ARCSTAT_BUMPDOWN(stat) ARCSTAT_INCR(stat, -1)
455
456 #define ARCSTAT_MAX(stat, val) { \
457 uint64_t m; \
458 while ((val) > (m = arc_stats.stat.value.ui64) && \
459 (m != atomic_cas_64(&arc_stats.stat.value.ui64, m, (val)))) \
460 continue; \
461 }
462
463 #define ARCSTAT_MAXSTAT(stat) \
464 ARCSTAT_MAX(stat##_max, arc_stats.stat.value.ui64)
465
466 /*
467 * We define a macro to allow ARC hits/misses to be easily broken down by
468 * two separate conditions, giving a total of four different subtypes for
469 * each of hits and misses (so eight statistics total).
470 */
471 #define ARCSTAT_CONDSTAT(cond1, stat1, notstat1, cond2, stat2, notstat2, stat) \
472 if (cond1) { \
473 if (cond2) { \
474 ARCSTAT_BUMP(arcstat_##stat1##_##stat2##_##stat); \
475 } else { \
476 ARCSTAT_BUMP(arcstat_##stat1##_##notstat2##_##stat); \
477 } \
478 } else { \
479 if (cond2) { \
480 ARCSTAT_BUMP(arcstat_##notstat1##_##stat2##_##stat); \
481 } else { \
482 ARCSTAT_BUMP(arcstat_##notstat1##_##notstat2##_##stat);\
483 } \
484 }
485
486 kstat_t *arc_ksp;
487 static arc_state_t *arc_anon;
488 static arc_state_t *arc_mru;
489 static arc_state_t *arc_mru_ghost;
490 static arc_state_t *arc_mfu;
491 static arc_state_t *arc_mfu_ghost;
492 static arc_state_t *arc_l2c_only;
493
494 /*
495 * There are several ARC variables that are critical to export as kstats --
496 * but we don't want to have to grovel around in the kstat whenever we wish to
497 * manipulate them. For these variables, we therefore define them to be in
498 * terms of the statistic variable. This assures that we are not introducing
499 * the possibility of inconsistency by having shadow copies of the variables,
500 * while still allowing the code to be readable.
501 */
502 #define arc_size ARCSTAT(arcstat_size) /* actual total arc size */
503 #define arc_p ARCSTAT(arcstat_p) /* target size of MRU */
504 #define arc_c ARCSTAT(arcstat_c) /* target size of cache */
505 #define arc_c_min ARCSTAT(arcstat_c_min) /* min target cache size */
506 #define arc_c_max ARCSTAT(arcstat_c_max) /* max target cache size */
507 #define arc_no_grow ARCSTAT(arcstat_no_grow)
508 #define arc_tempreserve ARCSTAT(arcstat_tempreserve)
509 #define arc_loaned_bytes ARCSTAT(arcstat_loaned_bytes)
510 #define arc_meta_limit ARCSTAT(arcstat_meta_limit) /* max size for metadata */
511 #define arc_meta_used ARCSTAT(arcstat_meta_used) /* size of metadata */
512 #define arc_meta_max ARCSTAT(arcstat_meta_max) /* max size of metadata */
513
514 #define L2ARC_IS_VALID_COMPRESS(_c_) \
515 ((_c_) == ZIO_COMPRESS_LZ4 || (_c_) == ZIO_COMPRESS_EMPTY)
516
517 typedef struct l2arc_buf_hdr l2arc_buf_hdr_t;
518
519 typedef struct arc_callback arc_callback_t;
520
521 struct arc_callback {
522 void *acb_private;
523 arc_done_func_t *acb_done;
524 arc_buf_t *acb_buf;
525 zio_t *acb_zio_dummy;
526 arc_callback_t *acb_next;
527 };
528
529 typedef struct arc_write_callback arc_write_callback_t;
530
531 struct arc_write_callback {
532 void *awcb_private;
533 arc_done_func_t *awcb_ready;
534 arc_done_func_t *awcb_physdone;
535 arc_done_func_t *awcb_done;
536 arc_buf_t *awcb_buf;
537 };
538
539 struct arc_buf_hdr {
540 /* protected by hash lock */
541 dva_t b_dva;
542 uint64_t b_birth;
543 uint64_t b_cksum0;
544
545 kmutex_t b_freeze_lock;
546 zio_cksum_t *b_freeze_cksum;
547
548 arc_buf_hdr_t *b_hash_next;
549 arc_buf_t *b_buf;
550 uint32_t b_flags;
551 uint32_t b_datacnt;
552
553 arc_callback_t *b_acb;
554 kcondvar_t b_cv;
555
556 /* immutable */
557 arc_buf_contents_t b_type;
558 uint64_t b_size;
559 uint64_t b_spa;
560
561 /* protected by arc state mutex */
562 arc_state_t *b_state;
563 list_node_t b_arc_node;
564
565 /* updated atomically */
566 clock_t b_arc_access;
567 uint32_t b_mru_hits;
568 uint32_t b_mru_ghost_hits;
569 uint32_t b_mfu_hits;
570 uint32_t b_mfu_ghost_hits;
571 uint32_t b_l2_hits;
572
573 /* self protecting */
574 refcount_t b_refcnt;
575
576 l2arc_buf_hdr_t *b_l2hdr;
577 list_node_t b_l2node;
578 };
579
580 static list_t arc_prune_list;
581 static kmutex_t arc_prune_mtx;
582 static arc_buf_t *arc_eviction_list;
583 static kmutex_t arc_eviction_mtx;
584 static arc_buf_hdr_t arc_eviction_hdr;
585 static void arc_get_data_buf(arc_buf_t *buf);
586 static void arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock);
587 static int arc_evict_needed(arc_buf_contents_t type);
588 static void arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes,
589 arc_buf_contents_t type);
590 static void arc_buf_watch(arc_buf_t *buf);
591
592 static boolean_t l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab);
593
594 #define GHOST_STATE(state) \
595 ((state) == arc_mru_ghost || (state) == arc_mfu_ghost || \
596 (state) == arc_l2c_only)
597
598 /*
599 * Private ARC flags. These flags are private ARC only flags that will show up
600 * in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
601 * be passed in as arc_flags in things like arc_read. However, these flags
602 * should never be passed and should only be set by ARC code. When adding new
603 * public flags, make sure not to smash the private ones.
604 */
605
606 #define ARC_IN_HASH_TABLE (1 << 9) /* this buffer is hashed */
607 #define ARC_IO_IN_PROGRESS (1 << 10) /* I/O in progress for buf */
608 #define ARC_IO_ERROR (1 << 11) /* I/O failed for buf */
609 #define ARC_FREED_IN_READ (1 << 12) /* buf freed while in read */
610 #define ARC_BUF_AVAILABLE (1 << 13) /* block not in active use */
611 #define ARC_INDIRECT (1 << 14) /* this is an indirect block */
612 #define ARC_FREE_IN_PROGRESS (1 << 15) /* hdr about to be freed */
613 #define ARC_L2_WRITING (1 << 16) /* L2ARC write in progress */
614 #define ARC_L2_EVICTED (1 << 17) /* evicted during I/O */
615 #define ARC_L2_WRITE_HEAD (1 << 18) /* head of write list */
616
617 #define HDR_IN_HASH_TABLE(hdr) ((hdr)->b_flags & ARC_IN_HASH_TABLE)
618 #define HDR_IO_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS)
619 #define HDR_IO_ERROR(hdr) ((hdr)->b_flags & ARC_IO_ERROR)
620 #define HDR_PREFETCH(hdr) ((hdr)->b_flags & ARC_PREFETCH)
621 #define HDR_FREED_IN_READ(hdr) ((hdr)->b_flags & ARC_FREED_IN_READ)
622 #define HDR_BUF_AVAILABLE(hdr) ((hdr)->b_flags & ARC_BUF_AVAILABLE)
623 #define HDR_FREE_IN_PROGRESS(hdr) ((hdr)->b_flags & ARC_FREE_IN_PROGRESS)
624 #define HDR_L2CACHE(hdr) ((hdr)->b_flags & ARC_L2CACHE)
625 #define HDR_L2_READING(hdr) ((hdr)->b_flags & ARC_IO_IN_PROGRESS && \
626 (hdr)->b_l2hdr != NULL)
627 #define HDR_L2_WRITING(hdr) ((hdr)->b_flags & ARC_L2_WRITING)
628 #define HDR_L2_EVICTED(hdr) ((hdr)->b_flags & ARC_L2_EVICTED)
629 #define HDR_L2_WRITE_HEAD(hdr) ((hdr)->b_flags & ARC_L2_WRITE_HEAD)
630
631 /*
632 * Other sizes
633 */
634
635 #define HDR_SIZE ((int64_t)sizeof (arc_buf_hdr_t))
636 #define L2HDR_SIZE ((int64_t)sizeof (l2arc_buf_hdr_t))
637
638 /*
639 * Hash table routines
640 */
641
642 #define HT_LOCK_ALIGN 64
643 #define HT_LOCK_PAD (P2NPHASE(sizeof (kmutex_t), (HT_LOCK_ALIGN)))
644
645 struct ht_lock {
646 kmutex_t ht_lock;
647 #ifdef _KERNEL
648 unsigned char pad[HT_LOCK_PAD];
649 #endif
650 };
651
652 #define BUF_LOCKS 256
653 typedef struct buf_hash_table {
654 uint64_t ht_mask;
655 arc_buf_hdr_t **ht_table;
656 struct ht_lock ht_locks[BUF_LOCKS];
657 } buf_hash_table_t;
658
659 static buf_hash_table_t buf_hash_table;
660
661 #define BUF_HASH_INDEX(spa, dva, birth) \
662 (buf_hash(spa, dva, birth) & buf_hash_table.ht_mask)
663 #define BUF_HASH_LOCK_NTRY(idx) (buf_hash_table.ht_locks[idx & (BUF_LOCKS-1)])
664 #define BUF_HASH_LOCK(idx) (&(BUF_HASH_LOCK_NTRY(idx).ht_lock))
665 #define HDR_LOCK(hdr) \
666 (BUF_HASH_LOCK(BUF_HASH_INDEX(hdr->b_spa, &hdr->b_dva, hdr->b_birth)))
667
668 uint64_t zfs_crc64_table[256];
669
670 /*
671 * Level 2 ARC
672 */
673
674 #define L2ARC_WRITE_SIZE (8 * 1024 * 1024) /* initial write max */
675 #define L2ARC_HEADROOM 2 /* num of writes */
676 /*
677 * If we discover during ARC scan any buffers to be compressed, we boost
678 * our headroom for the next scanning cycle by this percentage multiple.
679 */
680 #define L2ARC_HEADROOM_BOOST 200
681 #define L2ARC_FEED_SECS 1 /* caching interval secs */
682 #define L2ARC_FEED_MIN_MS 200 /* min caching interval ms */
683
684 #define l2arc_writes_sent ARCSTAT(arcstat_l2_writes_sent)
685 #define l2arc_writes_done ARCSTAT(arcstat_l2_writes_done)
686
687 /* L2ARC Performance Tunables */
688 unsigned long l2arc_write_max = L2ARC_WRITE_SIZE; /* def max write size */
689 unsigned long l2arc_write_boost = L2ARC_WRITE_SIZE; /* extra warmup write */
690 unsigned long l2arc_headroom = L2ARC_HEADROOM; /* # of dev writes */
691 unsigned long l2arc_headroom_boost = L2ARC_HEADROOM_BOOST;
692 unsigned long l2arc_feed_secs = L2ARC_FEED_SECS; /* interval seconds */
693 unsigned long l2arc_feed_min_ms = L2ARC_FEED_MIN_MS; /* min interval msecs */
694 int l2arc_noprefetch = B_TRUE; /* don't cache prefetch bufs */
695 int l2arc_nocompress = B_FALSE; /* don't compress bufs */
696 int l2arc_feed_again = B_TRUE; /* turbo warmup */
697 int l2arc_norw = B_FALSE; /* no reads during writes */
698
699 /*
700 * L2ARC Internals
701 */
702 typedef struct l2arc_dev {
703 vdev_t *l2ad_vdev; /* vdev */
704 spa_t *l2ad_spa; /* spa */
705 uint64_t l2ad_hand; /* next write location */
706 uint64_t l2ad_start; /* first addr on device */
707 uint64_t l2ad_end; /* last addr on device */
708 uint64_t l2ad_evict; /* last addr eviction reached */
709 boolean_t l2ad_first; /* first sweep through */
710 boolean_t l2ad_writing; /* currently writing */
711 list_t *l2ad_buflist; /* buffer list */
712 list_node_t l2ad_node; /* device list node */
713 } l2arc_dev_t;
714
715 static list_t L2ARC_dev_list; /* device list */
716 static list_t *l2arc_dev_list; /* device list pointer */
717 static kmutex_t l2arc_dev_mtx; /* device list mutex */
718 static l2arc_dev_t *l2arc_dev_last; /* last device used */
719 static kmutex_t l2arc_buflist_mtx; /* mutex for all buflists */
720 static list_t L2ARC_free_on_write; /* free after write buf list */
721 static list_t *l2arc_free_on_write; /* free after write list ptr */
722 static kmutex_t l2arc_free_on_write_mtx; /* mutex for list */
723 static uint64_t l2arc_ndev; /* number of devices */
724
725 typedef struct l2arc_read_callback {
726 arc_buf_t *l2rcb_buf; /* read buffer */
727 spa_t *l2rcb_spa; /* spa */
728 blkptr_t l2rcb_bp; /* original blkptr */
729 zbookmark_t l2rcb_zb; /* original bookmark */
730 int l2rcb_flags; /* original flags */
731 enum zio_compress l2rcb_compress; /* applied compress */
732 } l2arc_read_callback_t;
733
734 typedef struct l2arc_write_callback {
735 l2arc_dev_t *l2wcb_dev; /* device info */
736 arc_buf_hdr_t *l2wcb_head; /* head of write buflist */
737 } l2arc_write_callback_t;
738
739 struct l2arc_buf_hdr {
740 /* protected by arc_buf_hdr mutex */
741 l2arc_dev_t *b_dev; /* L2ARC device */
742 uint64_t b_daddr; /* disk address, offset byte */
743 /* compression applied to buffer data */
744 enum zio_compress b_compress;
745 /* real alloc'd buffer size depending on b_compress applied */
746 uint32_t b_asize;
747 uint32_t b_hits;
748 /* temporary buffer holder for in-flight compressed data */
749 void *b_tmp_cdata;
750 };
751
752 typedef struct l2arc_data_free {
753 /* protected by l2arc_free_on_write_mtx */
754 void *l2df_data;
755 size_t l2df_size;
756 void (*l2df_func)(void *, size_t);
757 list_node_t l2df_list_node;
758 } l2arc_data_free_t;
759
760 static kmutex_t l2arc_feed_thr_lock;
761 static kcondvar_t l2arc_feed_thr_cv;
762 static uint8_t l2arc_thread_exit;
763
764 static void l2arc_read_done(zio_t *zio);
765 static void l2arc_hdr_stat_add(void);
766 static void l2arc_hdr_stat_remove(void);
767
768 static boolean_t l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr);
769 static void l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr,
770 enum zio_compress c);
771 static void l2arc_release_cdata_buf(arc_buf_hdr_t *ab);
772
773 static uint64_t
774 buf_hash(uint64_t spa, const dva_t *dva, uint64_t birth)
775 {
776 uint8_t *vdva = (uint8_t *)dva;
777 uint64_t crc = -1ULL;
778 int i;
779
780 ASSERT(zfs_crc64_table[128] == ZFS_CRC64_POLY);
781
782 for (i = 0; i < sizeof (dva_t); i++)
783 crc = (crc >> 8) ^ zfs_crc64_table[(crc ^ vdva[i]) & 0xFF];
784
785 crc ^= (spa>>8) ^ birth;
786
787 return (crc);
788 }
789
790 #define BUF_EMPTY(buf) \
791 ((buf)->b_dva.dva_word[0] == 0 && \
792 (buf)->b_dva.dva_word[1] == 0 && \
793 (buf)->b_birth == 0)
794
795 #define BUF_EQUAL(spa, dva, birth, buf) \
796 ((buf)->b_dva.dva_word[0] == (dva)->dva_word[0]) && \
797 ((buf)->b_dva.dva_word[1] == (dva)->dva_word[1]) && \
798 ((buf)->b_birth == birth) && ((buf)->b_spa == spa)
799
800 static void
801 buf_discard_identity(arc_buf_hdr_t *hdr)
802 {
803 hdr->b_dva.dva_word[0] = 0;
804 hdr->b_dva.dva_word[1] = 0;
805 hdr->b_birth = 0;
806 hdr->b_cksum0 = 0;
807 }
808
809 static arc_buf_hdr_t *
810 buf_hash_find(uint64_t spa, const dva_t *dva, uint64_t birth, kmutex_t **lockp)
811 {
812 uint64_t idx = BUF_HASH_INDEX(spa, dva, birth);
813 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
814 arc_buf_hdr_t *buf;
815
816 mutex_enter(hash_lock);
817 for (buf = buf_hash_table.ht_table[idx]; buf != NULL;
818 buf = buf->b_hash_next) {
819 if (BUF_EQUAL(spa, dva, birth, buf)) {
820 *lockp = hash_lock;
821 return (buf);
822 }
823 }
824 mutex_exit(hash_lock);
825 *lockp = NULL;
826 return (NULL);
827 }
828
829 /*
830 * Insert an entry into the hash table. If there is already an element
831 * equal to elem in the hash table, then the already existing element
832 * will be returned and the new element will not be inserted.
833 * Otherwise returns NULL.
834 */
835 static arc_buf_hdr_t *
836 buf_hash_insert(arc_buf_hdr_t *buf, kmutex_t **lockp)
837 {
838 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
839 kmutex_t *hash_lock = BUF_HASH_LOCK(idx);
840 arc_buf_hdr_t *fbuf;
841 uint32_t i;
842
843 ASSERT(!HDR_IN_HASH_TABLE(buf));
844 *lockp = hash_lock;
845 mutex_enter(hash_lock);
846 for (fbuf = buf_hash_table.ht_table[idx], i = 0; fbuf != NULL;
847 fbuf = fbuf->b_hash_next, i++) {
848 if (BUF_EQUAL(buf->b_spa, &buf->b_dva, buf->b_birth, fbuf))
849 return (fbuf);
850 }
851
852 buf->b_hash_next = buf_hash_table.ht_table[idx];
853 buf_hash_table.ht_table[idx] = buf;
854 buf->b_flags |= ARC_IN_HASH_TABLE;
855
856 /* collect some hash table performance data */
857 if (i > 0) {
858 ARCSTAT_BUMP(arcstat_hash_collisions);
859 if (i == 1)
860 ARCSTAT_BUMP(arcstat_hash_chains);
861
862 ARCSTAT_MAX(arcstat_hash_chain_max, i);
863 }
864
865 ARCSTAT_BUMP(arcstat_hash_elements);
866 ARCSTAT_MAXSTAT(arcstat_hash_elements);
867
868 return (NULL);
869 }
870
871 static void
872 buf_hash_remove(arc_buf_hdr_t *buf)
873 {
874 arc_buf_hdr_t *fbuf, **bufp;
875 uint64_t idx = BUF_HASH_INDEX(buf->b_spa, &buf->b_dva, buf->b_birth);
876
877 ASSERT(MUTEX_HELD(BUF_HASH_LOCK(idx)));
878 ASSERT(HDR_IN_HASH_TABLE(buf));
879
880 bufp = &buf_hash_table.ht_table[idx];
881 while ((fbuf = *bufp) != buf) {
882 ASSERT(fbuf != NULL);
883 bufp = &fbuf->b_hash_next;
884 }
885 *bufp = buf->b_hash_next;
886 buf->b_hash_next = NULL;
887 buf->b_flags &= ~ARC_IN_HASH_TABLE;
888
889 /* collect some hash table performance data */
890 ARCSTAT_BUMPDOWN(arcstat_hash_elements);
891
892 if (buf_hash_table.ht_table[idx] &&
893 buf_hash_table.ht_table[idx]->b_hash_next == NULL)
894 ARCSTAT_BUMPDOWN(arcstat_hash_chains);
895 }
896
897 /*
898 * Global data structures and functions for the buf kmem cache.
899 */
900 static kmem_cache_t *hdr_cache;
901 static kmem_cache_t *buf_cache;
902
903 static void
904 buf_fini(void)
905 {
906 int i;
907
908 #if defined(_KERNEL) && defined(HAVE_SPL)
909 /*
910 * Large allocations which do not require contiguous pages
911 * should be using vmem_free() in the linux kernel\
912 */
913 vmem_free(buf_hash_table.ht_table,
914 (buf_hash_table.ht_mask + 1) * sizeof (void *));
915 #else
916 kmem_free(buf_hash_table.ht_table,
917 (buf_hash_table.ht_mask + 1) * sizeof (void *));
918 #endif
919 for (i = 0; i < BUF_LOCKS; i++)
920 mutex_destroy(&buf_hash_table.ht_locks[i].ht_lock);
921 kmem_cache_destroy(hdr_cache);
922 kmem_cache_destroy(buf_cache);
923 }
924
925 /*
926 * Constructor callback - called when the cache is empty
927 * and a new buf is requested.
928 */
929 /* ARGSUSED */
930 static int
931 hdr_cons(void *vbuf, void *unused, int kmflag)
932 {
933 arc_buf_hdr_t *buf = vbuf;
934
935 bzero(buf, sizeof (arc_buf_hdr_t));
936 refcount_create(&buf->b_refcnt);
937 cv_init(&buf->b_cv, NULL, CV_DEFAULT, NULL);
938 mutex_init(&buf->b_freeze_lock, NULL, MUTEX_DEFAULT, NULL);
939 list_link_init(&buf->b_arc_node);
940 list_link_init(&buf->b_l2node);
941 arc_space_consume(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
942
943 return (0);
944 }
945
946 /* ARGSUSED */
947 static int
948 buf_cons(void *vbuf, void *unused, int kmflag)
949 {
950 arc_buf_t *buf = vbuf;
951
952 bzero(buf, sizeof (arc_buf_t));
953 mutex_init(&buf->b_evict_lock, NULL, MUTEX_DEFAULT, NULL);
954 arc_space_consume(sizeof (arc_buf_t), ARC_SPACE_HDRS);
955
956 return (0);
957 }
958
959 /*
960 * Destructor callback - called when a cached buf is
961 * no longer required.
962 */
963 /* ARGSUSED */
964 static void
965 hdr_dest(void *vbuf, void *unused)
966 {
967 arc_buf_hdr_t *buf = vbuf;
968
969 ASSERT(BUF_EMPTY(buf));
970 refcount_destroy(&buf->b_refcnt);
971 cv_destroy(&buf->b_cv);
972 mutex_destroy(&buf->b_freeze_lock);
973 arc_space_return(sizeof (arc_buf_hdr_t), ARC_SPACE_HDRS);
974 }
975
976 /* ARGSUSED */
977 static void
978 buf_dest(void *vbuf, void *unused)
979 {
980 arc_buf_t *buf = vbuf;
981
982 mutex_destroy(&buf->b_evict_lock);
983 arc_space_return(sizeof (arc_buf_t), ARC_SPACE_HDRS);
984 }
985
986 static void
987 buf_init(void)
988 {
989 uint64_t *ct;
990 uint64_t hsize = 1ULL << 12;
991 int i, j;
992
993 /*
994 * The hash table is big enough to fill all of physical memory
995 * with an average 64K block size. The table will take up
996 * totalmem*sizeof(void*)/64K (eg. 128KB/GB with 8-byte pointers).
997 */
998 while (hsize * 65536 < physmem * PAGESIZE)
999 hsize <<= 1;
1000 retry:
1001 buf_hash_table.ht_mask = hsize - 1;
1002 #if defined(_KERNEL) && defined(HAVE_SPL)
1003 /*
1004 * Large allocations which do not require contiguous pages
1005 * should be using vmem_alloc() in the linux kernel
1006 */
1007 buf_hash_table.ht_table =
1008 vmem_zalloc(hsize * sizeof (void*), KM_SLEEP);
1009 #else
1010 buf_hash_table.ht_table =
1011 kmem_zalloc(hsize * sizeof (void*), KM_NOSLEEP);
1012 #endif
1013 if (buf_hash_table.ht_table == NULL) {
1014 ASSERT(hsize > (1ULL << 8));
1015 hsize >>= 1;
1016 goto retry;
1017 }
1018
1019 hdr_cache = kmem_cache_create("arc_buf_hdr_t", sizeof (arc_buf_hdr_t),
1020 0, hdr_cons, hdr_dest, NULL, NULL, NULL, 0);
1021 buf_cache = kmem_cache_create("arc_buf_t", sizeof (arc_buf_t),
1022 0, buf_cons, buf_dest, NULL, NULL, NULL, 0);
1023
1024 for (i = 0; i < 256; i++)
1025 for (ct = zfs_crc64_table + i, *ct = i, j = 8; j > 0; j--)
1026 *ct = (*ct >> 1) ^ (-(*ct & 1) & ZFS_CRC64_POLY);
1027
1028 for (i = 0; i < BUF_LOCKS; i++) {
1029 mutex_init(&buf_hash_table.ht_locks[i].ht_lock,
1030 NULL, MUTEX_DEFAULT, NULL);
1031 }
1032 }
1033
1034 #define ARC_MINTIME (hz>>4) /* 62 ms */
1035
1036 static void
1037 arc_cksum_verify(arc_buf_t *buf)
1038 {
1039 zio_cksum_t zc;
1040
1041 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1042 return;
1043
1044 mutex_enter(&buf->b_hdr->b_freeze_lock);
1045 if (buf->b_hdr->b_freeze_cksum == NULL ||
1046 (buf->b_hdr->b_flags & ARC_IO_ERROR)) {
1047 mutex_exit(&buf->b_hdr->b_freeze_lock);
1048 return;
1049 }
1050 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1051 if (!ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc))
1052 panic("buffer modified while frozen!");
1053 mutex_exit(&buf->b_hdr->b_freeze_lock);
1054 }
1055
1056 static int
1057 arc_cksum_equal(arc_buf_t *buf)
1058 {
1059 zio_cksum_t zc;
1060 int equal;
1061
1062 mutex_enter(&buf->b_hdr->b_freeze_lock);
1063 fletcher_2_native(buf->b_data, buf->b_hdr->b_size, &zc);
1064 equal = ZIO_CHECKSUM_EQUAL(*buf->b_hdr->b_freeze_cksum, zc);
1065 mutex_exit(&buf->b_hdr->b_freeze_lock);
1066
1067 return (equal);
1068 }
1069
1070 static void
1071 arc_cksum_compute(arc_buf_t *buf, boolean_t force)
1072 {
1073 if (!force && !(zfs_flags & ZFS_DEBUG_MODIFY))
1074 return;
1075
1076 mutex_enter(&buf->b_hdr->b_freeze_lock);
1077 if (buf->b_hdr->b_freeze_cksum != NULL) {
1078 mutex_exit(&buf->b_hdr->b_freeze_lock);
1079 return;
1080 }
1081 buf->b_hdr->b_freeze_cksum = kmem_alloc(sizeof (zio_cksum_t),
1082 KM_PUSHPAGE);
1083 fletcher_2_native(buf->b_data, buf->b_hdr->b_size,
1084 buf->b_hdr->b_freeze_cksum);
1085 mutex_exit(&buf->b_hdr->b_freeze_lock);
1086 arc_buf_watch(buf);
1087 }
1088
1089 #ifndef _KERNEL
1090 void
1091 arc_buf_sigsegv(int sig, siginfo_t *si, void *unused)
1092 {
1093 panic("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);
1094 }
1095 #endif
1096
1097 /* ARGSUSED */
1098 static void
1099 arc_buf_unwatch(arc_buf_t *buf)
1100 {
1101 #ifndef _KERNEL
1102 if (arc_watch) {
1103 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size,
1104 PROT_READ | PROT_WRITE));
1105 }
1106 #endif
1107 }
1108
1109 /* ARGSUSED */
1110 static void
1111 arc_buf_watch(arc_buf_t *buf)
1112 {
1113 #ifndef _KERNEL
1114 if (arc_watch)
1115 ASSERT0(mprotect(buf->b_data, buf->b_hdr->b_size, PROT_READ));
1116 #endif
1117 }
1118
1119 void
1120 arc_buf_thaw(arc_buf_t *buf)
1121 {
1122 if (zfs_flags & ZFS_DEBUG_MODIFY) {
1123 if (buf->b_hdr->b_state != arc_anon)
1124 panic("modifying non-anon buffer!");
1125 if (buf->b_hdr->b_flags & ARC_IO_IN_PROGRESS)
1126 panic("modifying buffer while i/o in progress!");
1127 arc_cksum_verify(buf);
1128 }
1129
1130 mutex_enter(&buf->b_hdr->b_freeze_lock);
1131 if (buf->b_hdr->b_freeze_cksum != NULL) {
1132 kmem_free(buf->b_hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1133 buf->b_hdr->b_freeze_cksum = NULL;
1134 }
1135
1136 mutex_exit(&buf->b_hdr->b_freeze_lock);
1137
1138 arc_buf_unwatch(buf);
1139 }
1140
1141 void
1142 arc_buf_freeze(arc_buf_t *buf)
1143 {
1144 kmutex_t *hash_lock;
1145
1146 if (!(zfs_flags & ZFS_DEBUG_MODIFY))
1147 return;
1148
1149 hash_lock = HDR_LOCK(buf->b_hdr);
1150 mutex_enter(hash_lock);
1151
1152 ASSERT(buf->b_hdr->b_freeze_cksum != NULL ||
1153 buf->b_hdr->b_state == arc_anon);
1154 arc_cksum_compute(buf, B_FALSE);
1155 mutex_exit(hash_lock);
1156
1157 }
1158
1159 static void
1160 add_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1161 {
1162 ASSERT(MUTEX_HELD(hash_lock));
1163
1164 if ((refcount_add(&ab->b_refcnt, tag) == 1) &&
1165 (ab->b_state != arc_anon)) {
1166 uint64_t delta = ab->b_size * ab->b_datacnt;
1167 list_t *list = &ab->b_state->arcs_list[ab->b_type];
1168 uint64_t *size = &ab->b_state->arcs_lsize[ab->b_type];
1169
1170 ASSERT(!MUTEX_HELD(&ab->b_state->arcs_mtx));
1171 mutex_enter(&ab->b_state->arcs_mtx);
1172 ASSERT(list_link_active(&ab->b_arc_node));
1173 list_remove(list, ab);
1174 if (GHOST_STATE(ab->b_state)) {
1175 ASSERT0(ab->b_datacnt);
1176 ASSERT3P(ab->b_buf, ==, NULL);
1177 delta = ab->b_size;
1178 }
1179 ASSERT(delta > 0);
1180 ASSERT3U(*size, >=, delta);
1181 atomic_add_64(size, -delta);
1182 mutex_exit(&ab->b_state->arcs_mtx);
1183 /* remove the prefetch flag if we get a reference */
1184 if (ab->b_flags & ARC_PREFETCH)
1185 ab->b_flags &= ~ARC_PREFETCH;
1186 }
1187 }
1188
1189 static int
1190 remove_reference(arc_buf_hdr_t *ab, kmutex_t *hash_lock, void *tag)
1191 {
1192 int cnt;
1193 arc_state_t *state = ab->b_state;
1194
1195 ASSERT(state == arc_anon || MUTEX_HELD(hash_lock));
1196 ASSERT(!GHOST_STATE(state));
1197
1198 if (((cnt = refcount_remove(&ab->b_refcnt, tag)) == 0) &&
1199 (state != arc_anon)) {
1200 uint64_t *size = &state->arcs_lsize[ab->b_type];
1201
1202 ASSERT(!MUTEX_HELD(&state->arcs_mtx));
1203 mutex_enter(&state->arcs_mtx);
1204 ASSERT(!list_link_active(&ab->b_arc_node));
1205 list_insert_head(&state->arcs_list[ab->b_type], ab);
1206 ASSERT(ab->b_datacnt > 0);
1207 atomic_add_64(size, ab->b_size * ab->b_datacnt);
1208 mutex_exit(&state->arcs_mtx);
1209 }
1210 return (cnt);
1211 }
1212
1213 /*
1214 * Returns detailed information about a specific arc buffer. When the
1215 * state_index argument is set the function will calculate the arc header
1216 * list position for its arc state. Since this requires a linear traversal
1217 * callers are strongly encourage not to do this. However, it can be helpful
1218 * for targeted analysis so the functionality is provided.
1219 */
1220 void
1221 arc_buf_info(arc_buf_t *ab, arc_buf_info_t *abi, int state_index)
1222 {
1223 arc_buf_hdr_t *hdr = ab->b_hdr;
1224 arc_state_t *state = hdr->b_state;
1225
1226 memset(abi, 0, sizeof (arc_buf_info_t));
1227 abi->abi_flags = hdr->b_flags;
1228 abi->abi_datacnt = hdr->b_datacnt;
1229 abi->abi_state_type = state ? state->arcs_state : ARC_STATE_ANON;
1230 abi->abi_state_contents = hdr->b_type;
1231 abi->abi_state_index = -1;
1232 abi->abi_size = hdr->b_size;
1233 abi->abi_access = hdr->b_arc_access;
1234 abi->abi_mru_hits = hdr->b_mru_hits;
1235 abi->abi_mru_ghost_hits = hdr->b_mru_ghost_hits;
1236 abi->abi_mfu_hits = hdr->b_mfu_hits;
1237 abi->abi_mfu_ghost_hits = hdr->b_mfu_ghost_hits;
1238 abi->abi_holds = refcount_count(&hdr->b_refcnt);
1239
1240 if (hdr->b_l2hdr) {
1241 abi->abi_l2arc_dattr = hdr->b_l2hdr->b_daddr;
1242 abi->abi_l2arc_asize = hdr->b_l2hdr->b_asize;
1243 abi->abi_l2arc_compress = hdr->b_l2hdr->b_compress;
1244 abi->abi_l2arc_hits = hdr->b_l2hdr->b_hits;
1245 }
1246
1247 if (state && state_index && list_link_active(&hdr->b_arc_node)) {
1248 list_t *list = &state->arcs_list[hdr->b_type];
1249 arc_buf_hdr_t *h;
1250
1251 mutex_enter(&state->arcs_mtx);
1252 for (h = list_head(list); h != NULL; h = list_next(list, h)) {
1253 abi->abi_state_index++;
1254 if (h == hdr)
1255 break;
1256 }
1257 mutex_exit(&state->arcs_mtx);
1258 }
1259 }
1260
1261 /*
1262 * Move the supplied buffer to the indicated state. The mutex
1263 * for the buffer must be held by the caller.
1264 */
1265 static void
1266 arc_change_state(arc_state_t *new_state, arc_buf_hdr_t *ab, kmutex_t *hash_lock)
1267 {
1268 arc_state_t *old_state = ab->b_state;
1269 int64_t refcnt = refcount_count(&ab->b_refcnt);
1270 uint64_t from_delta, to_delta;
1271
1272 ASSERT(MUTEX_HELD(hash_lock));
1273 ASSERT3P(new_state, !=, old_state);
1274 ASSERT(refcnt == 0 || ab->b_datacnt > 0);
1275 ASSERT(ab->b_datacnt == 0 || !GHOST_STATE(new_state));
1276 ASSERT(ab->b_datacnt <= 1 || old_state != arc_anon);
1277
1278 from_delta = to_delta = ab->b_datacnt * ab->b_size;
1279
1280 /*
1281 * If this buffer is evictable, transfer it from the
1282 * old state list to the new state list.
1283 */
1284 if (refcnt == 0) {
1285 if (old_state != arc_anon) {
1286 int use_mutex = !MUTEX_HELD(&old_state->arcs_mtx);
1287 uint64_t *size = &old_state->arcs_lsize[ab->b_type];
1288
1289 if (use_mutex)
1290 mutex_enter(&old_state->arcs_mtx);
1291
1292 ASSERT(list_link_active(&ab->b_arc_node));
1293 list_remove(&old_state->arcs_list[ab->b_type], ab);
1294
1295 /*
1296 * If prefetching out of the ghost cache,
1297 * we will have a non-zero datacnt.
1298 */
1299 if (GHOST_STATE(old_state) && ab->b_datacnt == 0) {
1300 /* ghost elements have a ghost size */
1301 ASSERT(ab->b_buf == NULL);
1302 from_delta = ab->b_size;
1303 }
1304 ASSERT3U(*size, >=, from_delta);
1305 atomic_add_64(size, -from_delta);
1306
1307 if (use_mutex)
1308 mutex_exit(&old_state->arcs_mtx);
1309 }
1310 if (new_state != arc_anon) {
1311 int use_mutex = !MUTEX_HELD(&new_state->arcs_mtx);
1312 uint64_t *size = &new_state->arcs_lsize[ab->b_type];
1313
1314 if (use_mutex)
1315 mutex_enter(&new_state->arcs_mtx);
1316
1317 list_insert_head(&new_state->arcs_list[ab->b_type], ab);
1318
1319 /* ghost elements have a ghost size */
1320 if (GHOST_STATE(new_state)) {
1321 ASSERT(ab->b_datacnt == 0);
1322 ASSERT(ab->b_buf == NULL);
1323 to_delta = ab->b_size;
1324 }
1325 atomic_add_64(size, to_delta);
1326
1327 if (use_mutex)
1328 mutex_exit(&new_state->arcs_mtx);
1329 }
1330 }
1331
1332 ASSERT(!BUF_EMPTY(ab));
1333 if (new_state == arc_anon && HDR_IN_HASH_TABLE(ab))
1334 buf_hash_remove(ab);
1335
1336 /* adjust state sizes */
1337 if (to_delta)
1338 atomic_add_64(&new_state->arcs_size, to_delta);
1339 if (from_delta) {
1340 ASSERT3U(old_state->arcs_size, >=, from_delta);
1341 atomic_add_64(&old_state->arcs_size, -from_delta);
1342 }
1343 ab->b_state = new_state;
1344
1345 /* adjust l2arc hdr stats */
1346 if (new_state == arc_l2c_only)
1347 l2arc_hdr_stat_add();
1348 else if (old_state == arc_l2c_only)
1349 l2arc_hdr_stat_remove();
1350 }
1351
1352 void
1353 arc_space_consume(uint64_t space, arc_space_type_t type)
1354 {
1355 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1356
1357 switch (type) {
1358 default:
1359 break;
1360 case ARC_SPACE_DATA:
1361 ARCSTAT_INCR(arcstat_data_size, space);
1362 break;
1363 case ARC_SPACE_OTHER:
1364 ARCSTAT_INCR(arcstat_other_size, space);
1365 break;
1366 case ARC_SPACE_HDRS:
1367 ARCSTAT_INCR(arcstat_hdr_size, space);
1368 break;
1369 case ARC_SPACE_L2HDRS:
1370 ARCSTAT_INCR(arcstat_l2_hdr_size, space);
1371 break;
1372 }
1373
1374 ARCSTAT_INCR(arcstat_meta_used, space);
1375 atomic_add_64(&arc_size, space);
1376 }
1377
1378 void
1379 arc_space_return(uint64_t space, arc_space_type_t type)
1380 {
1381 ASSERT(type >= 0 && type < ARC_SPACE_NUMTYPES);
1382
1383 switch (type) {
1384 default:
1385 break;
1386 case ARC_SPACE_DATA:
1387 ARCSTAT_INCR(arcstat_data_size, -space);
1388 break;
1389 case ARC_SPACE_OTHER:
1390 ARCSTAT_INCR(arcstat_other_size, -space);
1391 break;
1392 case ARC_SPACE_HDRS:
1393 ARCSTAT_INCR(arcstat_hdr_size, -space);
1394 break;
1395 case ARC_SPACE_L2HDRS:
1396 ARCSTAT_INCR(arcstat_l2_hdr_size, -space);
1397 break;
1398 }
1399
1400 ASSERT(arc_meta_used >= space);
1401 if (arc_meta_max < arc_meta_used)
1402 arc_meta_max = arc_meta_used;
1403 ARCSTAT_INCR(arcstat_meta_used, -space);
1404 ASSERT(arc_size >= space);
1405 atomic_add_64(&arc_size, -space);
1406 }
1407
1408 arc_buf_t *
1409 arc_buf_alloc(spa_t *spa, int size, void *tag, arc_buf_contents_t type)
1410 {
1411 arc_buf_hdr_t *hdr;
1412 arc_buf_t *buf;
1413
1414 ASSERT3U(size, >, 0);
1415 hdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
1416 ASSERT(BUF_EMPTY(hdr));
1417 hdr->b_size = size;
1418 hdr->b_type = type;
1419 hdr->b_spa = spa_load_guid(spa);
1420 hdr->b_state = arc_anon;
1421 hdr->b_arc_access = 0;
1422 hdr->b_mru_hits = 0;
1423 hdr->b_mru_ghost_hits = 0;
1424 hdr->b_mfu_hits = 0;
1425 hdr->b_mfu_ghost_hits = 0;
1426 hdr->b_l2_hits = 0;
1427 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1428 buf->b_hdr = hdr;
1429 buf->b_data = NULL;
1430 buf->b_efunc = NULL;
1431 buf->b_private = NULL;
1432 buf->b_next = NULL;
1433 hdr->b_buf = buf;
1434 arc_get_data_buf(buf);
1435 hdr->b_datacnt = 1;
1436 hdr->b_flags = 0;
1437 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1438 (void) refcount_add(&hdr->b_refcnt, tag);
1439
1440 return (buf);
1441 }
1442
1443 static char *arc_onloan_tag = "onloan";
1444
1445 /*
1446 * Loan out an anonymous arc buffer. Loaned buffers are not counted as in
1447 * flight data by arc_tempreserve_space() until they are "returned". Loaned
1448 * buffers must be returned to the arc before they can be used by the DMU or
1449 * freed.
1450 */
1451 arc_buf_t *
1452 arc_loan_buf(spa_t *spa, int size)
1453 {
1454 arc_buf_t *buf;
1455
1456 buf = arc_buf_alloc(spa, size, arc_onloan_tag, ARC_BUFC_DATA);
1457
1458 atomic_add_64(&arc_loaned_bytes, size);
1459 return (buf);
1460 }
1461
1462 /*
1463 * Return a loaned arc buffer to the arc.
1464 */
1465 void
1466 arc_return_buf(arc_buf_t *buf, void *tag)
1467 {
1468 arc_buf_hdr_t *hdr = buf->b_hdr;
1469
1470 ASSERT(buf->b_data != NULL);
1471 (void) refcount_add(&hdr->b_refcnt, tag);
1472 (void) refcount_remove(&hdr->b_refcnt, arc_onloan_tag);
1473
1474 atomic_add_64(&arc_loaned_bytes, -hdr->b_size);
1475 }
1476
1477 /* Detach an arc_buf from a dbuf (tag) */
1478 void
1479 arc_loan_inuse_buf(arc_buf_t *buf, void *tag)
1480 {
1481 arc_buf_hdr_t *hdr;
1482
1483 ASSERT(buf->b_data != NULL);
1484 hdr = buf->b_hdr;
1485 (void) refcount_add(&hdr->b_refcnt, arc_onloan_tag);
1486 (void) refcount_remove(&hdr->b_refcnt, tag);
1487 buf->b_efunc = NULL;
1488 buf->b_private = NULL;
1489
1490 atomic_add_64(&arc_loaned_bytes, hdr->b_size);
1491 }
1492
1493 static arc_buf_t *
1494 arc_buf_clone(arc_buf_t *from)
1495 {
1496 arc_buf_t *buf;
1497 arc_buf_hdr_t *hdr = from->b_hdr;
1498 uint64_t size = hdr->b_size;
1499
1500 ASSERT(hdr->b_state != arc_anon);
1501
1502 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
1503 buf->b_hdr = hdr;
1504 buf->b_data = NULL;
1505 buf->b_efunc = NULL;
1506 buf->b_private = NULL;
1507 buf->b_next = hdr->b_buf;
1508 hdr->b_buf = buf;
1509 arc_get_data_buf(buf);
1510 bcopy(from->b_data, buf->b_data, size);
1511
1512 /*
1513 * This buffer already exists in the arc so create a duplicate
1514 * copy for the caller. If the buffer is associated with user data
1515 * then track the size and number of duplicates. These stats will be
1516 * updated as duplicate buffers are created and destroyed.
1517 */
1518 if (hdr->b_type == ARC_BUFC_DATA) {
1519 ARCSTAT_BUMP(arcstat_duplicate_buffers);
1520 ARCSTAT_INCR(arcstat_duplicate_buffers_size, size);
1521 }
1522 hdr->b_datacnt += 1;
1523 return (buf);
1524 }
1525
1526 void
1527 arc_buf_add_ref(arc_buf_t *buf, void* tag)
1528 {
1529 arc_buf_hdr_t *hdr;
1530 kmutex_t *hash_lock;
1531
1532 /*
1533 * Check to see if this buffer is evicted. Callers
1534 * must verify b_data != NULL to know if the add_ref
1535 * was successful.
1536 */
1537 mutex_enter(&buf->b_evict_lock);
1538 if (buf->b_data == NULL) {
1539 mutex_exit(&buf->b_evict_lock);
1540 return;
1541 }
1542 hash_lock = HDR_LOCK(buf->b_hdr);
1543 mutex_enter(hash_lock);
1544 hdr = buf->b_hdr;
1545 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1546 mutex_exit(&buf->b_evict_lock);
1547
1548 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
1549 add_reference(hdr, hash_lock, tag);
1550 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
1551 arc_access(hdr, hash_lock);
1552 mutex_exit(hash_lock);
1553 ARCSTAT_BUMP(arcstat_hits);
1554 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
1555 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
1556 data, metadata, hits);
1557 }
1558
1559 /*
1560 * Free the arc data buffer. If it is an l2arc write in progress,
1561 * the buffer is placed on l2arc_free_on_write to be freed later.
1562 */
1563 static void
1564 arc_buf_data_free(arc_buf_t *buf, void (*free_func)(void *, size_t))
1565 {
1566 arc_buf_hdr_t *hdr = buf->b_hdr;
1567
1568 if (HDR_L2_WRITING(hdr)) {
1569 l2arc_data_free_t *df;
1570 df = kmem_alloc(sizeof (l2arc_data_free_t), KM_PUSHPAGE);
1571 df->l2df_data = buf->b_data;
1572 df->l2df_size = hdr->b_size;
1573 df->l2df_func = free_func;
1574 mutex_enter(&l2arc_free_on_write_mtx);
1575 list_insert_head(l2arc_free_on_write, df);
1576 mutex_exit(&l2arc_free_on_write_mtx);
1577 ARCSTAT_BUMP(arcstat_l2_free_on_write);
1578 } else {
1579 free_func(buf->b_data, hdr->b_size);
1580 }
1581 }
1582
1583 static void
1584 arc_buf_destroy(arc_buf_t *buf, boolean_t recycle, boolean_t all)
1585 {
1586 arc_buf_t **bufp;
1587
1588 /* free up data associated with the buf */
1589 if (buf->b_data) {
1590 arc_state_t *state = buf->b_hdr->b_state;
1591 uint64_t size = buf->b_hdr->b_size;
1592 arc_buf_contents_t type = buf->b_hdr->b_type;
1593
1594 arc_cksum_verify(buf);
1595 arc_buf_unwatch(buf);
1596
1597 if (!recycle) {
1598 if (type == ARC_BUFC_METADATA) {
1599 arc_buf_data_free(buf, zio_buf_free);
1600 arc_space_return(size, ARC_SPACE_DATA);
1601 } else {
1602 ASSERT(type == ARC_BUFC_DATA);
1603 arc_buf_data_free(buf, zio_data_buf_free);
1604 ARCSTAT_INCR(arcstat_data_size, -size);
1605 atomic_add_64(&arc_size, -size);
1606 }
1607 }
1608 if (list_link_active(&buf->b_hdr->b_arc_node)) {
1609 uint64_t *cnt = &state->arcs_lsize[type];
1610
1611 ASSERT(refcount_is_zero(&buf->b_hdr->b_refcnt));
1612 ASSERT(state != arc_anon);
1613
1614 ASSERT3U(*cnt, >=, size);
1615 atomic_add_64(cnt, -size);
1616 }
1617 ASSERT3U(state->arcs_size, >=, size);
1618 atomic_add_64(&state->arcs_size, -size);
1619 buf->b_data = NULL;
1620
1621 /*
1622 * If we're destroying a duplicate buffer make sure
1623 * that the appropriate statistics are updated.
1624 */
1625 if (buf->b_hdr->b_datacnt > 1 &&
1626 buf->b_hdr->b_type == ARC_BUFC_DATA) {
1627 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
1628 ARCSTAT_INCR(arcstat_duplicate_buffers_size, -size);
1629 }
1630 ASSERT(buf->b_hdr->b_datacnt > 0);
1631 buf->b_hdr->b_datacnt -= 1;
1632 }
1633
1634 /* only remove the buf if requested */
1635 if (!all)
1636 return;
1637
1638 /* remove the buf from the hdr list */
1639 for (bufp = &buf->b_hdr->b_buf; *bufp != buf; bufp = &(*bufp)->b_next)
1640 continue;
1641 *bufp = buf->b_next;
1642 buf->b_next = NULL;
1643
1644 ASSERT(buf->b_efunc == NULL);
1645
1646 /* clean up the buf */
1647 buf->b_hdr = NULL;
1648 kmem_cache_free(buf_cache, buf);
1649 }
1650
1651 static void
1652 arc_hdr_destroy(arc_buf_hdr_t *hdr)
1653 {
1654 l2arc_buf_hdr_t *l2hdr = hdr->b_l2hdr;
1655
1656 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1657 ASSERT3P(hdr->b_state, ==, arc_anon);
1658 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
1659
1660 if (l2hdr != NULL) {
1661 boolean_t buflist_held = MUTEX_HELD(&l2arc_buflist_mtx);
1662 /*
1663 * To prevent arc_free() and l2arc_evict() from
1664 * attempting to free the same buffer at the same time,
1665 * a FREE_IN_PROGRESS flag is given to arc_free() to
1666 * give it priority. l2arc_evict() can't destroy this
1667 * header while we are waiting on l2arc_buflist_mtx.
1668 *
1669 * The hdr may be removed from l2ad_buflist before we
1670 * grab l2arc_buflist_mtx, so b_l2hdr is rechecked.
1671 */
1672 if (!buflist_held) {
1673 mutex_enter(&l2arc_buflist_mtx);
1674 l2hdr = hdr->b_l2hdr;
1675 }
1676
1677 if (l2hdr != NULL) {
1678 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
1679 ARCSTAT_INCR(arcstat_l2_size, -hdr->b_size);
1680 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
1681 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
1682 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
1683 if (hdr->b_state == arc_l2c_only)
1684 l2arc_hdr_stat_remove();
1685 hdr->b_l2hdr = NULL;
1686 }
1687
1688 if (!buflist_held)
1689 mutex_exit(&l2arc_buflist_mtx);
1690 }
1691
1692 if (!BUF_EMPTY(hdr)) {
1693 ASSERT(!HDR_IN_HASH_TABLE(hdr));
1694 buf_discard_identity(hdr);
1695 }
1696 while (hdr->b_buf) {
1697 arc_buf_t *buf = hdr->b_buf;
1698
1699 if (buf->b_efunc) {
1700 mutex_enter(&arc_eviction_mtx);
1701 mutex_enter(&buf->b_evict_lock);
1702 ASSERT(buf->b_hdr != NULL);
1703 arc_buf_destroy(hdr->b_buf, FALSE, FALSE);
1704 hdr->b_buf = buf->b_next;
1705 buf->b_hdr = &arc_eviction_hdr;
1706 buf->b_next = arc_eviction_list;
1707 arc_eviction_list = buf;
1708 mutex_exit(&buf->b_evict_lock);
1709 mutex_exit(&arc_eviction_mtx);
1710 } else {
1711 arc_buf_destroy(hdr->b_buf, FALSE, TRUE);
1712 }
1713 }
1714 if (hdr->b_freeze_cksum != NULL) {
1715 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
1716 hdr->b_freeze_cksum = NULL;
1717 }
1718
1719 ASSERT(!list_link_active(&hdr->b_arc_node));
1720 ASSERT3P(hdr->b_hash_next, ==, NULL);
1721 ASSERT3P(hdr->b_acb, ==, NULL);
1722 kmem_cache_free(hdr_cache, hdr);
1723 }
1724
1725 void
1726 arc_buf_free(arc_buf_t *buf, void *tag)
1727 {
1728 arc_buf_hdr_t *hdr = buf->b_hdr;
1729 int hashed = hdr->b_state != arc_anon;
1730
1731 ASSERT(buf->b_efunc == NULL);
1732 ASSERT(buf->b_data != NULL);
1733
1734 if (hashed) {
1735 kmutex_t *hash_lock = HDR_LOCK(hdr);
1736
1737 mutex_enter(hash_lock);
1738 hdr = buf->b_hdr;
1739 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1740
1741 (void) remove_reference(hdr, hash_lock, tag);
1742 if (hdr->b_datacnt > 1) {
1743 arc_buf_destroy(buf, FALSE, TRUE);
1744 } else {
1745 ASSERT(buf == hdr->b_buf);
1746 ASSERT(buf->b_efunc == NULL);
1747 hdr->b_flags |= ARC_BUF_AVAILABLE;
1748 }
1749 mutex_exit(hash_lock);
1750 } else if (HDR_IO_IN_PROGRESS(hdr)) {
1751 int destroy_hdr;
1752 /*
1753 * We are in the middle of an async write. Don't destroy
1754 * this buffer unless the write completes before we finish
1755 * decrementing the reference count.
1756 */
1757 mutex_enter(&arc_eviction_mtx);
1758 (void) remove_reference(hdr, NULL, tag);
1759 ASSERT(refcount_is_zero(&hdr->b_refcnt));
1760 destroy_hdr = !HDR_IO_IN_PROGRESS(hdr);
1761 mutex_exit(&arc_eviction_mtx);
1762 if (destroy_hdr)
1763 arc_hdr_destroy(hdr);
1764 } else {
1765 if (remove_reference(hdr, NULL, tag) > 0)
1766 arc_buf_destroy(buf, FALSE, TRUE);
1767 else
1768 arc_hdr_destroy(hdr);
1769 }
1770 }
1771
1772 boolean_t
1773 arc_buf_remove_ref(arc_buf_t *buf, void* tag)
1774 {
1775 arc_buf_hdr_t *hdr = buf->b_hdr;
1776 kmutex_t *hash_lock = NULL;
1777 boolean_t no_callback = (buf->b_efunc == NULL);
1778
1779 if (hdr->b_state == arc_anon) {
1780 ASSERT(hdr->b_datacnt == 1);
1781 arc_buf_free(buf, tag);
1782 return (no_callback);
1783 }
1784
1785 hash_lock = HDR_LOCK(hdr);
1786 mutex_enter(hash_lock);
1787 hdr = buf->b_hdr;
1788 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
1789 ASSERT(hdr->b_state != arc_anon);
1790 ASSERT(buf->b_data != NULL);
1791
1792 (void) remove_reference(hdr, hash_lock, tag);
1793 if (hdr->b_datacnt > 1) {
1794 if (no_callback)
1795 arc_buf_destroy(buf, FALSE, TRUE);
1796 } else if (no_callback) {
1797 ASSERT(hdr->b_buf == buf && buf->b_next == NULL);
1798 ASSERT(buf->b_efunc == NULL);
1799 hdr->b_flags |= ARC_BUF_AVAILABLE;
1800 }
1801 ASSERT(no_callback || hdr->b_datacnt > 1 ||
1802 refcount_is_zero(&hdr->b_refcnt));
1803 mutex_exit(hash_lock);
1804 return (no_callback);
1805 }
1806
1807 int
1808 arc_buf_size(arc_buf_t *buf)
1809 {
1810 return (buf->b_hdr->b_size);
1811 }
1812
1813 /*
1814 * Called from the DMU to determine if the current buffer should be
1815 * evicted. In order to ensure proper locking, the eviction must be initiated
1816 * from the DMU. Return true if the buffer is associated with user data and
1817 * duplicate buffers still exist.
1818 */
1819 boolean_t
1820 arc_buf_eviction_needed(arc_buf_t *buf)
1821 {
1822 arc_buf_hdr_t *hdr;
1823 boolean_t evict_needed = B_FALSE;
1824
1825 if (zfs_disable_dup_eviction)
1826 return (B_FALSE);
1827
1828 mutex_enter(&buf->b_evict_lock);
1829 hdr = buf->b_hdr;
1830 if (hdr == NULL) {
1831 /*
1832 * We are in arc_do_user_evicts(); let that function
1833 * perform the eviction.
1834 */
1835 ASSERT(buf->b_data == NULL);
1836 mutex_exit(&buf->b_evict_lock);
1837 return (B_FALSE);
1838 } else if (buf->b_data == NULL) {
1839 /*
1840 * We have already been added to the arc eviction list;
1841 * recommend eviction.
1842 */
1843 ASSERT3P(hdr, ==, &arc_eviction_hdr);
1844 mutex_exit(&buf->b_evict_lock);
1845 return (B_TRUE);
1846 }
1847
1848 if (hdr->b_datacnt > 1 && hdr->b_type == ARC_BUFC_DATA)
1849 evict_needed = B_TRUE;
1850
1851 mutex_exit(&buf->b_evict_lock);
1852 return (evict_needed);
1853 }
1854
1855 /*
1856 * Evict buffers from list until we've removed the specified number of
1857 * bytes. Move the removed buffers to the appropriate evict state.
1858 * If the recycle flag is set, then attempt to "recycle" a buffer:
1859 * - look for a buffer to evict that is `bytes' long.
1860 * - return the data block from this buffer rather than freeing it.
1861 * This flag is used by callers that are trying to make space for a
1862 * new buffer in a full arc cache.
1863 *
1864 * This function makes a "best effort". It skips over any buffers
1865 * it can't get a hash_lock on, and so may not catch all candidates.
1866 * It may also return without evicting as much space as requested.
1867 */
1868 static void *
1869 arc_evict(arc_state_t *state, uint64_t spa, int64_t bytes, boolean_t recycle,
1870 arc_buf_contents_t type)
1871 {
1872 arc_state_t *evicted_state;
1873 uint64_t bytes_evicted = 0, skipped = 0, missed = 0;
1874 arc_buf_hdr_t *ab, *ab_prev = NULL;
1875 list_t *list = &state->arcs_list[type];
1876 kmutex_t *hash_lock;
1877 boolean_t have_lock;
1878 void *stolen = NULL;
1879 arc_buf_hdr_t marker = {{{ 0 }}};
1880 int count = 0;
1881
1882 ASSERT(state == arc_mru || state == arc_mfu);
1883
1884 evicted_state = (state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
1885
1886 mutex_enter(&state->arcs_mtx);
1887 mutex_enter(&evicted_state->arcs_mtx);
1888
1889 for (ab = list_tail(list); ab; ab = ab_prev) {
1890 ab_prev = list_prev(list, ab);
1891 /* prefetch buffers have a minimum lifespan */
1892 if (HDR_IO_IN_PROGRESS(ab) ||
1893 (spa && ab->b_spa != spa) ||
1894 (ab->b_flags & (ARC_PREFETCH|ARC_INDIRECT) &&
1895 ddi_get_lbolt() - ab->b_arc_access <
1896 zfs_arc_min_prefetch_lifespan)) {
1897 skipped++;
1898 continue;
1899 }
1900 /* "lookahead" for better eviction candidate */
1901 if (recycle && ab->b_size != bytes &&
1902 ab_prev && ab_prev->b_size == bytes)
1903 continue;
1904
1905 /* ignore markers */
1906 if (ab->b_spa == 0)
1907 continue;
1908
1909 /*
1910 * It may take a long time to evict all the bufs requested.
1911 * To avoid blocking all arc activity, periodically drop
1912 * the arcs_mtx and give other threads a chance to run
1913 * before reacquiring the lock.
1914 *
1915 * If we are looking for a buffer to recycle, we are in
1916 * the hot code path, so don't sleep.
1917 */
1918 if (!recycle && count++ > arc_evict_iterations) {
1919 list_insert_after(list, ab, &marker);
1920 mutex_exit(&evicted_state->arcs_mtx);
1921 mutex_exit(&state->arcs_mtx);
1922 kpreempt(KPREEMPT_SYNC);
1923 mutex_enter(&state->arcs_mtx);
1924 mutex_enter(&evicted_state->arcs_mtx);
1925 ab_prev = list_prev(list, &marker);
1926 list_remove(list, &marker);
1927 count = 0;
1928 continue;
1929 }
1930
1931 hash_lock = HDR_LOCK(ab);
1932 have_lock = MUTEX_HELD(hash_lock);
1933 if (have_lock || mutex_tryenter(hash_lock)) {
1934 ASSERT0(refcount_count(&ab->b_refcnt));
1935 ASSERT(ab->b_datacnt > 0);
1936 while (ab->b_buf) {
1937 arc_buf_t *buf = ab->b_buf;
1938 if (!mutex_tryenter(&buf->b_evict_lock)) {
1939 missed += 1;
1940 break;
1941 }
1942 if (buf->b_data) {
1943 bytes_evicted += ab->b_size;
1944 if (recycle && ab->b_type == type &&
1945 ab->b_size == bytes &&
1946 !HDR_L2_WRITING(ab)) {
1947 stolen = buf->b_data;
1948 recycle = FALSE;
1949 }
1950 }
1951 if (buf->b_efunc) {
1952 mutex_enter(&arc_eviction_mtx);
1953 arc_buf_destroy(buf,
1954 buf->b_data == stolen, FALSE);
1955 ab->b_buf = buf->b_next;
1956 buf->b_hdr = &arc_eviction_hdr;
1957 buf->b_next = arc_eviction_list;
1958 arc_eviction_list = buf;
1959 mutex_exit(&arc_eviction_mtx);
1960 mutex_exit(&buf->b_evict_lock);
1961 } else {
1962 mutex_exit(&buf->b_evict_lock);
1963 arc_buf_destroy(buf,
1964 buf->b_data == stolen, TRUE);
1965 }
1966 }
1967
1968 if (ab->b_l2hdr) {
1969 ARCSTAT_INCR(arcstat_evict_l2_cached,
1970 ab->b_size);
1971 } else {
1972 if (l2arc_write_eligible(ab->b_spa, ab)) {
1973 ARCSTAT_INCR(arcstat_evict_l2_eligible,
1974 ab->b_size);
1975 } else {
1976 ARCSTAT_INCR(
1977 arcstat_evict_l2_ineligible,
1978 ab->b_size);
1979 }
1980 }
1981
1982 if (ab->b_datacnt == 0) {
1983 arc_change_state(evicted_state, ab, hash_lock);
1984 ASSERT(HDR_IN_HASH_TABLE(ab));
1985 ab->b_flags |= ARC_IN_HASH_TABLE;
1986 ab->b_flags &= ~ARC_BUF_AVAILABLE;
1987 DTRACE_PROBE1(arc__evict, arc_buf_hdr_t *, ab);
1988 }
1989 if (!have_lock)
1990 mutex_exit(hash_lock);
1991 if (bytes >= 0 && bytes_evicted >= bytes)
1992 break;
1993 } else {
1994 missed += 1;
1995 }
1996 }
1997
1998 mutex_exit(&evicted_state->arcs_mtx);
1999 mutex_exit(&state->arcs_mtx);
2000
2001 if (bytes_evicted < bytes)
2002 dprintf("only evicted %lld bytes from %x\n",
2003 (longlong_t)bytes_evicted, state);
2004
2005 if (skipped)
2006 ARCSTAT_INCR(arcstat_evict_skip, skipped);
2007
2008 if (missed)
2009 ARCSTAT_INCR(arcstat_mutex_miss, missed);
2010
2011 /*
2012 * Note: we have just evicted some data into the ghost state,
2013 * potentially putting the ghost size over the desired size. Rather
2014 * that evicting from the ghost list in this hot code path, leave
2015 * this chore to the arc_reclaim_thread().
2016 */
2017
2018 return (stolen);
2019 }
2020
2021 /*
2022 * Remove buffers from list until we've removed the specified number of
2023 * bytes. Destroy the buffers that are removed.
2024 */
2025 static void
2026 arc_evict_ghost(arc_state_t *state, uint64_t spa, int64_t bytes,
2027 arc_buf_contents_t type)
2028 {
2029 arc_buf_hdr_t *ab, *ab_prev;
2030 arc_buf_hdr_t marker;
2031 list_t *list = &state->arcs_list[type];
2032 kmutex_t *hash_lock;
2033 uint64_t bytes_deleted = 0;
2034 uint64_t bufs_skipped = 0;
2035 int count = 0;
2036
2037 ASSERT(GHOST_STATE(state));
2038 bzero(&marker, sizeof (marker));
2039 top:
2040 mutex_enter(&state->arcs_mtx);
2041 for (ab = list_tail(list); ab; ab = ab_prev) {
2042 ab_prev = list_prev(list, ab);
2043 if (ab->b_type > ARC_BUFC_NUMTYPES)
2044 panic("invalid ab=%p", (void *)ab);
2045 if (spa && ab->b_spa != spa)
2046 continue;
2047
2048 /* ignore markers */
2049 if (ab->b_spa == 0)
2050 continue;
2051
2052 hash_lock = HDR_LOCK(ab);
2053 /* caller may be trying to modify this buffer, skip it */
2054 if (MUTEX_HELD(hash_lock))
2055 continue;
2056
2057 /*
2058 * It may take a long time to evict all the bufs requested.
2059 * To avoid blocking all arc activity, periodically drop
2060 * the arcs_mtx and give other threads a chance to run
2061 * before reacquiring the lock.
2062 */
2063 if (count++ > arc_evict_iterations) {
2064 list_insert_after(list, ab, &marker);
2065 mutex_exit(&state->arcs_mtx);
2066 kpreempt(KPREEMPT_SYNC);
2067 mutex_enter(&state->arcs_mtx);
2068 ab_prev = list_prev(list, &marker);
2069 list_remove(list, &marker);
2070 count = 0;
2071 continue;
2072 }
2073 if (mutex_tryenter(hash_lock)) {
2074 ASSERT(!HDR_IO_IN_PROGRESS(ab));
2075 ASSERT(ab->b_buf == NULL);
2076 ARCSTAT_BUMP(arcstat_deleted);
2077 bytes_deleted += ab->b_size;
2078
2079 if (ab->b_l2hdr != NULL) {
2080 /*
2081 * This buffer is cached on the 2nd Level ARC;
2082 * don't destroy the header.
2083 */
2084 arc_change_state(arc_l2c_only, ab, hash_lock);
2085 mutex_exit(hash_lock);
2086 } else {
2087 arc_change_state(arc_anon, ab, hash_lock);
2088 mutex_exit(hash_lock);
2089 arc_hdr_destroy(ab);
2090 }
2091
2092 DTRACE_PROBE1(arc__delete, arc_buf_hdr_t *, ab);
2093 if (bytes >= 0 && bytes_deleted >= bytes)
2094 break;
2095 } else if (bytes < 0) {
2096 /*
2097 * Insert a list marker and then wait for the
2098 * hash lock to become available. Once its
2099 * available, restart from where we left off.
2100 */
2101 list_insert_after(list, ab, &marker);
2102 mutex_exit(&state->arcs_mtx);
2103 mutex_enter(hash_lock);
2104 mutex_exit(hash_lock);
2105 mutex_enter(&state->arcs_mtx);
2106 ab_prev = list_prev(list, &marker);
2107 list_remove(list, &marker);
2108 } else {
2109 bufs_skipped += 1;
2110 }
2111 }
2112 mutex_exit(&state->arcs_mtx);
2113
2114 if (list == &state->arcs_list[ARC_BUFC_DATA] &&
2115 (bytes < 0 || bytes_deleted < bytes)) {
2116 list = &state->arcs_list[ARC_BUFC_METADATA];
2117 goto top;
2118 }
2119
2120 if (bufs_skipped) {
2121 ARCSTAT_INCR(arcstat_mutex_miss, bufs_skipped);
2122 ASSERT(bytes >= 0);
2123 }
2124
2125 if (bytes_deleted < bytes)
2126 dprintf("only deleted %lld bytes from %p\n",
2127 (longlong_t)bytes_deleted, state);
2128 }
2129
2130 static void
2131 arc_adjust(void)
2132 {
2133 int64_t adjustment, delta;
2134
2135 /*
2136 * Adjust MRU size
2137 */
2138
2139 adjustment = MIN((int64_t)(arc_size - arc_c),
2140 (int64_t)(arc_anon->arcs_size + arc_mru->arcs_size + arc_meta_used -
2141 arc_p));
2142
2143 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_DATA] > 0) {
2144 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_DATA], adjustment);
2145 (void) arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_DATA);
2146 adjustment -= delta;
2147 }
2148
2149 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2150 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2151 (void) arc_evict(arc_mru, 0, delta, FALSE,
2152 ARC_BUFC_METADATA);
2153 }
2154
2155 /*
2156 * Adjust MFU size
2157 */
2158
2159 adjustment = arc_size - arc_c;
2160
2161 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_DATA] > 0) {
2162 delta = MIN(adjustment, arc_mfu->arcs_lsize[ARC_BUFC_DATA]);
2163 (void) arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_DATA);
2164 adjustment -= delta;
2165 }
2166
2167 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2168 int64_t delta = MIN(adjustment,
2169 arc_mfu->arcs_lsize[ARC_BUFC_METADATA]);
2170 (void) arc_evict(arc_mfu, 0, delta, FALSE,
2171 ARC_BUFC_METADATA);
2172 }
2173
2174 /*
2175 * Adjust ghost lists
2176 */
2177
2178 adjustment = arc_mru->arcs_size + arc_mru_ghost->arcs_size - arc_c;
2179
2180 if (adjustment > 0 && arc_mru_ghost->arcs_size > 0) {
2181 delta = MIN(arc_mru_ghost->arcs_size, adjustment);
2182 arc_evict_ghost(arc_mru_ghost, 0, delta, ARC_BUFC_DATA);
2183 }
2184
2185 adjustment =
2186 arc_mru_ghost->arcs_size + arc_mfu_ghost->arcs_size - arc_c;
2187
2188 if (adjustment > 0 && arc_mfu_ghost->arcs_size > 0) {
2189 delta = MIN(arc_mfu_ghost->arcs_size, adjustment);
2190 arc_evict_ghost(arc_mfu_ghost, 0, delta, ARC_BUFC_DATA);
2191 }
2192 }
2193
2194 /*
2195 * Request that arc user drop references so that N bytes can be released
2196 * from the cache. This provides a mechanism to ensure the arc can honor
2197 * the arc_meta_limit and reclaim buffers which are pinned in the cache
2198 * by higher layers. (i.e. the zpl)
2199 */
2200 static void
2201 arc_do_user_prune(int64_t adjustment)
2202 {
2203 arc_prune_func_t *func;
2204 void *private;
2205 arc_prune_t *cp, *np;
2206
2207 mutex_enter(&arc_prune_mtx);
2208
2209 cp = list_head(&arc_prune_list);
2210 while (cp != NULL) {
2211 func = cp->p_pfunc;
2212 private = cp->p_private;
2213 np = list_next(&arc_prune_list, cp);
2214 refcount_add(&cp->p_refcnt, func);
2215 mutex_exit(&arc_prune_mtx);
2216
2217 if (func != NULL)
2218 func(adjustment, private);
2219
2220 mutex_enter(&arc_prune_mtx);
2221
2222 /* User removed prune callback concurrently with execution */
2223 if (refcount_remove(&cp->p_refcnt, func) == 0) {
2224 ASSERT(!list_link_active(&cp->p_node));
2225 refcount_destroy(&cp->p_refcnt);
2226 kmem_free(cp, sizeof (*cp));
2227 }
2228
2229 cp = np;
2230 }
2231
2232 ARCSTAT_BUMP(arcstat_prune);
2233 mutex_exit(&arc_prune_mtx);
2234 }
2235
2236 static void
2237 arc_do_user_evicts(void)
2238 {
2239 mutex_enter(&arc_eviction_mtx);
2240 while (arc_eviction_list != NULL) {
2241 arc_buf_t *buf = arc_eviction_list;
2242 arc_eviction_list = buf->b_next;
2243 mutex_enter(&buf->b_evict_lock);
2244 buf->b_hdr = NULL;
2245 mutex_exit(&buf->b_evict_lock);
2246 mutex_exit(&arc_eviction_mtx);
2247
2248 if (buf->b_efunc != NULL)
2249 VERIFY(buf->b_efunc(buf) == 0);
2250
2251 buf->b_efunc = NULL;
2252 buf->b_private = NULL;
2253 kmem_cache_free(buf_cache, buf);
2254 mutex_enter(&arc_eviction_mtx);
2255 }
2256 mutex_exit(&arc_eviction_mtx);
2257 }
2258
2259 /*
2260 * Evict only meta data objects from the cache leaving the data objects.
2261 * This is only used to enforce the tunable arc_meta_limit, if we are
2262 * unable to evict enough buffers notify the user via the prune callback.
2263 */
2264 void
2265 arc_adjust_meta(int64_t adjustment, boolean_t may_prune)
2266 {
2267 int64_t delta;
2268
2269 if (adjustment > 0 && arc_mru->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2270 delta = MIN(arc_mru->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2271 arc_evict(arc_mru, 0, delta, FALSE, ARC_BUFC_METADATA);
2272 adjustment -= delta;
2273 }
2274
2275 if (adjustment > 0 && arc_mfu->arcs_lsize[ARC_BUFC_METADATA] > 0) {
2276 delta = MIN(arc_mfu->arcs_lsize[ARC_BUFC_METADATA], adjustment);
2277 arc_evict(arc_mfu, 0, delta, FALSE, ARC_BUFC_METADATA);
2278 adjustment -= delta;
2279 }
2280
2281 if (may_prune && (adjustment > 0) && (arc_meta_used > arc_meta_limit))
2282 arc_do_user_prune(zfs_arc_meta_prune);
2283 }
2284
2285 /*
2286 * Flush all *evictable* data from the cache for the given spa.
2287 * NOTE: this will not touch "active" (i.e. referenced) data.
2288 */
2289 void
2290 arc_flush(spa_t *spa)
2291 {
2292 uint64_t guid = 0;
2293
2294 if (spa)
2295 guid = spa_load_guid(spa);
2296
2297 while (list_head(&arc_mru->arcs_list[ARC_BUFC_DATA])) {
2298 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
2299 if (spa)
2300 break;
2301 }
2302 while (list_head(&arc_mru->arcs_list[ARC_BUFC_METADATA])) {
2303 (void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_METADATA);
2304 if (spa)
2305 break;
2306 }
2307 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_DATA])) {
2308 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_DATA);
2309 if (spa)
2310 break;
2311 }
2312 while (list_head(&arc_mfu->arcs_list[ARC_BUFC_METADATA])) {
2313 (void) arc_evict(arc_mfu, guid, -1, FALSE, ARC_BUFC_METADATA);
2314 if (spa)
2315 break;
2316 }
2317
2318 arc_evict_ghost(arc_mru_ghost, guid, -1, ARC_BUFC_DATA);
2319 arc_evict_ghost(arc_mfu_ghost, guid, -1, ARC_BUFC_DATA);
2320
2321 mutex_enter(&arc_reclaim_thr_lock);
2322 arc_do_user_evicts();
2323 mutex_exit(&arc_reclaim_thr_lock);
2324 ASSERT(spa || arc_eviction_list == NULL);
2325 }
2326
2327 void
2328 arc_shrink(uint64_t bytes)
2329 {
2330 if (arc_c > arc_c_min) {
2331 uint64_t to_free;
2332
2333 to_free = bytes ? bytes : arc_c >> zfs_arc_shrink_shift;
2334
2335 if (arc_c > arc_c_min + to_free)
2336 atomic_add_64(&arc_c, -to_free);
2337 else
2338 arc_c = arc_c_min;
2339
2340 atomic_add_64(&arc_p, -(arc_p >> zfs_arc_shrink_shift));
2341 if (arc_c > arc_size)
2342 arc_c = MAX(arc_size, arc_c_min);
2343 if (arc_p > arc_c)
2344 arc_p = (arc_c >> 1);
2345 ASSERT(arc_c >= arc_c_min);
2346 ASSERT((int64_t)arc_p >= 0);
2347 }
2348
2349 if (arc_size > arc_c)
2350 arc_adjust();
2351 }
2352
2353 static void
2354 arc_kmem_reap_now(arc_reclaim_strategy_t strat, uint64_t bytes)
2355 {
2356 size_t i;
2357 kmem_cache_t *prev_cache = NULL;
2358 kmem_cache_t *prev_data_cache = NULL;
2359 extern kmem_cache_t *zio_buf_cache[];
2360 extern kmem_cache_t *zio_data_buf_cache[];
2361
2362 /*
2363 * An aggressive reclamation will shrink the cache size as well as
2364 * reap free buffers from the arc kmem caches.
2365 */
2366 if (strat == ARC_RECLAIM_AGGR)
2367 arc_shrink(bytes);
2368
2369 for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
2370 if (zio_buf_cache[i] != prev_cache) {
2371 prev_cache = zio_buf_cache[i];
2372 kmem_cache_reap_now(zio_buf_cache[i]);
2373 }
2374 if (zio_data_buf_cache[i] != prev_data_cache) {
2375 prev_data_cache = zio_data_buf_cache[i];
2376 kmem_cache_reap_now(zio_data_buf_cache[i]);
2377 }
2378 }
2379
2380 kmem_cache_reap_now(buf_cache);
2381 kmem_cache_reap_now(hdr_cache);
2382 }
2383
2384 /*
2385 * Unlike other ZFS implementations this thread is only responsible for
2386 * adapting the target ARC size on Linux. The responsibility for memory
2387 * reclamation has been entirely delegated to the arc_shrinker_func()
2388 * which is registered with the VM. To reflect this change in behavior
2389 * the arc_reclaim thread has been renamed to arc_adapt.
2390 */
2391 static void
2392 arc_adapt_thread(void)
2393 {
2394 callb_cpr_t cpr;
2395 int64_t prune;
2396
2397 CALLB_CPR_INIT(&cpr, &arc_reclaim_thr_lock, callb_generic_cpr, FTAG);
2398
2399 mutex_enter(&arc_reclaim_thr_lock);
2400 while (arc_thread_exit == 0) {
2401 #ifndef _KERNEL
2402 arc_reclaim_strategy_t last_reclaim = ARC_RECLAIM_CONS;
2403
2404 if (spa_get_random(100) == 0) {
2405
2406 if (arc_no_grow) {
2407 if (last_reclaim == ARC_RECLAIM_CONS) {
2408 last_reclaim = ARC_RECLAIM_AGGR;
2409 } else {
2410 last_reclaim = ARC_RECLAIM_CONS;
2411 }
2412 } else {
2413 arc_no_grow = TRUE;
2414 last_reclaim = ARC_RECLAIM_AGGR;
2415 membar_producer();
2416 }
2417
2418 /* reset the growth delay for every reclaim */
2419 arc_grow_time = ddi_get_lbolt() +
2420 (zfs_arc_grow_retry * hz);
2421
2422 arc_kmem_reap_now(last_reclaim, 0);
2423 arc_warm = B_TRUE;
2424 }
2425 #endif /* !_KERNEL */
2426
2427 /* No recent memory pressure allow the ARC to grow. */
2428 if (arc_no_grow && ddi_get_lbolt() >= arc_grow_time)
2429 arc_no_grow = FALSE;
2430
2431 /*
2432 * Keep meta data usage within limits, arc_shrink() is not
2433 * used to avoid collapsing the arc_c value when only the
2434 * arc_meta_limit is being exceeded.
2435 */
2436 prune = (int64_t)arc_meta_used - (int64_t)arc_meta_limit;
2437 if (prune > 0)
2438 arc_adjust_meta(prune, B_TRUE);
2439
2440 arc_adjust();
2441
2442 if (arc_eviction_list != NULL)
2443 arc_do_user_evicts();
2444
2445 /* block until needed, or one second, whichever is shorter */
2446 CALLB_CPR_SAFE_BEGIN(&cpr);
2447 (void) cv_timedwait_interruptible(&arc_reclaim_thr_cv,
2448 &arc_reclaim_thr_lock, (ddi_get_lbolt() + hz));
2449 CALLB_CPR_SAFE_END(&cpr, &arc_reclaim_thr_lock);
2450
2451
2452 /* Allow the module options to be changed */
2453 if (zfs_arc_max > 64 << 20 &&
2454 zfs_arc_max < physmem * PAGESIZE &&
2455 zfs_arc_max != arc_c_max)
2456 arc_c_max = zfs_arc_max;
2457
2458 if (zfs_arc_min > 0 &&
2459 zfs_arc_min < arc_c_max &&
2460 zfs_arc_min != arc_c_min)
2461 arc_c_min = zfs_arc_min;
2462
2463 if (zfs_arc_meta_limit > 0 &&
2464 zfs_arc_meta_limit <= arc_c_max &&
2465 zfs_arc_meta_limit != arc_meta_limit)
2466 arc_meta_limit = zfs_arc_meta_limit;
2467
2468
2469
2470 }
2471
2472 arc_thread_exit = 0;
2473 cv_broadcast(&arc_reclaim_thr_cv);
2474 CALLB_CPR_EXIT(&cpr); /* drops arc_reclaim_thr_lock */
2475 thread_exit();
2476 }
2477
2478 #ifdef _KERNEL
2479 /*
2480 * Determine the amount of memory eligible for eviction contained in the
2481 * ARC. All clean data reported by the ghost lists can always be safely
2482 * evicted. Due to arc_c_min, the same does not hold for all clean data
2483 * contained by the regular mru and mfu lists.
2484 *
2485 * In the case of the regular mru and mfu lists, we need to report as
2486 * much clean data as possible, such that evicting that same reported
2487 * data will not bring arc_size below arc_c_min. Thus, in certain
2488 * circumstances, the total amount of clean data in the mru and mfu
2489 * lists might not actually be evictable.
2490 *
2491 * The following two distinct cases are accounted for:
2492 *
2493 * 1. The sum of the amount of dirty data contained by both the mru and
2494 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2495 * is greater than or equal to arc_c_min.
2496 * (i.e. amount of dirty data >= arc_c_min)
2497 *
2498 * This is the easy case; all clean data contained by the mru and mfu
2499 * lists is evictable. Evicting all clean data can only drop arc_size
2500 * to the amount of dirty data, which is greater than arc_c_min.
2501 *
2502 * 2. The sum of the amount of dirty data contained by both the mru and
2503 * mfu lists, plus the ARC's other accounting (e.g. the anon list),
2504 * is less than arc_c_min.
2505 * (i.e. arc_c_min > amount of dirty data)
2506 *
2507 * 2.1. arc_size is greater than or equal arc_c_min.
2508 * (i.e. arc_size >= arc_c_min > amount of dirty data)
2509 *
2510 * In this case, not all clean data from the regular mru and mfu
2511 * lists is actually evictable; we must leave enough clean data
2512 * to keep arc_size above arc_c_min. Thus, the maximum amount of
2513 * evictable data from the two lists combined, is exactly the
2514 * difference between arc_size and arc_c_min.
2515 *
2516 * 2.2. arc_size is less than arc_c_min
2517 * (i.e. arc_c_min > arc_size > amount of dirty data)
2518 *
2519 * In this case, none of the data contained in the mru and mfu
2520 * lists is evictable, even if it's clean. Since arc_size is
2521 * already below arc_c_min, evicting any more would only
2522 * increase this negative difference.
2523 */
2524 static uint64_t
2525 arc_evictable_memory(void) {
2526 uint64_t arc_clean =
2527 arc_mru->arcs_lsize[ARC_BUFC_DATA] +
2528 arc_mru->arcs_lsize[ARC_BUFC_METADATA] +
2529 arc_mfu->arcs_lsize[ARC_BUFC_DATA] +
2530 arc_mfu->arcs_lsize[ARC_BUFC_METADATA];
2531 uint64_t ghost_clean =
2532 arc_mru_ghost->arcs_lsize[ARC_BUFC_DATA] +
2533 arc_mru_ghost->arcs_lsize[ARC_BUFC_METADATA] +
2534 arc_mfu_ghost->arcs_lsize[ARC_BUFC_DATA] +
2535 arc_mfu_ghost->arcs_lsize[ARC_BUFC_METADATA];
2536 uint64_t arc_dirty = MAX((int64_t)arc_size - (int64_t)arc_clean, 0);
2537
2538 if (arc_dirty >= arc_c_min)
2539 return (ghost_clean + arc_clean);
2540
2541 return (ghost_clean + MAX((int64_t)arc_size - (int64_t)arc_c_min, 0));
2542 }
2543
2544 static int
2545 __arc_shrinker_func(struct shrinker *shrink, struct shrink_control *sc)
2546 {
2547 uint64_t pages;
2548
2549 /* The arc is considered warm once reclaim has occurred */
2550 if (unlikely(arc_warm == B_FALSE))
2551 arc_warm = B_TRUE;
2552
2553 /* Return the potential number of reclaimable pages */
2554 pages = btop(arc_evictable_memory());
2555 if (sc->nr_to_scan == 0)
2556 return (pages);
2557
2558 /* Not allowed to perform filesystem reclaim */
2559 if (!(sc->gfp_mask & __GFP_FS))
2560 return (-1);
2561
2562 /* Reclaim in progress */
2563 if (mutex_tryenter(&arc_reclaim_thr_lock) == 0)
2564 return (-1);
2565
2566 /*
2567 * Evict the requested number of pages by shrinking arc_c the
2568 * requested amount. If there is nothing left to evict just
2569 * reap whatever we can from the various arc slabs.
2570 */
2571 if (pages > 0) {
2572 arc_kmem_reap_now(ARC_RECLAIM_AGGR, ptob(sc->nr_to_scan));
2573 } else {
2574 arc_kmem_reap_now(ARC_RECLAIM_CONS, ptob(sc->nr_to_scan));
2575 }
2576
2577 /*
2578 * When direct reclaim is observed it usually indicates a rapid
2579 * increase in memory pressure. This occurs because the kswapd
2580 * threads were unable to asynchronously keep enough free memory
2581 * available. In this case set arc_no_grow to briefly pause arc
2582 * growth to avoid compounding the memory pressure.
2583 */
2584 if (current_is_kswapd()) {
2585 ARCSTAT_BUMP(arcstat_memory_indirect_count);
2586 } else {
2587 arc_no_grow = B_TRUE;
2588 arc_grow_time = ddi_get_lbolt() + (zfs_arc_grow_retry * hz);
2589 ARCSTAT_BUMP(arcstat_memory_direct_count);
2590 }
2591
2592 mutex_exit(&arc_reclaim_thr_lock);
2593
2594 return (-1);
2595 }
2596 SPL_SHRINKER_CALLBACK_WRAPPER(arc_shrinker_func);
2597
2598 SPL_SHRINKER_DECLARE(arc_shrinker, arc_shrinker_func, DEFAULT_SEEKS);
2599 #endif /* _KERNEL */
2600
2601 /*
2602 * Adapt arc info given the number of bytes we are trying to add and
2603 * the state that we are comming from. This function is only called
2604 * when we are adding new content to the cache.
2605 */
2606 static void
2607 arc_adapt(int bytes, arc_state_t *state)
2608 {
2609 int mult;
2610 uint64_t arc_p_min = (arc_c >> zfs_arc_p_min_shift);
2611
2612 if (state == arc_l2c_only)
2613 return;
2614
2615 ASSERT(bytes > 0);
2616 /*
2617 * Adapt the target size of the MRU list:
2618 * - if we just hit in the MRU ghost list, then increase
2619 * the target size of the MRU list.
2620 * - if we just hit in the MFU ghost list, then increase
2621 * the target size of the MFU list by decreasing the
2622 * target size of the MRU list.
2623 */
2624 if (state == arc_mru_ghost) {
2625 mult = ((arc_mru_ghost->arcs_size >= arc_mfu_ghost->arcs_size) ?
2626 1 : (arc_mfu_ghost->arcs_size/arc_mru_ghost->arcs_size));
2627 mult = MIN(mult, 10); /* avoid wild arc_p adjustment */
2628
2629 arc_p = MIN(arc_c - arc_p_min, arc_p + bytes * mult);
2630 } else if (state == arc_mfu_ghost) {
2631 uint64_t delta;
2632
2633 mult = ((arc_mfu_ghost->arcs_size >= arc_mru_ghost->arcs_size) ?
2634 1 : (arc_mru_ghost->arcs_size/arc_mfu_ghost->arcs_size));
2635 mult = MIN(mult, 10);
2636
2637 delta = MIN(bytes * mult, arc_p);
2638 arc_p = MAX(arc_p_min, arc_p - delta);
2639 }
2640 ASSERT((int64_t)arc_p >= 0);
2641
2642 if (arc_no_grow)
2643 return;
2644
2645 if (arc_c >= arc_c_max)
2646 return;
2647
2648 /*
2649 * If we're within (2 * maxblocksize) bytes of the target
2650 * cache size, increment the target cache size
2651 */
2652 if (arc_size > arc_c - (2ULL << SPA_MAXBLOCKSHIFT)) {
2653 atomic_add_64(&arc_c, (int64_t)bytes);
2654 if (arc_c > arc_c_max)
2655 arc_c = arc_c_max;
2656 else if (state == arc_anon)
2657 atomic_add_64(&arc_p, (int64_t)bytes);
2658 if (arc_p > arc_c)
2659 arc_p = arc_c;
2660 }
2661 ASSERT((int64_t)arc_p >= 0);
2662 }
2663
2664 /*
2665 * Check if the cache has reached its limits and eviction is required
2666 * prior to insert.
2667 */
2668 static int
2669 arc_evict_needed(arc_buf_contents_t type)
2670 {
2671 if (type == ARC_BUFC_METADATA && arc_meta_used >= arc_meta_limit)
2672 return (1);
2673
2674 if (arc_no_grow)
2675 return (1);
2676
2677 return (arc_size > arc_c);
2678 }
2679
2680 /*
2681 * The buffer, supplied as the first argument, needs a data block.
2682 * So, if we are at cache max, determine which cache should be victimized.
2683 * We have the following cases:
2684 *
2685 * 1. Insert for MRU, p > sizeof(arc_anon + arc_mru) ->
2686 * In this situation if we're out of space, but the resident size of the MFU is
2687 * under the limit, victimize the MFU cache to satisfy this insertion request.
2688 *
2689 * 2. Insert for MRU, p <= sizeof(arc_anon + arc_mru) ->
2690 * Here, we've used up all of the available space for the MRU, so we need to
2691 * evict from our own cache instead. Evict from the set of resident MRU
2692 * entries.
2693 *
2694 * 3. Insert for MFU (c - p) > sizeof(arc_mfu) ->
2695 * c minus p represents the MFU space in the cache, since p is the size of the
2696 * cache that is dedicated to the MRU. In this situation there's still space on
2697 * the MFU side, so the MRU side needs to be victimized.
2698 *
2699 * 4. Insert for MFU (c - p) < sizeof(arc_mfu) ->
2700 * MFU's resident set is consuming more space than it has been allotted. In
2701 * this situation, we must victimize our own cache, the MFU, for this insertion.
2702 */
2703 static void
2704 arc_get_data_buf(arc_buf_t *buf)
2705 {
2706 arc_state_t *state = buf->b_hdr->b_state;
2707 uint64_t size = buf->b_hdr->b_size;
2708 arc_buf_contents_t type = buf->b_hdr->b_type;
2709
2710 arc_adapt(size, state);
2711
2712 /*
2713 * We have not yet reached cache maximum size,
2714 * just allocate a new buffer.
2715 */
2716 if (!arc_evict_needed(type)) {
2717 if (type == ARC_BUFC_METADATA) {
2718 buf->b_data = zio_buf_alloc(size);
2719 arc_space_consume(size, ARC_SPACE_DATA);
2720 } else {
2721 ASSERT(type == ARC_BUFC_DATA);
2722 buf->b_data = zio_data_buf_alloc(size);
2723 ARCSTAT_INCR(arcstat_data_size, size);
2724 atomic_add_64(&arc_size, size);
2725 }
2726 goto out;
2727 }
2728
2729 /*
2730 * If we are prefetching from the mfu ghost list, this buffer
2731 * will end up on the mru list; so steal space from there.
2732 */
2733 if (state == arc_mfu_ghost)
2734 state = buf->b_hdr->b_flags & ARC_PREFETCH ? arc_mru : arc_mfu;
2735 else if (state == arc_mru_ghost)
2736 state = arc_mru;
2737
2738 if (state == arc_mru || state == arc_anon) {
2739 uint64_t mru_used = arc_anon->arcs_size + arc_mru->arcs_size;
2740 state = (arc_mfu->arcs_lsize[type] >= size &&
2741 arc_p > mru_used) ? arc_mfu : arc_mru;
2742 } else {
2743 /* MFU cases */
2744 uint64_t mfu_space = arc_c - arc_p;
2745 state = (arc_mru->arcs_lsize[type] >= size &&
2746 mfu_space > arc_mfu->arcs_size) ? arc_mru : arc_mfu;
2747 }
2748
2749 if ((buf->b_data = arc_evict(state, 0, size, TRUE, type)) == NULL) {
2750 if (type == ARC_BUFC_METADATA) {
2751 buf->b_data = zio_buf_alloc(size);
2752 arc_space_consume(size, ARC_SPACE_DATA);
2753
2754 /*
2755 * If we are unable to recycle an existing meta buffer
2756 * signal the reclaim thread. It will notify users
2757 * via the prune callback to drop references. The
2758 * prune callback in run in the context of the reclaim
2759 * thread to avoid deadlocking on the hash_lock.
2760 */
2761 cv_signal(&arc_reclaim_thr_cv);
2762 } else {
2763 ASSERT(type == ARC_BUFC_DATA);
2764 buf->b_data = zio_data_buf_alloc(size);
2765 ARCSTAT_INCR(arcstat_data_size, size);
2766 atomic_add_64(&arc_size, size);
2767 }
2768
2769 ARCSTAT_BUMP(arcstat_recycle_miss);
2770 }
2771 ASSERT(buf->b_data != NULL);
2772 out:
2773 /*
2774 * Update the state size. Note that ghost states have a
2775 * "ghost size" and so don't need to be updated.
2776 */
2777 if (!GHOST_STATE(buf->b_hdr->b_state)) {
2778 arc_buf_hdr_t *hdr = buf->b_hdr;
2779
2780 atomic_add_64(&hdr->b_state->arcs_size, size);
2781 if (list_link_active(&hdr->b_arc_node)) {
2782 ASSERT(refcount_is_zero(&hdr->b_refcnt));
2783 atomic_add_64(&hdr->b_state->arcs_lsize[type], size);
2784 }
2785 /*
2786 * If we are growing the cache, and we are adding anonymous
2787 * data, and we have outgrown arc_p, update arc_p
2788 */
2789 if (arc_size < arc_c && hdr->b_state == arc_anon &&
2790 arc_anon->arcs_size + arc_mru->arcs_size > arc_p)
2791 arc_p = MIN(arc_c, arc_p + size);
2792 }
2793 }
2794
2795 /*
2796 * This routine is called whenever a buffer is accessed.
2797 * NOTE: the hash lock is dropped in this function.
2798 */
2799 static void
2800 arc_access(arc_buf_hdr_t *buf, kmutex_t *hash_lock)
2801 {
2802 clock_t now;
2803
2804 ASSERT(MUTEX_HELD(hash_lock));
2805
2806 if (buf->b_state == arc_anon) {
2807 /*
2808 * This buffer is not in the cache, and does not
2809 * appear in our "ghost" list. Add the new buffer
2810 * to the MRU state.
2811 */
2812
2813 ASSERT(buf->b_arc_access == 0);
2814 buf->b_arc_access = ddi_get_lbolt();
2815 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2816 arc_change_state(arc_mru, buf, hash_lock);
2817
2818 } else if (buf->b_state == arc_mru) {
2819 now = ddi_get_lbolt();
2820
2821 /*
2822 * If this buffer is here because of a prefetch, then either:
2823 * - clear the flag if this is a "referencing" read
2824 * (any subsequent access will bump this into the MFU state).
2825 * or
2826 * - move the buffer to the head of the list if this is
2827 * another prefetch (to make it less likely to be evicted).
2828 */
2829 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2830 if (refcount_count(&buf->b_refcnt) == 0) {
2831 ASSERT(list_link_active(&buf->b_arc_node));
2832 } else {
2833 buf->b_flags &= ~ARC_PREFETCH;
2834 atomic_inc_32(&buf->b_mru_hits);
2835 ARCSTAT_BUMP(arcstat_mru_hits);
2836 }
2837 buf->b_arc_access = now;
2838 return;
2839 }
2840
2841 /*
2842 * This buffer has been "accessed" only once so far,
2843 * but it is still in the cache. Move it to the MFU
2844 * state.
2845 */
2846 if (now > buf->b_arc_access + ARC_MINTIME) {
2847 /*
2848 * More than 125ms have passed since we
2849 * instantiated this buffer. Move it to the
2850 * most frequently used state.
2851 */
2852 buf->b_arc_access = now;
2853 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2854 arc_change_state(arc_mfu, buf, hash_lock);
2855 }
2856 atomic_inc_32(&buf->b_mru_hits);
2857 ARCSTAT_BUMP(arcstat_mru_hits);
2858 } else if (buf->b_state == arc_mru_ghost) {
2859 arc_state_t *new_state;
2860 /*
2861 * This buffer has been "accessed" recently, but
2862 * was evicted from the cache. Move it to the
2863 * MFU state.
2864 */
2865
2866 if (buf->b_flags & ARC_PREFETCH) {
2867 new_state = arc_mru;
2868 if (refcount_count(&buf->b_refcnt) > 0)
2869 buf->b_flags &= ~ARC_PREFETCH;
2870 DTRACE_PROBE1(new_state__mru, arc_buf_hdr_t *, buf);
2871 } else {
2872 new_state = arc_mfu;
2873 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2874 }
2875
2876 buf->b_arc_access = ddi_get_lbolt();
2877 arc_change_state(new_state, buf, hash_lock);
2878
2879 atomic_inc_32(&buf->b_mru_ghost_hits);
2880 ARCSTAT_BUMP(arcstat_mru_ghost_hits);
2881 } else if (buf->b_state == arc_mfu) {
2882 /*
2883 * This buffer has been accessed more than once and is
2884 * still in the cache. Keep it in the MFU state.
2885 *
2886 * NOTE: an add_reference() that occurred when we did
2887 * the arc_read() will have kicked this off the list.
2888 * If it was a prefetch, we will explicitly move it to
2889 * the head of the list now.
2890 */
2891 if ((buf->b_flags & ARC_PREFETCH) != 0) {
2892 ASSERT(refcount_count(&buf->b_refcnt) == 0);
2893 ASSERT(list_link_active(&buf->b_arc_node));
2894 }
2895 atomic_inc_32(&buf->b_mfu_hits);
2896 ARCSTAT_BUMP(arcstat_mfu_hits);
2897 buf->b_arc_access = ddi_get_lbolt();
2898 } else if (buf->b_state == arc_mfu_ghost) {
2899 arc_state_t *new_state = arc_mfu;
2900 /*
2901 * This buffer has been accessed more than once but has
2902 * been evicted from the cache. Move it back to the
2903 * MFU state.
2904 */
2905
2906 if (buf->b_flags & ARC_PREFETCH) {
2907 /*
2908 * This is a prefetch access...
2909 * move this block back to the MRU state.
2910 */
2911 ASSERT0(refcount_count(&buf->b_refcnt));
2912 new_state = arc_mru;
2913 }
2914
2915 buf->b_arc_access = ddi_get_lbolt();
2916 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2917 arc_change_state(new_state, buf, hash_lock);
2918
2919 atomic_inc_32(&buf->b_mfu_ghost_hits);
2920 ARCSTAT_BUMP(arcstat_mfu_ghost_hits);
2921 } else if (buf->b_state == arc_l2c_only) {
2922 /*
2923 * This buffer is on the 2nd Level ARC.
2924 */
2925
2926 buf->b_arc_access = ddi_get_lbolt();
2927 DTRACE_PROBE1(new_state__mfu, arc_buf_hdr_t *, buf);
2928 arc_change_state(arc_mfu, buf, hash_lock);
2929 } else {
2930 ASSERT(!"invalid arc state");
2931 }
2932 }
2933
2934 /* a generic arc_done_func_t which you can use */
2935 /* ARGSUSED */
2936 void
2937 arc_bcopy_func(zio_t *zio, arc_buf_t *buf, void *arg)
2938 {
2939 if (zio == NULL || zio->io_error == 0)
2940 bcopy(buf->b_data, arg, buf->b_hdr->b_size);
2941 VERIFY(arc_buf_remove_ref(buf, arg));
2942 }
2943
2944 /* a generic arc_done_func_t */
2945 void
2946 arc_getbuf_func(zio_t *zio, arc_buf_t *buf, void *arg)
2947 {
2948 arc_buf_t **bufp = arg;
2949 if (zio && zio->io_error) {
2950 VERIFY(arc_buf_remove_ref(buf, arg));
2951 *bufp = NULL;
2952 } else {
2953 *bufp = buf;
2954 ASSERT(buf->b_data);
2955 }
2956 }
2957
2958 static void
2959 arc_read_done(zio_t *zio)
2960 {
2961 arc_buf_hdr_t *hdr, *found;
2962 arc_buf_t *buf;
2963 arc_buf_t *abuf; /* buffer we're assigning to callback */
2964 kmutex_t *hash_lock;
2965 arc_callback_t *callback_list, *acb;
2966 int freeable = FALSE;
2967
2968 buf = zio->io_private;
2969 hdr = buf->b_hdr;
2970
2971 /*
2972 * The hdr was inserted into hash-table and removed from lists
2973 * prior to starting I/O. We should find this header, since
2974 * it's in the hash table, and it should be legit since it's
2975 * not possible to evict it during the I/O. The only possible
2976 * reason for it not to be found is if we were freed during the
2977 * read.
2978 */
2979 found = buf_hash_find(hdr->b_spa, &hdr->b_dva, hdr->b_birth,
2980 &hash_lock);
2981
2982 ASSERT((found == NULL && HDR_FREED_IN_READ(hdr) && hash_lock == NULL) ||
2983 (found == hdr && DVA_EQUAL(&hdr->b_dva, BP_IDENTITY(zio->io_bp))) ||
2984 (found == hdr && HDR_L2_READING(hdr)));
2985
2986 hdr->b_flags &= ~ARC_L2_EVICTED;
2987 if (l2arc_noprefetch && (hdr->b_flags & ARC_PREFETCH))
2988 hdr->b_flags &= ~ARC_L2CACHE;
2989
2990 /* byteswap if necessary */
2991 callback_list = hdr->b_acb;
2992 ASSERT(callback_list != NULL);
2993 if (BP_SHOULD_BYTESWAP(zio->io_bp) && zio->io_error == 0) {
2994 dmu_object_byteswap_t bswap =
2995 DMU_OT_BYTESWAP(BP_GET_TYPE(zio->io_bp));
2996 if (BP_GET_LEVEL(zio->io_bp) > 0)
2997 byteswap_uint64_array(buf->b_data, hdr->b_size);
2998 else
2999 dmu_ot_byteswap[bswap].ob_func(buf->b_data, hdr->b_size);
3000 }
3001
3002 arc_cksum_compute(buf, B_FALSE);
3003 arc_buf_watch(buf);
3004
3005 if (hash_lock && zio->io_error == 0 && hdr->b_state == arc_anon) {
3006 /*
3007 * Only call arc_access on anonymous buffers. This is because
3008 * if we've issued an I/O for an evicted buffer, we've already
3009 * called arc_access (to prevent any simultaneous readers from
3010 * getting confused).
3011 */
3012 arc_access(hdr, hash_lock);
3013 }
3014
3015 /* create copies of the data buffer for the callers */
3016 abuf = buf;
3017 for (acb = callback_list; acb; acb = acb->acb_next) {
3018 if (acb->acb_done) {
3019 if (abuf == NULL) {
3020 ARCSTAT_BUMP(arcstat_duplicate_reads);
3021 abuf = arc_buf_clone(buf);
3022 }
3023 acb->acb_buf = abuf;
3024 abuf = NULL;
3025 }
3026 }
3027 hdr->b_acb = NULL;
3028 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3029 ASSERT(!HDR_BUF_AVAILABLE(hdr));
3030 if (abuf == buf) {
3031 ASSERT(buf->b_efunc == NULL);
3032 ASSERT(hdr->b_datacnt == 1);
3033 hdr->b_flags |= ARC_BUF_AVAILABLE;
3034 }
3035
3036 ASSERT(refcount_is_zero(&hdr->b_refcnt) || callback_list != NULL);
3037
3038 if (zio->io_error != 0) {
3039 hdr->b_flags |= ARC_IO_ERROR;
3040 if (hdr->b_state != arc_anon)
3041 arc_change_state(arc_anon, hdr, hash_lock);
3042 if (HDR_IN_HASH_TABLE(hdr))
3043 buf_hash_remove(hdr);
3044 freeable = refcount_is_zero(&hdr->b_refcnt);
3045 }
3046
3047 /*
3048 * Broadcast before we drop the hash_lock to avoid the possibility
3049 * that the hdr (and hence the cv) might be freed before we get to
3050 * the cv_broadcast().
3051 */
3052 cv_broadcast(&hdr->b_cv);
3053
3054 if (hash_lock) {
3055 mutex_exit(hash_lock);
3056 } else {
3057 /*
3058 * This block was freed while we waited for the read to
3059 * complete. It has been removed from the hash table and
3060 * moved to the anonymous state (so that it won't show up
3061 * in the cache).
3062 */
3063 ASSERT3P(hdr->b_state, ==, arc_anon);
3064 freeable = refcount_is_zero(&hdr->b_refcnt);
3065 }
3066
3067 /* execute each callback and free its structure */
3068 while ((acb = callback_list) != NULL) {
3069 if (acb->acb_done)
3070 acb->acb_done(zio, acb->acb_buf, acb->acb_private);
3071
3072 if (acb->acb_zio_dummy != NULL) {
3073 acb->acb_zio_dummy->io_error = zio->io_error;
3074 zio_nowait(acb->acb_zio_dummy);
3075 }
3076
3077 callback_list = acb->acb_next;
3078 kmem_free(acb, sizeof (arc_callback_t));
3079 }
3080
3081 if (freeable)
3082 arc_hdr_destroy(hdr);
3083 }
3084
3085 /*
3086 * "Read" the block at the specified DVA (in bp) via the
3087 * cache. If the block is found in the cache, invoke the provided
3088 * callback immediately and return. Note that the `zio' parameter
3089 * in the callback will be NULL in this case, since no IO was
3090 * required. If the block is not in the cache pass the read request
3091 * on to the spa with a substitute callback function, so that the
3092 * requested block will be added to the cache.
3093 *
3094 * If a read request arrives for a block that has a read in-progress,
3095 * either wait for the in-progress read to complete (and return the
3096 * results); or, if this is a read with a "done" func, add a record
3097 * to the read to invoke the "done" func when the read completes,
3098 * and return; or just return.
3099 *
3100 * arc_read_done() will invoke all the requested "done" functions
3101 * for readers of this block.
3102 */
3103 int
3104 arc_read(zio_t *pio, spa_t *spa, const blkptr_t *bp, arc_done_func_t *done,
3105 void *private, zio_priority_t priority, int zio_flags, uint32_t *arc_flags,
3106 const zbookmark_t *zb)
3107 {
3108 arc_buf_hdr_t *hdr;
3109 arc_buf_t *buf = NULL;
3110 kmutex_t *hash_lock;
3111 zio_t *rzio;
3112 uint64_t guid = spa_load_guid(spa);
3113 int rc = 0;
3114
3115 top:
3116 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3117 &hash_lock);
3118 if (hdr && hdr->b_datacnt > 0) {
3119
3120 *arc_flags |= ARC_CACHED;
3121
3122 if (HDR_IO_IN_PROGRESS(hdr)) {
3123
3124 if (*arc_flags & ARC_WAIT) {
3125 cv_wait(&hdr->b_cv, hash_lock);
3126 mutex_exit(hash_lock);
3127 goto top;
3128 }
3129 ASSERT(*arc_flags & ARC_NOWAIT);
3130
3131 if (done) {
3132 arc_callback_t *acb = NULL;
3133
3134 acb = kmem_zalloc(sizeof (arc_callback_t),
3135 KM_PUSHPAGE);
3136 acb->acb_done = done;
3137 acb->acb_private = private;
3138 if (pio != NULL)
3139 acb->acb_zio_dummy = zio_null(pio,
3140 spa, NULL, NULL, NULL, zio_flags);
3141
3142 ASSERT(acb->acb_done != NULL);
3143 acb->acb_next = hdr->b_acb;
3144 hdr->b_acb = acb;
3145 add_reference(hdr, hash_lock, private);
3146 mutex_exit(hash_lock);
3147 goto out;
3148 }
3149 mutex_exit(hash_lock);
3150 goto out;
3151 }
3152
3153 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3154
3155 if (done) {
3156 add_reference(hdr, hash_lock, private);
3157 /*
3158 * If this block is already in use, create a new
3159 * copy of the data so that we will be guaranteed
3160 * that arc_release() will always succeed.
3161 */
3162 buf = hdr->b_buf;
3163 ASSERT(buf);
3164 ASSERT(buf->b_data);
3165 if (HDR_BUF_AVAILABLE(hdr)) {
3166 ASSERT(buf->b_efunc == NULL);
3167 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3168 } else {
3169 buf = arc_buf_clone(buf);
3170 }
3171
3172 } else if (*arc_flags & ARC_PREFETCH &&
3173 refcount_count(&hdr->b_refcnt) == 0) {
3174 hdr->b_flags |= ARC_PREFETCH;
3175 }
3176 DTRACE_PROBE1(arc__hit, arc_buf_hdr_t *, hdr);
3177 arc_access(hdr, hash_lock);
3178 if (*arc_flags & ARC_L2CACHE)
3179 hdr->b_flags |= ARC_L2CACHE;
3180 if (*arc_flags & ARC_L2COMPRESS)
3181 hdr->b_flags |= ARC_L2COMPRESS;
3182 mutex_exit(hash_lock);
3183 ARCSTAT_BUMP(arcstat_hits);
3184 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3185 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3186 data, metadata, hits);
3187
3188 if (done)
3189 done(NULL, buf, private);
3190 } else {
3191 uint64_t size = BP_GET_LSIZE(bp);
3192 arc_callback_t *acb;
3193 vdev_t *vd = NULL;
3194 uint64_t addr = 0;
3195 boolean_t devw = B_FALSE;
3196
3197 if (hdr == NULL) {
3198 /* this block is not in the cache */
3199 arc_buf_hdr_t *exists;
3200 arc_buf_contents_t type = BP_GET_BUFC_TYPE(bp);
3201 buf = arc_buf_alloc(spa, size, private, type);
3202 hdr = buf->b_hdr;
3203 hdr->b_dva = *BP_IDENTITY(bp);
3204 hdr->b_birth = BP_PHYSICAL_BIRTH(bp);
3205 hdr->b_cksum0 = bp->blk_cksum.zc_word[0];
3206 exists = buf_hash_insert(hdr, &hash_lock);
3207 if (exists) {
3208 /* somebody beat us to the hash insert */
3209 mutex_exit(hash_lock);
3210 buf_discard_identity(hdr);
3211 (void) arc_buf_remove_ref(buf, private);
3212 goto top; /* restart the IO request */
3213 }
3214 /* if this is a prefetch, we don't have a reference */
3215 if (*arc_flags & ARC_PREFETCH) {
3216 (void) remove_reference(hdr, hash_lock,
3217 private);
3218 hdr->b_flags |= ARC_PREFETCH;
3219 }
3220 if (*arc_flags & ARC_L2CACHE)
3221 hdr->b_flags |= ARC_L2CACHE;
3222 if (*arc_flags & ARC_L2COMPRESS)
3223 hdr->b_flags |= ARC_L2COMPRESS;
3224 if (BP_GET_LEVEL(bp) > 0)
3225 hdr->b_flags |= ARC_INDIRECT;
3226 } else {
3227 /* this block is in the ghost cache */
3228 ASSERT(GHOST_STATE(hdr->b_state));
3229 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3230 ASSERT0(refcount_count(&hdr->b_refcnt));
3231 ASSERT(hdr->b_buf == NULL);
3232
3233 /* if this is a prefetch, we don't have a reference */
3234 if (*arc_flags & ARC_PREFETCH)
3235 hdr->b_flags |= ARC_PREFETCH;
3236 else
3237 add_reference(hdr, hash_lock, private);
3238 if (*arc_flags & ARC_L2CACHE)
3239 hdr->b_flags |= ARC_L2CACHE;
3240 if (*arc_flags & ARC_L2COMPRESS)
3241 hdr->b_flags |= ARC_L2COMPRESS;
3242 buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
3243 buf->b_hdr = hdr;
3244 buf->b_data = NULL;
3245 buf->b_efunc = NULL;
3246 buf->b_private = NULL;
3247 buf->b_next = NULL;
3248 hdr->b_buf = buf;
3249 ASSERT(hdr->b_datacnt == 0);
3250 hdr->b_datacnt = 1;
3251 arc_get_data_buf(buf);
3252 arc_access(hdr, hash_lock);
3253 }
3254
3255 ASSERT(!GHOST_STATE(hdr->b_state));
3256
3257 acb = kmem_zalloc(sizeof (arc_callback_t), KM_PUSHPAGE);
3258 acb->acb_done = done;
3259 acb->acb_private = private;
3260
3261 ASSERT(hdr->b_acb == NULL);
3262 hdr->b_acb = acb;
3263 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3264
3265 if (HDR_L2CACHE(hdr) && hdr->b_l2hdr != NULL &&
3266 (vd = hdr->b_l2hdr->b_dev->l2ad_vdev) != NULL) {
3267 devw = hdr->b_l2hdr->b_dev->l2ad_writing;
3268 addr = hdr->b_l2hdr->b_daddr;
3269 /*
3270 * Lock out device removal.
3271 */
3272 if (vdev_is_dead(vd) ||
3273 !spa_config_tryenter(spa, SCL_L2ARC, vd, RW_READER))
3274 vd = NULL;
3275 }
3276
3277 mutex_exit(hash_lock);
3278
3279 /*
3280 * At this point, we have a level 1 cache miss. Try again in
3281 * L2ARC if possible.
3282 */
3283 ASSERT3U(hdr->b_size, ==, size);
3284 DTRACE_PROBE4(arc__miss, arc_buf_hdr_t *, hdr, blkptr_t *, bp,
3285 uint64_t, size, zbookmark_t *, zb);
3286 ARCSTAT_BUMP(arcstat_misses);
3287 ARCSTAT_CONDSTAT(!(hdr->b_flags & ARC_PREFETCH),
3288 demand, prefetch, hdr->b_type != ARC_BUFC_METADATA,
3289 data, metadata, misses);
3290
3291 if (vd != NULL && l2arc_ndev != 0 && !(l2arc_norw && devw)) {
3292 /*
3293 * Read from the L2ARC if the following are true:
3294 * 1. The L2ARC vdev was previously cached.
3295 * 2. This buffer still has L2ARC metadata.
3296 * 3. This buffer isn't currently writing to the L2ARC.
3297 * 4. The L2ARC entry wasn't evicted, which may
3298 * also have invalidated the vdev.
3299 * 5. This isn't prefetch and l2arc_noprefetch is set.
3300 */
3301 if (hdr->b_l2hdr != NULL &&
3302 !HDR_L2_WRITING(hdr) && !HDR_L2_EVICTED(hdr) &&
3303 !(l2arc_noprefetch && HDR_PREFETCH(hdr))) {
3304 l2arc_read_callback_t *cb;
3305
3306 DTRACE_PROBE1(l2arc__hit, arc_buf_hdr_t *, hdr);
3307 ARCSTAT_BUMP(arcstat_l2_hits);
3308 atomic_inc_32(&hdr->b_l2hdr->b_hits);
3309
3310 cb = kmem_zalloc(sizeof (l2arc_read_callback_t),
3311 KM_PUSHPAGE);
3312 cb->l2rcb_buf = buf;
3313 cb->l2rcb_spa = spa;
3314 cb->l2rcb_bp = *bp;
3315 cb->l2rcb_zb = *zb;
3316 cb->l2rcb_flags = zio_flags;
3317 cb->l2rcb_compress = hdr->b_l2hdr->b_compress;
3318
3319 ASSERT(addr >= VDEV_LABEL_START_SIZE &&
3320 addr + size < vd->vdev_psize -
3321 VDEV_LABEL_END_SIZE);
3322
3323 /*
3324 * l2arc read. The SCL_L2ARC lock will be
3325 * released by l2arc_read_done().
3326 * Issue a null zio if the underlying buffer
3327 * was squashed to zero size by compression.
3328 */
3329 if (hdr->b_l2hdr->b_compress ==
3330 ZIO_COMPRESS_EMPTY) {
3331 rzio = zio_null(pio, spa, vd,
3332 l2arc_read_done, cb,
3333 zio_flags | ZIO_FLAG_DONT_CACHE |
3334 ZIO_FLAG_CANFAIL |
3335 ZIO_FLAG_DONT_PROPAGATE |
3336 ZIO_FLAG_DONT_RETRY);
3337 } else {
3338 rzio = zio_read_phys(pio, vd, addr,
3339 hdr->b_l2hdr->b_asize,
3340 buf->b_data, ZIO_CHECKSUM_OFF,
3341 l2arc_read_done, cb, priority,
3342 zio_flags | ZIO_FLAG_DONT_CACHE |
3343 ZIO_FLAG_CANFAIL |
3344 ZIO_FLAG_DONT_PROPAGATE |
3345 ZIO_FLAG_DONT_RETRY, B_FALSE);
3346 }
3347 DTRACE_PROBE2(l2arc__read, vdev_t *, vd,
3348 zio_t *, rzio);
3349 ARCSTAT_INCR(arcstat_l2_read_bytes,
3350 hdr->b_l2hdr->b_asize);
3351
3352 if (*arc_flags & ARC_NOWAIT) {
3353 zio_nowait(rzio);
3354 goto out;
3355 }
3356
3357 ASSERT(*arc_flags & ARC_WAIT);
3358 if (zio_wait(rzio) == 0)
3359 goto out;
3360
3361 /* l2arc read error; goto zio_read() */
3362 } else {
3363 DTRACE_PROBE1(l2arc__miss,
3364 arc_buf_hdr_t *, hdr);
3365 ARCSTAT_BUMP(arcstat_l2_misses);
3366 if (HDR_L2_WRITING(hdr))
3367 ARCSTAT_BUMP(arcstat_l2_rw_clash);
3368 spa_config_exit(spa, SCL_L2ARC, vd);
3369 }
3370 } else {
3371 if (vd != NULL)
3372 spa_config_exit(spa, SCL_L2ARC, vd);
3373 if (l2arc_ndev != 0) {
3374 DTRACE_PROBE1(l2arc__miss,
3375 arc_buf_hdr_t *, hdr);
3376 ARCSTAT_BUMP(arcstat_l2_misses);
3377 }
3378 }
3379
3380 rzio = zio_read(pio, spa, bp, buf->b_data, size,
3381 arc_read_done, buf, priority, zio_flags, zb);
3382
3383 if (*arc_flags & ARC_WAIT) {
3384 rc = zio_wait(rzio);
3385 goto out;
3386 }
3387
3388 ASSERT(*arc_flags & ARC_NOWAIT);
3389 zio_nowait(rzio);
3390 }
3391
3392 out:
3393 spa_read_history_add(spa, zb, *arc_flags);
3394 return (rc);
3395 }
3396
3397 arc_prune_t *
3398 arc_add_prune_callback(arc_prune_func_t *func, void *private)
3399 {
3400 arc_prune_t *p;
3401
3402 p = kmem_alloc(sizeof (*p), KM_SLEEP);
3403 p->p_pfunc = func;
3404 p->p_private = private;
3405 list_link_init(&p->p_node);
3406 refcount_create(&p->p_refcnt);
3407
3408 mutex_enter(&arc_prune_mtx);
3409 refcount_add(&p->p_refcnt, &arc_prune_list);
3410 list_insert_head(&arc_prune_list, p);
3411 mutex_exit(&arc_prune_mtx);
3412
3413 return (p);
3414 }
3415
3416 void
3417 arc_remove_prune_callback(arc_prune_t *p)
3418 {
3419 mutex_enter(&arc_prune_mtx);
3420 list_remove(&arc_prune_list, p);
3421 if (refcount_remove(&p->p_refcnt, &arc_prune_list) == 0) {
3422 refcount_destroy(&p->p_refcnt);
3423 kmem_free(p, sizeof (*p));
3424 }
3425 mutex_exit(&arc_prune_mtx);
3426 }
3427
3428 void
3429 arc_set_callback(arc_buf_t *buf, arc_evict_func_t *func, void *private)
3430 {
3431 ASSERT(buf->b_hdr != NULL);
3432 ASSERT(buf->b_hdr->b_state != arc_anon);
3433 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt) || func == NULL);
3434 ASSERT(buf->b_efunc == NULL);
3435 ASSERT(!HDR_BUF_AVAILABLE(buf->b_hdr));
3436
3437 buf->b_efunc = func;
3438 buf->b_private = private;
3439 }
3440
3441 /*
3442 * Notify the arc that a block was freed, and thus will never be used again.
3443 */
3444 void
3445 arc_freed(spa_t *spa, const blkptr_t *bp)
3446 {
3447 arc_buf_hdr_t *hdr;
3448 kmutex_t *hash_lock;
3449 uint64_t guid = spa_load_guid(spa);
3450
3451 hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
3452 &hash_lock);
3453 if (hdr == NULL)
3454 return;
3455 if (HDR_BUF_AVAILABLE(hdr)) {
3456 arc_buf_t *buf = hdr->b_buf;
3457 add_reference(hdr, hash_lock, FTAG);
3458 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3459 mutex_exit(hash_lock);
3460
3461 arc_release(buf, FTAG);
3462 (void) arc_buf_remove_ref(buf, FTAG);
3463 } else {
3464 mutex_exit(hash_lock);
3465 }
3466
3467 }
3468
3469 /*
3470 * This is used by the DMU to let the ARC know that a buffer is
3471 * being evicted, so the ARC should clean up. If this arc buf
3472 * is not yet in the evicted state, it will be put there.
3473 */
3474 int
3475 arc_buf_evict(arc_buf_t *buf)
3476 {
3477 arc_buf_hdr_t *hdr;
3478 kmutex_t *hash_lock;
3479 arc_buf_t **bufp;
3480
3481 mutex_enter(&buf->b_evict_lock);
3482 hdr = buf->b_hdr;
3483 if (hdr == NULL) {
3484 /*
3485 * We are in arc_do_user_evicts().
3486 */
3487 ASSERT(buf->b_data == NULL);
3488 mutex_exit(&buf->b_evict_lock);
3489 return (0);
3490 } else if (buf->b_data == NULL) {
3491 arc_buf_t copy = *buf; /* structure assignment */
3492 /*
3493 * We are on the eviction list; process this buffer now
3494 * but let arc_do_user_evicts() do the reaping.
3495 */
3496 buf->b_efunc = NULL;
3497 mutex_exit(&buf->b_evict_lock);
3498 VERIFY(copy.b_efunc(&copy) == 0);
3499 return (1);
3500 }
3501 hash_lock = HDR_LOCK(hdr);
3502 mutex_enter(hash_lock);
3503 hdr = buf->b_hdr;
3504 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3505
3506 ASSERT3U(refcount_count(&hdr->b_refcnt), <, hdr->b_datacnt);
3507 ASSERT(hdr->b_state == arc_mru || hdr->b_state == arc_mfu);
3508
3509 /*
3510 * Pull this buffer off of the hdr
3511 */
3512 bufp = &hdr->b_buf;
3513 while (*bufp != buf)
3514 bufp = &(*bufp)->b_next;
3515 *bufp = buf->b_next;
3516
3517 ASSERT(buf->b_data != NULL);
3518 arc_buf_destroy(buf, FALSE, FALSE);
3519
3520 if (hdr->b_datacnt == 0) {
3521 arc_state_t *old_state = hdr->b_state;
3522 arc_state_t *evicted_state;
3523
3524 ASSERT(hdr->b_buf == NULL);
3525 ASSERT(refcount_is_zero(&hdr->b_refcnt));
3526
3527 evicted_state =
3528 (old_state == arc_mru) ? arc_mru_ghost : arc_mfu_ghost;
3529
3530 mutex_enter(&old_state->arcs_mtx);
3531 mutex_enter(&evicted_state->arcs_mtx);
3532
3533 arc_change_state(evicted_state, hdr, hash_lock);
3534 ASSERT(HDR_IN_HASH_TABLE(hdr));
3535 hdr->b_flags |= ARC_IN_HASH_TABLE;
3536 hdr->b_flags &= ~ARC_BUF_AVAILABLE;
3537
3538 mutex_exit(&evicted_state->arcs_mtx);
3539 mutex_exit(&old_state->arcs_mtx);
3540 }
3541 mutex_exit(hash_lock);
3542 mutex_exit(&buf->b_evict_lock);
3543
3544 VERIFY(buf->b_efunc(buf) == 0);
3545 buf->b_efunc = NULL;
3546 buf->b_private = NULL;
3547 buf->b_hdr = NULL;
3548 buf->b_next = NULL;
3549 kmem_cache_free(buf_cache, buf);
3550 return (1);
3551 }
3552
3553 /*
3554 * Release this buffer from the cache, making it an anonymous buffer. This
3555 * must be done after a read and prior to modifying the buffer contents.
3556 * If the buffer has more than one reference, we must make
3557 * a new hdr for the buffer.
3558 */
3559 void
3560 arc_release(arc_buf_t *buf, void *tag)
3561 {
3562 arc_buf_hdr_t *hdr;
3563 kmutex_t *hash_lock = NULL;
3564 l2arc_buf_hdr_t *l2hdr;
3565 uint64_t buf_size = 0;
3566
3567 /*
3568 * It would be nice to assert that if it's DMU metadata (level >
3569 * 0 || it's the dnode file), then it must be syncing context.
3570 * But we don't know that information at this level.
3571 */
3572
3573 mutex_enter(&buf->b_evict_lock);
3574 hdr = buf->b_hdr;
3575
3576 /* this buffer is not on any list */
3577 ASSERT(refcount_count(&hdr->b_refcnt) > 0);
3578
3579 if (hdr->b_state == arc_anon) {
3580 /* this buffer is already released */
3581 ASSERT(buf->b_efunc == NULL);
3582 } else {
3583 hash_lock = HDR_LOCK(hdr);
3584 mutex_enter(hash_lock);
3585 hdr = buf->b_hdr;
3586 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
3587 }
3588
3589 l2hdr = hdr->b_l2hdr;
3590 if (l2hdr) {
3591 mutex_enter(&l2arc_buflist_mtx);
3592 hdr->b_l2hdr = NULL;
3593 }
3594 buf_size = hdr->b_size;
3595
3596 /*
3597 * Do we have more than one buf?
3598 */
3599 if (hdr->b_datacnt > 1) {
3600 arc_buf_hdr_t *nhdr;
3601 arc_buf_t **bufp;
3602 uint64_t blksz = hdr->b_size;
3603 uint64_t spa = hdr->b_spa;
3604 arc_buf_contents_t type = hdr->b_type;
3605 uint32_t flags = hdr->b_flags;
3606
3607 ASSERT(hdr->b_buf != buf || buf->b_next != NULL);
3608 /*
3609 * Pull the data off of this hdr and attach it to
3610 * a new anonymous hdr.
3611 */
3612 (void) remove_reference(hdr, hash_lock, tag);
3613 bufp = &hdr->b_buf;
3614 while (*bufp != buf)
3615 bufp = &(*bufp)->b_next;
3616 *bufp = buf->b_next;
3617 buf->b_next = NULL;
3618
3619 ASSERT3U(hdr->b_state->arcs_size, >=, hdr->b_size);
3620 atomic_add_64(&hdr->b_state->arcs_size, -hdr->b_size);
3621 if (refcount_is_zero(&hdr->b_refcnt)) {
3622 uint64_t *size = &hdr->b_state->arcs_lsize[hdr->b_type];
3623 ASSERT3U(*size, >=, hdr->b_size);
3624 atomic_add_64(size, -hdr->b_size);
3625 }
3626
3627 /*
3628 * We're releasing a duplicate user data buffer, update
3629 * our statistics accordingly.
3630 */
3631 if (hdr->b_type == ARC_BUFC_DATA) {
3632 ARCSTAT_BUMPDOWN(arcstat_duplicate_buffers);
3633 ARCSTAT_INCR(arcstat_duplicate_buffers_size,
3634 -hdr->b_size);
3635 }
3636 hdr->b_datacnt -= 1;
3637 arc_cksum_verify(buf);
3638 arc_buf_unwatch(buf);
3639
3640 mutex_exit(hash_lock);
3641
3642 nhdr = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
3643 nhdr->b_size = blksz;
3644 nhdr->b_spa = spa;
3645 nhdr->b_type = type;
3646 nhdr->b_buf = buf;
3647 nhdr->b_state = arc_anon;
3648 nhdr->b_arc_access = 0;
3649 nhdr->b_mru_hits = 0;
3650 nhdr->b_mru_ghost_hits = 0;
3651 nhdr->b_mfu_hits = 0;
3652 nhdr->b_mfu_ghost_hits = 0;
3653 nhdr->b_l2_hits = 0;
3654 nhdr->b_flags = flags & ARC_L2_WRITING;
3655 nhdr->b_l2hdr = NULL;
3656 nhdr->b_datacnt = 1;
3657 nhdr->b_freeze_cksum = NULL;
3658 (void) refcount_add(&nhdr->b_refcnt, tag);
3659 buf->b_hdr = nhdr;
3660 mutex_exit(&buf->b_evict_lock);
3661 atomic_add_64(&arc_anon->arcs_size, blksz);
3662 } else {
3663 mutex_exit(&buf->b_evict_lock);
3664 ASSERT(refcount_count(&hdr->b_refcnt) == 1);
3665 ASSERT(!list_link_active(&hdr->b_arc_node));
3666 ASSERT(!HDR_IO_IN_PROGRESS(hdr));
3667 if (hdr->b_state != arc_anon)
3668 arc_change_state(arc_anon, hdr, hash_lock);
3669 hdr->b_arc_access = 0;
3670 hdr->b_mru_hits = 0;
3671 hdr->b_mru_ghost_hits = 0;
3672 hdr->b_mfu_hits = 0;
3673 hdr->b_mfu_ghost_hits = 0;
3674 hdr->b_l2_hits = 0;
3675 if (hash_lock)
3676 mutex_exit(hash_lock);
3677
3678 buf_discard_identity(hdr);
3679 arc_buf_thaw(buf);
3680 }
3681 buf->b_efunc = NULL;
3682 buf->b_private = NULL;
3683
3684 if (l2hdr) {
3685 ARCSTAT_INCR(arcstat_l2_asize, -l2hdr->b_asize);
3686 list_remove(l2hdr->b_dev->l2ad_buflist, hdr);
3687 kmem_free(l2hdr, sizeof (l2arc_buf_hdr_t));
3688 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
3689 ARCSTAT_INCR(arcstat_l2_size, -buf_size);
3690 mutex_exit(&l2arc_buflist_mtx);
3691 }
3692 }
3693
3694 int
3695 arc_released(arc_buf_t *buf)
3696 {
3697 int released;
3698
3699 mutex_enter(&buf->b_evict_lock);
3700 released = (buf->b_data != NULL && buf->b_hdr->b_state == arc_anon);
3701 mutex_exit(&buf->b_evict_lock);
3702 return (released);
3703 }
3704
3705 int
3706 arc_has_callback(arc_buf_t *buf)
3707 {
3708 int callback;
3709
3710 mutex_enter(&buf->b_evict_lock);
3711 callback = (buf->b_efunc != NULL);
3712 mutex_exit(&buf->b_evict_lock);
3713 return (callback);
3714 }
3715
3716 #ifdef ZFS_DEBUG
3717 int
3718 arc_referenced(arc_buf_t *buf)
3719 {
3720 int referenced;
3721
3722 mutex_enter(&buf->b_evict_lock);
3723 referenced = (refcount_count(&buf->b_hdr->b_refcnt));
3724 mutex_exit(&buf->b_evict_lock);
3725 return (referenced);
3726 }
3727 #endif
3728
3729 static void
3730 arc_write_ready(zio_t *zio)
3731 {
3732 arc_write_callback_t *callback = zio->io_private;
3733 arc_buf_t *buf = callback->awcb_buf;
3734 arc_buf_hdr_t *hdr = buf->b_hdr;
3735
3736 ASSERT(!refcount_is_zero(&buf->b_hdr->b_refcnt));
3737 callback->awcb_ready(zio, buf, callback->awcb_private);
3738
3739 /*
3740 * If the IO is already in progress, then this is a re-write
3741 * attempt, so we need to thaw and re-compute the cksum.
3742 * It is the responsibility of the callback to handle the
3743 * accounting for any re-write attempt.
3744 */
3745 if (HDR_IO_IN_PROGRESS(hdr)) {
3746 mutex_enter(&hdr->b_freeze_lock);
3747 if (hdr->b_freeze_cksum != NULL) {
3748 kmem_free(hdr->b_freeze_cksum, sizeof (zio_cksum_t));
3749 hdr->b_freeze_cksum = NULL;
3750 }
3751 mutex_exit(&hdr->b_freeze_lock);
3752 }
3753 arc_cksum_compute(buf, B_FALSE);
3754 hdr->b_flags |= ARC_IO_IN_PROGRESS;
3755 }
3756
3757 /*
3758 * The SPA calls this callback for each physical write that happens on behalf
3759 * of a logical write. See the comment in dbuf_write_physdone() for details.
3760 */
3761 static void
3762 arc_write_physdone(zio_t *zio)
3763 {
3764 arc_write_callback_t *cb = zio->io_private;
3765 if (cb->awcb_physdone != NULL)
3766 cb->awcb_physdone(zio, cb->awcb_buf, cb->awcb_private);
3767 }
3768
3769 static void
3770 arc_write_done(zio_t *zio)
3771 {
3772 arc_write_callback_t *callback = zio->io_private;
3773 arc_buf_t *buf = callback->awcb_buf;
3774 arc_buf_hdr_t *hdr = buf->b_hdr;
3775
3776 ASSERT(hdr->b_acb == NULL);
3777
3778 if (zio->io_error == 0) {
3779 hdr->b_dva = *BP_IDENTITY(zio->io_bp);
3780 hdr->b_birth = BP_PHYSICAL_BIRTH(zio->io_bp);
3781 hdr->b_cksum0 = zio->io_bp->blk_cksum.zc_word[0];
3782 } else {
3783 ASSERT(BUF_EMPTY(hdr));
3784 }
3785
3786 /*
3787 * If the block to be written was all-zero, we may have
3788 * compressed it away. In this case no write was performed
3789 * so there will be no dva/birth/checksum. The buffer must
3790 * therefore remain anonymous (and uncached).
3791 */
3792 if (!BUF_EMPTY(hdr)) {
3793 arc_buf_hdr_t *exists;
3794 kmutex_t *hash_lock;
3795
3796 ASSERT(zio->io_error == 0);
3797
3798 arc_cksum_verify(buf);
3799
3800 exists = buf_hash_insert(hdr, &hash_lock);
3801 if (exists) {
3802 /*
3803 * This can only happen if we overwrite for
3804 * sync-to-convergence, because we remove
3805 * buffers from the hash table when we arc_free().
3806 */
3807 if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
3808 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3809 panic("bad overwrite, hdr=%p exists=%p",
3810 (void *)hdr, (void *)exists);
3811 ASSERT(refcount_is_zero(&exists->b_refcnt));
3812 arc_change_state(arc_anon, exists, hash_lock);
3813 mutex_exit(hash_lock);
3814 arc_hdr_destroy(exists);
3815 exists = buf_hash_insert(hdr, &hash_lock);
3816 ASSERT3P(exists, ==, NULL);
3817 } else if (zio->io_flags & ZIO_FLAG_NOPWRITE) {
3818 /* nopwrite */
3819 ASSERT(zio->io_prop.zp_nopwrite);
3820 if (!BP_EQUAL(&zio->io_bp_orig, zio->io_bp))
3821 panic("bad nopwrite, hdr=%p exists=%p",
3822 (void *)hdr, (void *)exists);
3823 } else {
3824 /* Dedup */
3825 ASSERT(hdr->b_datacnt == 1);
3826 ASSERT(hdr->b_state == arc_anon);
3827 ASSERT(BP_GET_DEDUP(zio->io_bp));
3828 ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
3829 }
3830 }
3831 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3832 /* if it's not anon, we are doing a scrub */
3833 if (!exists && hdr->b_state == arc_anon)
3834 arc_access(hdr, hash_lock);
3835 mutex_exit(hash_lock);
3836 } else {
3837 hdr->b_flags &= ~ARC_IO_IN_PROGRESS;
3838 }
3839
3840 ASSERT(!refcount_is_zero(&hdr->b_refcnt));
3841 callback->awcb_done(zio, buf, callback->awcb_private);
3842
3843 kmem_free(callback, sizeof (arc_write_callback_t));
3844 }
3845
3846 zio_t *
3847 arc_write(zio_t *pio, spa_t *spa, uint64_t txg,
3848 blkptr_t *bp, arc_buf_t *buf, boolean_t l2arc, boolean_t l2arc_compress,
3849 const zio_prop_t *zp, arc_done_func_t *ready, arc_done_func_t *physdone,
3850 arc_done_func_t *done, void *private, zio_priority_t priority,
3851 int zio_flags, const zbookmark_t *zb)
3852 {
3853 arc_buf_hdr_t *hdr = buf->b_hdr;
3854 arc_write_callback_t *callback;
3855 zio_t *zio;
3856
3857 ASSERT(ready != NULL);
3858 ASSERT(done != NULL);
3859 ASSERT(!HDR_IO_ERROR(hdr));
3860 ASSERT((hdr->b_flags & ARC_IO_IN_PROGRESS) == 0);
3861 ASSERT(hdr->b_acb == NULL);
3862 if (l2arc)
3863 hdr->b_flags |= ARC_L2CACHE;
3864 if (l2arc_compress)
3865 hdr->b_flags |= ARC_L2COMPRESS;
3866 callback = kmem_zalloc(sizeof (arc_write_callback_t), KM_PUSHPAGE);
3867 callback->awcb_ready = ready;
3868 callback->awcb_physdone = physdone;
3869 callback->awcb_done = done;
3870 callback->awcb_private = private;
3871 callback->awcb_buf = buf;
3872
3873 zio = zio_write(pio, spa, txg, bp, buf->b_data, hdr->b_size, zp,
3874 arc_write_ready, arc_write_physdone, arc_write_done, callback,
3875 priority, zio_flags, zb);
3876
3877 return (zio);
3878 }
3879
3880 static int
3881 arc_memory_throttle(uint64_t reserve, uint64_t txg)
3882 {
3883 #ifdef _KERNEL
3884 if (zfs_arc_memory_throttle_disable)
3885 return (0);
3886
3887 if (freemem <= physmem * arc_lotsfree_percent / 100) {
3888 ARCSTAT_INCR(arcstat_memory_throttle_count, 1);
3889 DMU_TX_STAT_BUMP(dmu_tx_memory_reclaim);
3890 return (SET_ERROR(EAGAIN));
3891 }
3892 #endif
3893 return (0);
3894 }
3895
3896 void
3897 arc_tempreserve_clear(uint64_t reserve)
3898 {
3899 atomic_add_64(&arc_tempreserve, -reserve);
3900 ASSERT((int64_t)arc_tempreserve >= 0);
3901 }
3902
3903 int
3904 arc_tempreserve_space(uint64_t reserve, uint64_t txg)
3905 {
3906 int error;
3907 uint64_t anon_size;
3908
3909 if (reserve > arc_c/4 && !arc_no_grow)
3910 arc_c = MIN(arc_c_max, reserve * 4);
3911 if (reserve > arc_c) {
3912 DMU_TX_STAT_BUMP(dmu_tx_memory_reserve);
3913 return (SET_ERROR(ENOMEM));
3914 }
3915
3916 /*
3917 * Don't count loaned bufs as in flight dirty data to prevent long
3918 * network delays from blocking transactions that are ready to be
3919 * assigned to a txg.
3920 */
3921 anon_size = MAX((int64_t)(arc_anon->arcs_size - arc_loaned_bytes), 0);
3922
3923 /*
3924 * Writes will, almost always, require additional memory allocations
3925 * in order to compress/encrypt/etc the data. We therefore need to
3926 * make sure that there is sufficient available memory for this.
3927 */
3928 error = arc_memory_throttle(reserve, txg);
3929 if (error != 0)
3930 return (error);
3931
3932 /*
3933 * Throttle writes when the amount of dirty data in the cache
3934 * gets too large. We try to keep the cache less than half full
3935 * of dirty blocks so that our sync times don't grow too large.
3936 * Note: if two requests come in concurrently, we might let them
3937 * both succeed, when one of them should fail. Not a huge deal.
3938 */
3939
3940 if (reserve + arc_tempreserve + anon_size > arc_c / 2 &&
3941 anon_size > arc_c / 4) {
3942 dprintf("failing, arc_tempreserve=%lluK anon_meta=%lluK "
3943 "anon_data=%lluK tempreserve=%lluK arc_c=%lluK\n",
3944 arc_tempreserve>>10,
3945 arc_anon->arcs_lsize[ARC_BUFC_METADATA]>>10,
3946 arc_anon->arcs_lsize[ARC_BUFC_DATA]>>10,
3947 reserve>>10, arc_c>>10);
3948 DMU_TX_STAT_BUMP(dmu_tx_dirty_throttle);
3949 return (SET_ERROR(ERESTART));
3950 }
3951 atomic_add_64(&arc_tempreserve, reserve);
3952 return (0);
3953 }
3954
3955 static void
3956 arc_kstat_update_state(arc_state_t *state, kstat_named_t *size,
3957 kstat_named_t *evict_data, kstat_named_t *evict_metadata)
3958 {
3959 size->value.ui64 = state->arcs_size;
3960 evict_data->value.ui64 = state->arcs_lsize[ARC_BUFC_DATA];
3961 evict_metadata->value.ui64 = state->arcs_lsize[ARC_BUFC_METADATA];
3962 }
3963
3964 static int
3965 arc_kstat_update(kstat_t *ksp, int rw)
3966 {
3967 arc_stats_t *as = ksp->ks_data;
3968
3969 if (rw == KSTAT_WRITE) {
3970 return (SET_ERROR(EACCES));
3971 } else {
3972 arc_kstat_update_state(arc_anon,
3973 &as->arcstat_anon_size,
3974 &as->arcstat_anon_evict_data,
3975 &as->arcstat_anon_evict_metadata);
3976 arc_kstat_update_state(arc_mru,
3977 &as->arcstat_mru_size,
3978 &as->arcstat_mru_evict_data,
3979 &as->arcstat_mru_evict_metadata);
3980 arc_kstat_update_state(arc_mru_ghost,
3981 &as->arcstat_mru_ghost_size,
3982 &as->arcstat_mru_ghost_evict_data,
3983 &as->arcstat_mru_ghost_evict_metadata);
3984 arc_kstat_update_state(arc_mfu,
3985 &as->arcstat_mfu_size,
3986 &as->arcstat_mfu_evict_data,
3987 &as->arcstat_mfu_evict_metadata);
3988 arc_kstat_update_state(arc_mfu_ghost,
3989 &as->arcstat_mfu_ghost_size,
3990 &as->arcstat_mfu_ghost_evict_data,
3991 &as->arcstat_mfu_ghost_evict_metadata);
3992 }
3993
3994 return (0);
3995 }
3996
3997 void
3998 arc_init(void)
3999 {
4000 mutex_init(&arc_reclaim_thr_lock, NULL, MUTEX_DEFAULT, NULL);
4001 cv_init(&arc_reclaim_thr_cv, NULL, CV_DEFAULT, NULL);
4002
4003 /* Convert seconds to clock ticks */
4004 zfs_arc_min_prefetch_lifespan = 1 * hz;
4005
4006 /* Start out with 1/8 of all memory */
4007 arc_c = physmem * PAGESIZE / 8;
4008
4009 #ifdef _KERNEL
4010 /*
4011 * On architectures where the physical memory can be larger
4012 * than the addressable space (intel in 32-bit mode), we may
4013 * need to limit the cache to 1/8 of VM size.
4014 */
4015 arc_c = MIN(arc_c, vmem_size(heap_arena, VMEM_ALLOC | VMEM_FREE) / 8);
4016 /*
4017 * Register a shrinker to support synchronous (direct) memory
4018 * reclaim from the arc. This is done to prevent kswapd from
4019 * swapping out pages when it is preferable to shrink the arc.
4020 */
4021 spl_register_shrinker(&arc_shrinker);
4022 #endif
4023
4024 /* set min cache to 1/32 of all memory, or 64MB, whichever is more */
4025 arc_c_min = MAX(arc_c / 4, 64<<20);
4026 /* set max to 1/2 of all memory */
4027 arc_c_max = arc_c * 4;
4028
4029 /*
4030 * Allow the tunables to override our calculations if they are
4031 * reasonable (ie. over 64MB)
4032 */
4033 if (zfs_arc_max > 64<<20 && zfs_arc_max < physmem * PAGESIZE)
4034 arc_c_max = zfs_arc_max;
4035 if (zfs_arc_min > 64<<20 && zfs_arc_min <= arc_c_max)
4036 arc_c_min = zfs_arc_min;
4037
4038 arc_c = arc_c_max;
4039 arc_p = (arc_c >> 1);
4040
4041 /* limit meta-data to 1/4 of the arc capacity */
4042 arc_meta_limit = arc_c_max / 4;
4043 arc_meta_max = 0;
4044
4045 /* Allow the tunable to override if it is reasonable */
4046 if (zfs_arc_meta_limit > 0 && zfs_arc_meta_limit <= arc_c_max)
4047 arc_meta_limit = zfs_arc_meta_limit;
4048
4049 if (arc_c_min < arc_meta_limit / 2 && zfs_arc_min == 0)
4050 arc_c_min = arc_meta_limit / 2;
4051
4052 /* if kmem_flags are set, lets try to use less memory */
4053 if (kmem_debugging())
4054 arc_c = arc_c / 2;
4055 if (arc_c < arc_c_min)
4056 arc_c = arc_c_min;
4057
4058 arc_anon = &ARC_anon;
4059 arc_mru = &ARC_mru;
4060 arc_mru_ghost = &ARC_mru_ghost;
4061 arc_mfu = &ARC_mfu;
4062 arc_mfu_ghost = &ARC_mfu_ghost;
4063 arc_l2c_only = &ARC_l2c_only;
4064 arc_size = 0;
4065
4066 mutex_init(&arc_anon->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4067 mutex_init(&arc_mru->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4068 mutex_init(&arc_mru_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4069 mutex_init(&arc_mfu->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4070 mutex_init(&arc_mfu_ghost->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4071 mutex_init(&arc_l2c_only->arcs_mtx, NULL, MUTEX_DEFAULT, NULL);
4072
4073 list_create(&arc_mru->arcs_list[ARC_BUFC_METADATA],
4074 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4075 list_create(&arc_mru->arcs_list[ARC_BUFC_DATA],
4076 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4077 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA],
4078 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4079 list_create(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA],
4080 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4081 list_create(&arc_mfu->arcs_list[ARC_BUFC_METADATA],
4082 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4083 list_create(&arc_mfu->arcs_list[ARC_BUFC_DATA],
4084 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4085 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA],
4086 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4087 list_create(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA],
4088 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4089 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_METADATA],
4090 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4091 list_create(&arc_l2c_only->arcs_list[ARC_BUFC_DATA],
4092 sizeof (arc_buf_hdr_t), offsetof(arc_buf_hdr_t, b_arc_node));
4093
4094 arc_anon->arcs_state = ARC_STATE_ANON;
4095 arc_mru->arcs_state = ARC_STATE_MRU;
4096 arc_mru_ghost->arcs_state = ARC_STATE_MRU_GHOST;
4097 arc_mfu->arcs_state = ARC_STATE_MFU;
4098 arc_mfu_ghost->arcs_state = ARC_STATE_MFU_GHOST;
4099 arc_l2c_only->arcs_state = ARC_STATE_L2C_ONLY;
4100
4101 buf_init();
4102
4103 arc_thread_exit = 0;
4104 list_create(&arc_prune_list, sizeof (arc_prune_t),
4105 offsetof(arc_prune_t, p_node));
4106 arc_eviction_list = NULL;
4107 mutex_init(&arc_prune_mtx, NULL, MUTEX_DEFAULT, NULL);
4108 mutex_init(&arc_eviction_mtx, NULL, MUTEX_DEFAULT, NULL);
4109 bzero(&arc_eviction_hdr, sizeof (arc_buf_hdr_t));
4110
4111 arc_ksp = kstat_create("zfs", 0, "arcstats", "misc", KSTAT_TYPE_NAMED,
4112 sizeof (arc_stats) / sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
4113
4114 if (arc_ksp != NULL) {
4115 arc_ksp->ks_data = &arc_stats;
4116 arc_ksp->ks_update = arc_kstat_update;
4117 kstat_install(arc_ksp);
4118 }
4119
4120 (void) thread_create(NULL, 0, arc_adapt_thread, NULL, 0, &p0,
4121 TS_RUN, minclsyspri);
4122
4123 arc_dead = FALSE;
4124 arc_warm = B_FALSE;
4125
4126 /*
4127 * Calculate maximum amount of dirty data per pool.
4128 *
4129 * If it has been set by a module parameter, take that.
4130 * Otherwise, use a percentage of physical memory defined by
4131 * zfs_dirty_data_max_percent (default 10%) with a cap at
4132 * zfs_dirty_data_max_max (default 25% of physical memory).
4133 */
4134 if (zfs_dirty_data_max_max == 0)
4135 zfs_dirty_data_max_max = physmem * PAGESIZE *
4136 zfs_dirty_data_max_max_percent / 100;
4137
4138 if (zfs_dirty_data_max == 0) {
4139 zfs_dirty_data_max = physmem * PAGESIZE *
4140 zfs_dirty_data_max_percent / 100;
4141 zfs_dirty_data_max = MIN(zfs_dirty_data_max,
4142 zfs_dirty_data_max_max);
4143 }
4144 }
4145
4146 void
4147 arc_fini(void)
4148 {
4149 arc_prune_t *p;
4150
4151 mutex_enter(&arc_reclaim_thr_lock);
4152 #ifdef _KERNEL
4153 spl_unregister_shrinker(&arc_shrinker);
4154 #endif /* _KERNEL */
4155
4156 arc_thread_exit = 1;
4157 while (arc_thread_exit != 0)
4158 cv_wait(&arc_reclaim_thr_cv, &arc_reclaim_thr_lock);
4159 mutex_exit(&arc_reclaim_thr_lock);
4160
4161 arc_flush(NULL);
4162
4163 arc_dead = TRUE;
4164
4165 if (arc_ksp != NULL) {
4166 kstat_delete(arc_ksp);
4167 arc_ksp = NULL;
4168 }
4169
4170 mutex_enter(&arc_prune_mtx);
4171 while ((p = list_head(&arc_prune_list)) != NULL) {
4172 list_remove(&arc_prune_list, p);
4173 refcount_remove(&p->p_refcnt, &arc_prune_list);
4174 refcount_destroy(&p->p_refcnt);
4175 kmem_free(p, sizeof (*p));
4176 }
4177 mutex_exit(&arc_prune_mtx);
4178
4179 list_destroy(&arc_prune_list);
4180 mutex_destroy(&arc_prune_mtx);
4181 mutex_destroy(&arc_eviction_mtx);
4182 mutex_destroy(&arc_reclaim_thr_lock);
4183 cv_destroy(&arc_reclaim_thr_cv);
4184
4185 list_destroy(&arc_mru->arcs_list[ARC_BUFC_METADATA]);
4186 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_METADATA]);
4187 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_METADATA]);
4188 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_METADATA]);
4189 list_destroy(&arc_mru->arcs_list[ARC_BUFC_DATA]);
4190 list_destroy(&arc_mru_ghost->arcs_list[ARC_BUFC_DATA]);
4191 list_destroy(&arc_mfu->arcs_list[ARC_BUFC_DATA]);
4192 list_destroy(&arc_mfu_ghost->arcs_list[ARC_BUFC_DATA]);
4193
4194 mutex_destroy(&arc_anon->arcs_mtx);
4195 mutex_destroy(&arc_mru->arcs_mtx);
4196 mutex_destroy(&arc_mru_ghost->arcs_mtx);
4197 mutex_destroy(&arc_mfu->arcs_mtx);
4198 mutex_destroy(&arc_mfu_ghost->arcs_mtx);
4199 mutex_destroy(&arc_l2c_only->arcs_mtx);
4200
4201 buf_fini();
4202
4203 ASSERT(arc_loaned_bytes == 0);
4204 }
4205
4206 /*
4207 * Level 2 ARC
4208 *
4209 * The level 2 ARC (L2ARC) is a cache layer in-between main memory and disk.
4210 * It uses dedicated storage devices to hold cached data, which are populated
4211 * using large infrequent writes. The main role of this cache is to boost
4212 * the performance of random read workloads. The intended L2ARC devices
4213 * include short-stroked disks, solid state disks, and other media with
4214 * substantially faster read latency than disk.
4215 *
4216 * +-----------------------+
4217 * | ARC |
4218 * +-----------------------+
4219 * | ^ ^
4220 * | | |
4221 * l2arc_feed_thread() arc_read()
4222 * | | |
4223 * | l2arc read |
4224 * V | |
4225 * +---------------+ |
4226 * | L2ARC | |
4227 * +---------------+ |
4228 * | ^ |
4229 * l2arc_write() | |
4230 * | | |
4231 * V | |
4232 * +-------+ +-------+
4233 * | vdev | | vdev |
4234 * | cache | | cache |
4235 * +-------+ +-------+
4236 * +=========+ .-----.
4237 * : L2ARC : |-_____-|
4238 * : devices : | Disks |
4239 * +=========+ `-_____-'
4240 *
4241 * Read requests are satisfied from the following sources, in order:
4242 *
4243 * 1) ARC
4244 * 2) vdev cache of L2ARC devices
4245 * 3) L2ARC devices
4246 * 4) vdev cache of disks
4247 * 5) disks
4248 *
4249 * Some L2ARC device types exhibit extremely slow write performance.
4250 * To accommodate for this there are some significant differences between
4251 * the L2ARC and traditional cache design:
4252 *
4253 * 1. There is no eviction path from the ARC to the L2ARC. Evictions from
4254 * the ARC behave as usual, freeing buffers and placing headers on ghost
4255 * lists. The ARC does not send buffers to the L2ARC during eviction as
4256 * this would add inflated write latencies for all ARC memory pressure.
4257 *
4258 * 2. The L2ARC attempts to cache data from the ARC before it is evicted.
4259 * It does this by periodically scanning buffers from the eviction-end of
4260 * the MFU and MRU ARC lists, copying them to the L2ARC devices if they are
4261 * not already there. It scans until a headroom of buffers is satisfied,
4262 * which itself is a buffer for ARC eviction. If a compressible buffer is
4263 * found during scanning and selected for writing to an L2ARC device, we
4264 * temporarily boost scanning headroom during the next scan cycle to make
4265 * sure we adapt to compression effects (which might significantly reduce
4266 * the data volume we write to L2ARC). The thread that does this is
4267 * l2arc_feed_thread(), illustrated below; example sizes are included to
4268 * provide a better sense of ratio than this diagram:
4269 *
4270 * head --> tail
4271 * +---------------------+----------+
4272 * ARC_mfu |:::::#:::::::::::::::|o#o###o###|-->. # already on L2ARC
4273 * +---------------------+----------+ | o L2ARC eligible
4274 * ARC_mru |:#:::::::::::::::::::|#o#ooo####|-->| : ARC buffer
4275 * +---------------------+----------+ |
4276 * 15.9 Gbytes ^ 32 Mbytes |
4277 * headroom |
4278 * l2arc_feed_thread()
4279 * |
4280 * l2arc write hand <--[oooo]--'
4281 * | 8 Mbyte
4282 * | write max
4283 * V
4284 * +==============================+
4285 * L2ARC dev |####|#|###|###| |####| ... |
4286 * +==============================+
4287 * 32 Gbytes
4288 *
4289 * 3. If an ARC buffer is copied to the L2ARC but then hit instead of
4290 * evicted, then the L2ARC has cached a buffer much sooner than it probably
4291 * needed to, potentially wasting L2ARC device bandwidth and storage. It is
4292 * safe to say that this is an uncommon case, since buffers at the end of
4293 * the ARC lists have moved there due to inactivity.
4294 *
4295 * 4. If the ARC evicts faster than the L2ARC can maintain a headroom,
4296 * then the L2ARC simply misses copying some buffers. This serves as a
4297 * pressure valve to prevent heavy read workloads from both stalling the ARC
4298 * with waits and clogging the L2ARC with writes. This also helps prevent
4299 * the potential for the L2ARC to churn if it attempts to cache content too
4300 * quickly, such as during backups of the entire pool.
4301 *
4302 * 5. After system boot and before the ARC has filled main memory, there are
4303 * no evictions from the ARC and so the tails of the ARC_mfu and ARC_mru
4304 * lists can remain mostly static. Instead of searching from tail of these
4305 * lists as pictured, the l2arc_feed_thread() will search from the list heads
4306 * for eligible buffers, greatly increasing its chance of finding them.
4307 *
4308 * The L2ARC device write speed is also boosted during this time so that
4309 * the L2ARC warms up faster. Since there have been no ARC evictions yet,
4310 * there are no L2ARC reads, and no fear of degrading read performance
4311 * through increased writes.
4312 *
4313 * 6. Writes to the L2ARC devices are grouped and sent in-sequence, so that
4314 * the vdev queue can aggregate them into larger and fewer writes. Each
4315 * device is written to in a rotor fashion, sweeping writes through
4316 * available space then repeating.
4317 *
4318 * 7. The L2ARC does not store dirty content. It never needs to flush
4319 * write buffers back to disk based storage.
4320 *
4321 * 8. If an ARC buffer is written (and dirtied) which also exists in the
4322 * L2ARC, the now stale L2ARC buffer is immediately dropped.
4323 *
4324 * The performance of the L2ARC can be tweaked by a number of tunables, which
4325 * may be necessary for different workloads:
4326 *
4327 * l2arc_write_max max write bytes per interval
4328 * l2arc_write_boost extra write bytes during device warmup
4329 * l2arc_noprefetch skip caching prefetched buffers
4330 * l2arc_nocompress skip compressing buffers
4331 * l2arc_headroom number of max device writes to precache
4332 * l2arc_headroom_boost when we find compressed buffers during ARC
4333 * scanning, we multiply headroom by this
4334 * percentage factor for the next scan cycle,
4335 * since more compressed buffers are likely to
4336 * be present
4337 * l2arc_feed_secs seconds between L2ARC writing
4338 *
4339 * Tunables may be removed or added as future performance improvements are
4340 * integrated, and also may become zpool properties.
4341 *
4342 * There are three key functions that control how the L2ARC warms up:
4343 *
4344 * l2arc_write_eligible() check if a buffer is eligible to cache
4345 * l2arc_write_size() calculate how much to write
4346 * l2arc_write_interval() calculate sleep delay between writes
4347 *
4348 * These three functions determine what to write, how much, and how quickly
4349 * to send writes.
4350 */
4351
4352 static boolean_t
4353 l2arc_write_eligible(uint64_t spa_guid, arc_buf_hdr_t *ab)
4354 {
4355 /*
4356 * A buffer is *not* eligible for the L2ARC if it:
4357 * 1. belongs to a different spa.
4358 * 2. is already cached on the L2ARC.
4359 * 3. has an I/O in progress (it may be an incomplete read).
4360 * 4. is flagged not eligible (zfs property).
4361 */
4362 if (ab->b_spa != spa_guid || ab->b_l2hdr != NULL ||
4363 HDR_IO_IN_PROGRESS(ab) || !HDR_L2CACHE(ab))
4364 return (B_FALSE);
4365
4366 return (B_TRUE);
4367 }
4368
4369 static uint64_t
4370 l2arc_write_size(void)
4371 {
4372 uint64_t size;
4373
4374 /*
4375 * Make sure our globals have meaningful values in case the user
4376 * altered them.
4377 */
4378 size = l2arc_write_max;
4379 if (size == 0) {
4380 cmn_err(CE_NOTE, "Bad value for l2arc_write_max, value must "
4381 "be greater than zero, resetting it to the default (%d)",
4382 L2ARC_WRITE_SIZE);
4383 size = l2arc_write_max = L2ARC_WRITE_SIZE;
4384 }
4385
4386 if (arc_warm == B_FALSE)
4387 size += l2arc_write_boost;
4388
4389 return (size);
4390
4391 }
4392
4393 static clock_t
4394 l2arc_write_interval(clock_t began, uint64_t wanted, uint64_t wrote)
4395 {
4396 clock_t interval, next, now;
4397
4398 /*
4399 * If the ARC lists are busy, increase our write rate; if the
4400 * lists are stale, idle back. This is achieved by checking
4401 * how much we previously wrote - if it was more than half of
4402 * what we wanted, schedule the next write much sooner.
4403 */
4404 if (l2arc_feed_again && wrote > (wanted / 2))
4405 interval = (hz * l2arc_feed_min_ms) / 1000;
4406 else
4407 interval = hz * l2arc_feed_secs;
4408
4409 now = ddi_get_lbolt();
4410 next = MAX(now, MIN(now + interval, began + interval));
4411
4412 return (next);
4413 }
4414
4415 static void
4416 l2arc_hdr_stat_add(void)
4417 {
4418 ARCSTAT_INCR(arcstat_l2_hdr_size, HDR_SIZE);
4419 ARCSTAT_INCR(arcstat_hdr_size, -HDR_SIZE);
4420 }
4421
4422 static void
4423 l2arc_hdr_stat_remove(void)
4424 {
4425 ARCSTAT_INCR(arcstat_l2_hdr_size, -HDR_SIZE);
4426 ARCSTAT_INCR(arcstat_hdr_size, HDR_SIZE);
4427 }
4428
4429 /*
4430 * Cycle through L2ARC devices. This is how L2ARC load balances.
4431 * If a device is returned, this also returns holding the spa config lock.
4432 */
4433 static l2arc_dev_t *
4434 l2arc_dev_get_next(void)
4435 {
4436 l2arc_dev_t *first, *next = NULL;
4437
4438 /*
4439 * Lock out the removal of spas (spa_namespace_lock), then removal
4440 * of cache devices (l2arc_dev_mtx). Once a device has been selected,
4441 * both locks will be dropped and a spa config lock held instead.
4442 */
4443 mutex_enter(&spa_namespace_lock);
4444 mutex_enter(&l2arc_dev_mtx);
4445
4446 /* if there are no vdevs, there is nothing to do */
4447 if (l2arc_ndev == 0)
4448 goto out;
4449
4450 first = NULL;
4451 next = l2arc_dev_last;
4452 do {
4453 /* loop around the list looking for a non-faulted vdev */
4454 if (next == NULL) {
4455 next = list_head(l2arc_dev_list);
4456 } else {
4457 next = list_next(l2arc_dev_list, next);
4458 if (next == NULL)
4459 next = list_head(l2arc_dev_list);
4460 }
4461
4462 /* if we have come back to the start, bail out */
4463 if (first == NULL)
4464 first = next;
4465 else if (next == first)
4466 break;
4467
4468 } while (vdev_is_dead(next->l2ad_vdev));
4469
4470 /* if we were unable to find any usable vdevs, return NULL */
4471 if (vdev_is_dead(next->l2ad_vdev))
4472 next = NULL;
4473
4474 l2arc_dev_last = next;
4475
4476 out:
4477 mutex_exit(&l2arc_dev_mtx);
4478
4479 /*
4480 * Grab the config lock to prevent the 'next' device from being
4481 * removed while we are writing to it.
4482 */
4483 if (next != NULL)
4484 spa_config_enter(next->l2ad_spa, SCL_L2ARC, next, RW_READER);
4485 mutex_exit(&spa_namespace_lock);
4486
4487 return (next);
4488 }
4489
4490 /*
4491 * Free buffers that were tagged for destruction.
4492 */
4493 static void
4494 l2arc_do_free_on_write(void)
4495 {
4496 list_t *buflist;
4497 l2arc_data_free_t *df, *df_prev;
4498
4499 mutex_enter(&l2arc_free_on_write_mtx);
4500 buflist = l2arc_free_on_write;
4501
4502 for (df = list_tail(buflist); df; df = df_prev) {
4503 df_prev = list_prev(buflist, df);
4504 ASSERT(df->l2df_data != NULL);
4505 ASSERT(df->l2df_func != NULL);
4506 df->l2df_func(df->l2df_data, df->l2df_size);
4507 list_remove(buflist, df);
4508 kmem_free(df, sizeof (l2arc_data_free_t));
4509 }
4510
4511 mutex_exit(&l2arc_free_on_write_mtx);
4512 }
4513
4514 /*
4515 * A write to a cache device has completed. Update all headers to allow
4516 * reads from these buffers to begin.
4517 */
4518 static void
4519 l2arc_write_done(zio_t *zio)
4520 {
4521 l2arc_write_callback_t *cb;
4522 l2arc_dev_t *dev;
4523 list_t *buflist;
4524 arc_buf_hdr_t *head, *ab, *ab_prev;
4525 l2arc_buf_hdr_t *abl2;
4526 kmutex_t *hash_lock;
4527
4528 cb = zio->io_private;
4529 ASSERT(cb != NULL);
4530 dev = cb->l2wcb_dev;
4531 ASSERT(dev != NULL);
4532 head = cb->l2wcb_head;
4533 ASSERT(head != NULL);
4534 buflist = dev->l2ad_buflist;
4535 ASSERT(buflist != NULL);
4536 DTRACE_PROBE2(l2arc__iodone, zio_t *, zio,
4537 l2arc_write_callback_t *, cb);
4538
4539 if (zio->io_error != 0)
4540 ARCSTAT_BUMP(arcstat_l2_writes_error);
4541
4542 mutex_enter(&l2arc_buflist_mtx);
4543
4544 /*
4545 * All writes completed, or an error was hit.
4546 */
4547 for (ab = list_prev(buflist, head); ab; ab = ab_prev) {
4548 ab_prev = list_prev(buflist, ab);
4549 abl2 = ab->b_l2hdr;
4550
4551 /*
4552 * Release the temporary compressed buffer as soon as possible.
4553 */
4554 if (abl2->b_compress != ZIO_COMPRESS_OFF)
4555 l2arc_release_cdata_buf(ab);
4556
4557 hash_lock = HDR_LOCK(ab);
4558 if (!mutex_tryenter(hash_lock)) {
4559 /*
4560 * This buffer misses out. It may be in a stage
4561 * of eviction. Its ARC_L2_WRITING flag will be
4562 * left set, denying reads to this buffer.
4563 */
4564 ARCSTAT_BUMP(arcstat_l2_writes_hdr_miss);
4565 continue;
4566 }
4567
4568 if (zio->io_error != 0) {
4569 /*
4570 * Error - drop L2ARC entry.
4571 */
4572 list_remove(buflist, ab);
4573 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4574 ab->b_l2hdr = NULL;
4575 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4576 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
4577 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4578 }
4579
4580 /*
4581 * Allow ARC to begin reads to this L2ARC entry.
4582 */
4583 ab->b_flags &= ~ARC_L2_WRITING;
4584
4585 mutex_exit(hash_lock);
4586 }
4587
4588 atomic_inc_64(&l2arc_writes_done);
4589 list_remove(buflist, head);
4590 kmem_cache_free(hdr_cache, head);
4591 mutex_exit(&l2arc_buflist_mtx);
4592
4593 l2arc_do_free_on_write();
4594
4595 kmem_free(cb, sizeof (l2arc_write_callback_t));
4596 }
4597
4598 /*
4599 * A read to a cache device completed. Validate buffer contents before
4600 * handing over to the regular ARC routines.
4601 */
4602 static void
4603 l2arc_read_done(zio_t *zio)
4604 {
4605 l2arc_read_callback_t *cb;
4606 arc_buf_hdr_t *hdr;
4607 arc_buf_t *buf;
4608 kmutex_t *hash_lock;
4609 int equal;
4610
4611 ASSERT(zio->io_vd != NULL);
4612 ASSERT(zio->io_flags & ZIO_FLAG_DONT_PROPAGATE);
4613
4614 spa_config_exit(zio->io_spa, SCL_L2ARC, zio->io_vd);
4615
4616 cb = zio->io_private;
4617 ASSERT(cb != NULL);
4618 buf = cb->l2rcb_buf;
4619 ASSERT(buf != NULL);
4620
4621 hash_lock = HDR_LOCK(buf->b_hdr);
4622 mutex_enter(hash_lock);
4623 hdr = buf->b_hdr;
4624 ASSERT3P(hash_lock, ==, HDR_LOCK(hdr));
4625
4626 /*
4627 * If the buffer was compressed, decompress it first.
4628 */
4629 if (cb->l2rcb_compress != ZIO_COMPRESS_OFF)
4630 l2arc_decompress_zio(zio, hdr, cb->l2rcb_compress);
4631 ASSERT(zio->io_data != NULL);
4632
4633 /*
4634 * Check this survived the L2ARC journey.
4635 */
4636 equal = arc_cksum_equal(buf);
4637 if (equal && zio->io_error == 0 && !HDR_L2_EVICTED(hdr)) {
4638 mutex_exit(hash_lock);
4639 zio->io_private = buf;
4640 zio->io_bp_copy = cb->l2rcb_bp; /* XXX fix in L2ARC 2.0 */
4641 zio->io_bp = &zio->io_bp_copy; /* XXX fix in L2ARC 2.0 */
4642 arc_read_done(zio);
4643 } else {
4644 mutex_exit(hash_lock);
4645 /*
4646 * Buffer didn't survive caching. Increment stats and
4647 * reissue to the original storage device.
4648 */
4649 if (zio->io_error != 0) {
4650 ARCSTAT_BUMP(arcstat_l2_io_error);
4651 } else {
4652 zio->io_error = SET_ERROR(EIO);
4653 }
4654 if (!equal)
4655 ARCSTAT_BUMP(arcstat_l2_cksum_bad);
4656
4657 /*
4658 * If there's no waiter, issue an async i/o to the primary
4659 * storage now. If there *is* a waiter, the caller must
4660 * issue the i/o in a context where it's OK to block.
4661 */
4662 if (zio->io_waiter == NULL) {
4663 zio_t *pio = zio_unique_parent(zio);
4664
4665 ASSERT(!pio || pio->io_child_type == ZIO_CHILD_LOGICAL);
4666
4667 zio_nowait(zio_read(pio, cb->l2rcb_spa, &cb->l2rcb_bp,
4668 buf->b_data, zio->io_size, arc_read_done, buf,
4669 zio->io_priority, cb->l2rcb_flags, &cb->l2rcb_zb));
4670 }
4671 }
4672
4673 kmem_free(cb, sizeof (l2arc_read_callback_t));
4674 }
4675
4676 /*
4677 * This is the list priority from which the L2ARC will search for pages to
4678 * cache. This is used within loops (0..3) to cycle through lists in the
4679 * desired order. This order can have a significant effect on cache
4680 * performance.
4681 *
4682 * Currently the metadata lists are hit first, MFU then MRU, followed by
4683 * the data lists. This function returns a locked list, and also returns
4684 * the lock pointer.
4685 */
4686 static list_t *
4687 l2arc_list_locked(int list_num, kmutex_t **lock)
4688 {
4689 list_t *list = NULL;
4690
4691 ASSERT(list_num >= 0 && list_num <= 3);
4692
4693 switch (list_num) {
4694 case 0:
4695 list = &arc_mfu->arcs_list[ARC_BUFC_METADATA];
4696 *lock = &arc_mfu->arcs_mtx;
4697 break;
4698 case 1:
4699 list = &arc_mru->arcs_list[ARC_BUFC_METADATA];
4700 *lock = &arc_mru->arcs_mtx;
4701 break;
4702 case 2:
4703 list = &arc_mfu->arcs_list[ARC_BUFC_DATA];
4704 *lock = &arc_mfu->arcs_mtx;
4705 break;
4706 case 3:
4707 list = &arc_mru->arcs_list[ARC_BUFC_DATA];
4708 *lock = &arc_mru->arcs_mtx;
4709 break;
4710 }
4711
4712 ASSERT(!(MUTEX_HELD(*lock)));
4713 mutex_enter(*lock);
4714 return (list);
4715 }
4716
4717 /*
4718 * Evict buffers from the device write hand to the distance specified in
4719 * bytes. This distance may span populated buffers, it may span nothing.
4720 * This is clearing a region on the L2ARC device ready for writing.
4721 * If the 'all' boolean is set, every buffer is evicted.
4722 */
4723 static void
4724 l2arc_evict(l2arc_dev_t *dev, uint64_t distance, boolean_t all)
4725 {
4726 list_t *buflist;
4727 l2arc_buf_hdr_t *abl2;
4728 arc_buf_hdr_t *ab, *ab_prev;
4729 kmutex_t *hash_lock;
4730 uint64_t taddr;
4731
4732 buflist = dev->l2ad_buflist;
4733
4734 if (buflist == NULL)
4735 return;
4736
4737 if (!all && dev->l2ad_first) {
4738 /*
4739 * This is the first sweep through the device. There is
4740 * nothing to evict.
4741 */
4742 return;
4743 }
4744
4745 if (dev->l2ad_hand >= (dev->l2ad_end - (2 * distance))) {
4746 /*
4747 * When nearing the end of the device, evict to the end
4748 * before the device write hand jumps to the start.
4749 */
4750 taddr = dev->l2ad_end;
4751 } else {
4752 taddr = dev->l2ad_hand + distance;
4753 }
4754 DTRACE_PROBE4(l2arc__evict, l2arc_dev_t *, dev, list_t *, buflist,
4755 uint64_t, taddr, boolean_t, all);
4756
4757 top:
4758 mutex_enter(&l2arc_buflist_mtx);
4759 for (ab = list_tail(buflist); ab; ab = ab_prev) {
4760 ab_prev = list_prev(buflist, ab);
4761
4762 hash_lock = HDR_LOCK(ab);
4763 if (!mutex_tryenter(hash_lock)) {
4764 /*
4765 * Missed the hash lock. Retry.
4766 */
4767 ARCSTAT_BUMP(arcstat_l2_evict_lock_retry);
4768 mutex_exit(&l2arc_buflist_mtx);
4769 mutex_enter(hash_lock);
4770 mutex_exit(hash_lock);
4771 goto top;
4772 }
4773
4774 if (HDR_L2_WRITE_HEAD(ab)) {
4775 /*
4776 * We hit a write head node. Leave it for
4777 * l2arc_write_done().
4778 */
4779 list_remove(buflist, ab);
4780 mutex_exit(hash_lock);
4781 continue;
4782 }
4783
4784 if (!all && ab->b_l2hdr != NULL &&
4785 (ab->b_l2hdr->b_daddr > taddr ||
4786 ab->b_l2hdr->b_daddr < dev->l2ad_hand)) {
4787 /*
4788 * We've evicted to the target address,
4789 * or the end of the device.
4790 */
4791 mutex_exit(hash_lock);
4792 break;
4793 }
4794
4795 if (HDR_FREE_IN_PROGRESS(ab)) {
4796 /*
4797 * Already on the path to destruction.
4798 */
4799 mutex_exit(hash_lock);
4800 continue;
4801 }
4802
4803 if (ab->b_state == arc_l2c_only) {
4804 ASSERT(!HDR_L2_READING(ab));
4805 /*
4806 * This doesn't exist in the ARC. Destroy.
4807 * arc_hdr_destroy() will call list_remove()
4808 * and decrement arcstat_l2_size.
4809 */
4810 arc_change_state(arc_anon, ab, hash_lock);
4811 arc_hdr_destroy(ab);
4812 } else {
4813 /*
4814 * Invalidate issued or about to be issued
4815 * reads, since we may be about to write
4816 * over this location.
4817 */
4818 if (HDR_L2_READING(ab)) {
4819 ARCSTAT_BUMP(arcstat_l2_evict_reading);
4820 ab->b_flags |= ARC_L2_EVICTED;
4821 }
4822
4823 /*
4824 * Tell ARC this no longer exists in L2ARC.
4825 */
4826 if (ab->b_l2hdr != NULL) {
4827 abl2 = ab->b_l2hdr;
4828 ARCSTAT_INCR(arcstat_l2_asize, -abl2->b_asize);
4829 ab->b_l2hdr = NULL;
4830 kmem_free(abl2, sizeof (l2arc_buf_hdr_t));
4831 arc_space_return(L2HDR_SIZE, ARC_SPACE_L2HDRS);
4832 ARCSTAT_INCR(arcstat_l2_size, -ab->b_size);
4833 }
4834 list_remove(buflist, ab);
4835
4836 /*
4837 * This may have been leftover after a
4838 * failed write.
4839 */
4840 ab->b_flags &= ~ARC_L2_WRITING;
4841 }
4842 mutex_exit(hash_lock);
4843 }
4844 mutex_exit(&l2arc_buflist_mtx);
4845
4846 vdev_space_update(dev->l2ad_vdev, -(taddr - dev->l2ad_evict), 0, 0);
4847 dev->l2ad_evict = taddr;
4848 }
4849
4850 /*
4851 * Find and write ARC buffers to the L2ARC device.
4852 *
4853 * An ARC_L2_WRITING flag is set so that the L2ARC buffers are not valid
4854 * for reading until they have completed writing.
4855 * The headroom_boost is an in-out parameter used to maintain headroom boost
4856 * state between calls to this function.
4857 *
4858 * Returns the number of bytes actually written (which may be smaller than
4859 * the delta by which the device hand has changed due to alignment).
4860 */
4861 static uint64_t
4862 l2arc_write_buffers(spa_t *spa, l2arc_dev_t *dev, uint64_t target_sz,
4863 boolean_t *headroom_boost)
4864 {
4865 arc_buf_hdr_t *ab, *ab_prev, *head;
4866 list_t *list;
4867 uint64_t write_asize, write_psize, write_sz, headroom,
4868 buf_compress_minsz;
4869 void *buf_data;
4870 kmutex_t *list_lock = NULL;
4871 boolean_t full;
4872 l2arc_write_callback_t *cb;
4873 zio_t *pio, *wzio;
4874 uint64_t guid = spa_load_guid(spa);
4875 int try;
4876 const boolean_t do_headroom_boost = *headroom_boost;
4877
4878 ASSERT(dev->l2ad_vdev != NULL);
4879
4880 /* Lower the flag now, we might want to raise it again later. */
4881 *headroom_boost = B_FALSE;
4882
4883 pio = NULL;
4884 write_sz = write_asize = write_psize = 0;
4885 full = B_FALSE;
4886 head = kmem_cache_alloc(hdr_cache, KM_PUSHPAGE);
4887 head->b_flags |= ARC_L2_WRITE_HEAD;
4888
4889 /*
4890 * We will want to try to compress buffers that are at least 2x the
4891 * device sector size.
4892 */
4893 buf_compress_minsz = 2 << dev->l2ad_vdev->vdev_ashift;
4894
4895 /*
4896 * Copy buffers for L2ARC writing.
4897 */
4898 mutex_enter(&l2arc_buflist_mtx);
4899 for (try = 0; try <= 3; try++) {
4900 uint64_t passed_sz = 0;
4901
4902 list = l2arc_list_locked(try, &list_lock);
4903
4904 /*
4905 * L2ARC fast warmup.
4906 *
4907 * Until the ARC is warm and starts to evict, read from the
4908 * head of the ARC lists rather than the tail.
4909 */
4910 if (arc_warm == B_FALSE)
4911 ab = list_head(list);
4912 else
4913 ab = list_tail(list);
4914
4915 headroom = target_sz * l2arc_headroom;
4916 if (do_headroom_boost)
4917 headroom = (headroom * l2arc_headroom_boost) / 100;
4918
4919 for (; ab; ab = ab_prev) {
4920 l2arc_buf_hdr_t *l2hdr;
4921 kmutex_t *hash_lock;
4922 uint64_t buf_sz;
4923
4924 if (arc_warm == B_FALSE)
4925 ab_prev = list_next(list, ab);
4926 else
4927 ab_prev = list_prev(list, ab);
4928
4929 hash_lock = HDR_LOCK(ab);
4930 if (!mutex_tryenter(hash_lock)) {
4931 /*
4932 * Skip this buffer rather than waiting.
4933 */
4934 continue;
4935 }
4936
4937 passed_sz += ab->b_size;
4938 if (passed_sz > headroom) {
4939 /*
4940 * Searched too far.
4941 */
4942 mutex_exit(hash_lock);
4943 break;
4944 }
4945
4946 if (!l2arc_write_eligible(guid, ab)) {
4947 mutex_exit(hash_lock);
4948 continue;
4949 }
4950
4951 if ((write_sz + ab->b_size) > target_sz) {
4952 full = B_TRUE;
4953 mutex_exit(hash_lock);
4954 break;
4955 }
4956
4957 if (pio == NULL) {
4958 /*
4959 * Insert a dummy header on the buflist so
4960 * l2arc_write_done() can find where the
4961 * write buffers begin without searching.
4962 */
4963 list_insert_head(dev->l2ad_buflist, head);
4964
4965 cb = kmem_alloc(sizeof (l2arc_write_callback_t),
4966 KM_PUSHPAGE);
4967 cb->l2wcb_dev = dev;
4968 cb->l2wcb_head = head;
4969 pio = zio_root(spa, l2arc_write_done, cb,
4970 ZIO_FLAG_CANFAIL);
4971 }
4972
4973 /*
4974 * Create and add a new L2ARC header.
4975 */
4976 l2hdr = kmem_zalloc(sizeof (l2arc_buf_hdr_t),
4977 KM_PUSHPAGE);
4978 l2hdr->b_dev = dev;
4979 arc_space_consume(L2HDR_SIZE, ARC_SPACE_L2HDRS);
4980
4981 ab->b_flags |= ARC_L2_WRITING;
4982
4983 /*
4984 * Temporarily stash the data buffer in b_tmp_cdata.
4985 * The subsequent write step will pick it up from
4986 * there. This is because can't access ab->b_buf
4987 * without holding the hash_lock, which we in turn
4988 * can't access without holding the ARC list locks
4989 * (which we want to avoid during compression/writing)
4990 */
4991 l2hdr->b_compress = ZIO_COMPRESS_OFF;
4992 l2hdr->b_asize = ab->b_size;
4993 l2hdr->b_tmp_cdata = ab->b_buf->b_data;
4994 l2hdr->b_hits = 0;
4995
4996 buf_sz = ab->b_size;
4997 ab->b_l2hdr = l2hdr;
4998
4999 list_insert_head(dev->l2ad_buflist, ab);
5000
5001 /*
5002 * Compute and store the buffer cksum before
5003 * writing. On debug the cksum is verified first.
5004 */
5005 arc_cksum_verify(ab->b_buf);
5006 arc_cksum_compute(ab->b_buf, B_TRUE);
5007
5008 mutex_exit(hash_lock);
5009
5010 write_sz += buf_sz;
5011 }
5012
5013 mutex_exit(list_lock);
5014
5015 if (full == B_TRUE)
5016 break;
5017 }
5018
5019 /* No buffers selected for writing? */
5020 if (pio == NULL) {
5021 ASSERT0(write_sz);
5022 mutex_exit(&l2arc_buflist_mtx);
5023 kmem_cache_free(hdr_cache, head);
5024 return (0);
5025 }
5026
5027 /*
5028 * Now start writing the buffers. We're starting at the write head
5029 * and work backwards, retracing the course of the buffer selector
5030 * loop above.
5031 */
5032 for (ab = list_prev(dev->l2ad_buflist, head); ab;
5033 ab = list_prev(dev->l2ad_buflist, ab)) {
5034 l2arc_buf_hdr_t *l2hdr;
5035 uint64_t buf_sz;
5036
5037 /*
5038 * We shouldn't need to lock the buffer here, since we flagged
5039 * it as ARC_L2_WRITING in the previous step, but we must take
5040 * care to only access its L2 cache parameters. In particular,
5041 * ab->b_buf may be invalid by now due to ARC eviction.
5042 */
5043 l2hdr = ab->b_l2hdr;
5044 l2hdr->b_daddr = dev->l2ad_hand;
5045
5046 if (!l2arc_nocompress && (ab->b_flags & ARC_L2COMPRESS) &&
5047 l2hdr->b_asize >= buf_compress_minsz) {
5048 if (l2arc_compress_buf(l2hdr)) {
5049 /*
5050 * If compression succeeded, enable headroom
5051 * boost on the next scan cycle.
5052 */
5053 *headroom_boost = B_TRUE;
5054 }
5055 }
5056
5057 /*
5058 * Pick up the buffer data we had previously stashed away
5059 * (and now potentially also compressed).
5060 */
5061 buf_data = l2hdr->b_tmp_cdata;
5062 buf_sz = l2hdr->b_asize;
5063
5064 /* Compression may have squashed the buffer to zero length. */
5065 if (buf_sz != 0) {
5066 uint64_t buf_p_sz;
5067
5068 wzio = zio_write_phys(pio, dev->l2ad_vdev,
5069 dev->l2ad_hand, buf_sz, buf_data, ZIO_CHECKSUM_OFF,
5070 NULL, NULL, ZIO_PRIORITY_ASYNC_WRITE,
5071 ZIO_FLAG_CANFAIL, B_FALSE);
5072
5073 DTRACE_PROBE2(l2arc__write, vdev_t *, dev->l2ad_vdev,
5074 zio_t *, wzio);
5075 (void) zio_nowait(wzio);
5076
5077 write_asize += buf_sz;
5078 /*
5079 * Keep the clock hand suitably device-aligned.
5080 */
5081 buf_p_sz = vdev_psize_to_asize(dev->l2ad_vdev, buf_sz);
5082 write_psize += buf_p_sz;
5083 dev->l2ad_hand += buf_p_sz;
5084 }
5085 }
5086
5087 mutex_exit(&l2arc_buflist_mtx);
5088
5089 ASSERT3U(write_asize, <=, target_sz);
5090 ARCSTAT_BUMP(arcstat_l2_writes_sent);
5091 ARCSTAT_INCR(arcstat_l2_write_bytes, write_asize);
5092 ARCSTAT_INCR(arcstat_l2_size, write_sz);
5093 ARCSTAT_INCR(arcstat_l2_asize, write_asize);
5094 vdev_space_update(dev->l2ad_vdev, write_psize, 0, 0);
5095
5096 /*
5097 * Bump device hand to the device start if it is approaching the end.
5098 * l2arc_evict() will already have evicted ahead for this case.
5099 */
5100 if (dev->l2ad_hand >= (dev->l2ad_end - target_sz)) {
5101 vdev_space_update(dev->l2ad_vdev,
5102 dev->l2ad_end - dev->l2ad_hand, 0, 0);
5103 dev->l2ad_hand = dev->l2ad_start;
5104 dev->l2ad_evict = dev->l2ad_start;
5105 dev->l2ad_first = B_FALSE;
5106 }
5107
5108 dev->l2ad_writing = B_TRUE;
5109 (void) zio_wait(pio);
5110 dev->l2ad_writing = B_FALSE;
5111
5112 return (write_asize);
5113 }
5114
5115 /*
5116 * Compresses an L2ARC buffer.
5117 * The data to be compressed must be prefilled in l2hdr->b_tmp_cdata and its
5118 * size in l2hdr->b_asize. This routine tries to compress the data and
5119 * depending on the compression result there are three possible outcomes:
5120 * *) The buffer was incompressible. The original l2hdr contents were left
5121 * untouched and are ready for writing to an L2 device.
5122 * *) The buffer was all-zeros, so there is no need to write it to an L2
5123 * device. To indicate this situation b_tmp_cdata is NULL'ed, b_asize is
5124 * set to zero and b_compress is set to ZIO_COMPRESS_EMPTY.
5125 * *) Compression succeeded and b_tmp_cdata was replaced with a temporary
5126 * data buffer which holds the compressed data to be written, and b_asize
5127 * tells us how much data there is. b_compress is set to the appropriate
5128 * compression algorithm. Once writing is done, invoke
5129 * l2arc_release_cdata_buf on this l2hdr to free this temporary buffer.
5130 *
5131 * Returns B_TRUE if compression succeeded, or B_FALSE if it didn't (the
5132 * buffer was incompressible).
5133 */
5134 static boolean_t
5135 l2arc_compress_buf(l2arc_buf_hdr_t *l2hdr)
5136 {
5137 void *cdata;
5138 size_t csize, len;
5139
5140 ASSERT(l2hdr->b_compress == ZIO_COMPRESS_OFF);
5141 ASSERT(l2hdr->b_tmp_cdata != NULL);
5142
5143 len = l2hdr->b_asize;
5144 cdata = zio_data_buf_alloc(len);
5145 csize = zio_compress_data(ZIO_COMPRESS_LZ4, l2hdr->b_tmp_cdata,
5146 cdata, l2hdr->b_asize);
5147
5148 if (csize == 0) {
5149 /* zero block, indicate that there's nothing to write */
5150 zio_data_buf_free(cdata, len);
5151 l2hdr->b_compress = ZIO_COMPRESS_EMPTY;
5152 l2hdr->b_asize = 0;
5153 l2hdr->b_tmp_cdata = NULL;
5154 ARCSTAT_BUMP(arcstat_l2_compress_zeros);
5155 return (B_TRUE);
5156 } else if (csize > 0 && csize < len) {
5157 /*
5158 * Compression succeeded, we'll keep the cdata around for
5159 * writing and release it afterwards.
5160 */
5161 l2hdr->b_compress = ZIO_COMPRESS_LZ4;
5162 l2hdr->b_asize = csize;
5163 l2hdr->b_tmp_cdata = cdata;
5164 ARCSTAT_BUMP(arcstat_l2_compress_successes);
5165 return (B_TRUE);
5166 } else {
5167 /*
5168 * Compression failed, release the compressed buffer.
5169 * l2hdr will be left unmodified.
5170 */
5171 zio_data_buf_free(cdata, len);
5172 ARCSTAT_BUMP(arcstat_l2_compress_failures);
5173 return (B_FALSE);
5174 }
5175 }
5176
5177 /*
5178 * Decompresses a zio read back from an l2arc device. On success, the
5179 * underlying zio's io_data buffer is overwritten by the uncompressed
5180 * version. On decompression error (corrupt compressed stream), the
5181 * zio->io_error value is set to signal an I/O error.
5182 *
5183 * Please note that the compressed data stream is not checksummed, so
5184 * if the underlying device is experiencing data corruption, we may feed
5185 * corrupt data to the decompressor, so the decompressor needs to be
5186 * able to handle this situation (LZ4 does).
5187 */
5188 static void
5189 l2arc_decompress_zio(zio_t *zio, arc_buf_hdr_t *hdr, enum zio_compress c)
5190 {
5191 uint64_t csize;
5192 void *cdata;
5193
5194 ASSERT(L2ARC_IS_VALID_COMPRESS(c));
5195
5196 if (zio->io_error != 0) {
5197 /*
5198 * An io error has occured, just restore the original io
5199 * size in preparation for a main pool read.
5200 */
5201 zio->io_orig_size = zio->io_size = hdr->b_size;
5202 return;
5203 }
5204
5205 if (c == ZIO_COMPRESS_EMPTY) {
5206 /*
5207 * An empty buffer results in a null zio, which means we
5208 * need to fill its io_data after we're done restoring the
5209 * buffer's contents.
5210 */
5211 ASSERT(hdr->b_buf != NULL);
5212 bzero(hdr->b_buf->b_data, hdr->b_size);
5213 zio->io_data = zio->io_orig_data = hdr->b_buf->b_data;
5214 } else {
5215 ASSERT(zio->io_data != NULL);
5216 /*
5217 * We copy the compressed data from the start of the arc buffer
5218 * (the zio_read will have pulled in only what we need, the
5219 * rest is garbage which we will overwrite at decompression)
5220 * and then decompress back to the ARC data buffer. This way we
5221 * can minimize copying by simply decompressing back over the
5222 * original compressed data (rather than decompressing to an
5223 * aux buffer and then copying back the uncompressed buffer,
5224 * which is likely to be much larger).
5225 */
5226 csize = zio->io_size;
5227 cdata = zio_data_buf_alloc(csize);
5228 bcopy(zio->io_data, cdata, csize);
5229 if (zio_decompress_data(c, cdata, zio->io_data, csize,
5230 hdr->b_size) != 0)
5231 zio->io_error = SET_ERROR(EIO);
5232 zio_data_buf_free(cdata, csize);
5233 }
5234
5235 /* Restore the expected uncompressed IO size. */
5236 zio->io_orig_size = zio->io_size = hdr->b_size;
5237 }
5238
5239 /*
5240 * Releases the temporary b_tmp_cdata buffer in an l2arc header structure.
5241 * This buffer serves as a temporary holder of compressed data while
5242 * the buffer entry is being written to an l2arc device. Once that is
5243 * done, we can dispose of it.
5244 */
5245 static void
5246 l2arc_release_cdata_buf(arc_buf_hdr_t *ab)
5247 {
5248 l2arc_buf_hdr_t *l2hdr = ab->b_l2hdr;
5249
5250 if (l2hdr->b_compress == ZIO_COMPRESS_LZ4) {
5251 /*
5252 * If the data was compressed, then we've allocated a
5253 * temporary buffer for it, so now we need to release it.
5254 */
5255 ASSERT(l2hdr->b_tmp_cdata != NULL);
5256 zio_data_buf_free(l2hdr->b_tmp_cdata, ab->b_size);
5257 }
5258 l2hdr->b_tmp_cdata = NULL;
5259 }
5260
5261 /*
5262 * This thread feeds the L2ARC at regular intervals. This is the beating
5263 * heart of the L2ARC.
5264 */
5265 static void
5266 l2arc_feed_thread(void)
5267 {
5268 callb_cpr_t cpr;
5269 l2arc_dev_t *dev;
5270 spa_t *spa;
5271 uint64_t size, wrote;
5272 clock_t begin, next = ddi_get_lbolt();
5273 boolean_t headroom_boost = B_FALSE;
5274
5275 CALLB_CPR_INIT(&cpr, &l2arc_feed_thr_lock, callb_generic_cpr, FTAG);
5276
5277 mutex_enter(&l2arc_feed_thr_lock);
5278
5279 while (l2arc_thread_exit == 0) {
5280 CALLB_CPR_SAFE_BEGIN(&cpr);
5281 (void) cv_timedwait_interruptible(&l2arc_feed_thr_cv,
5282 &l2arc_feed_thr_lock, next);
5283 CALLB_CPR_SAFE_END(&cpr, &l2arc_feed_thr_lock);
5284 next = ddi_get_lbolt() + hz;
5285
5286 /*
5287 * Quick check for L2ARC devices.
5288 */
5289 mutex_enter(&l2arc_dev_mtx);
5290 if (l2arc_ndev == 0) {
5291 mutex_exit(&l2arc_dev_mtx);
5292 continue;
5293 }
5294 mutex_exit(&l2arc_dev_mtx);
5295 begin = ddi_get_lbolt();
5296
5297 /*
5298 * This selects the next l2arc device to write to, and in
5299 * doing so the next spa to feed from: dev->l2ad_spa. This
5300 * will return NULL if there are now no l2arc devices or if
5301 * they are all faulted.
5302 *
5303 * If a device is returned, its spa's config lock is also
5304 * held to prevent device removal. l2arc_dev_get_next()
5305 * will grab and release l2arc_dev_mtx.
5306 */
5307 if ((dev = l2arc_dev_get_next()) == NULL)
5308 continue;
5309
5310 spa = dev->l2ad_spa;
5311 ASSERT(spa != NULL);
5312
5313 /*
5314 * If the pool is read-only then force the feed thread to
5315 * sleep a little longer.
5316 */
5317 if (!spa_writeable(spa)) {
5318 next = ddi_get_lbolt() + 5 * l2arc_feed_secs * hz;
5319 spa_config_exit(spa, SCL_L2ARC, dev);
5320 continue;
5321 }
5322
5323 /*
5324 * Avoid contributing to memory pressure.
5325 */
5326 if (arc_no_grow) {
5327 ARCSTAT_BUMP(arcstat_l2_abort_lowmem);
5328 spa_config_exit(spa, SCL_L2ARC, dev);
5329 continue;
5330 }
5331
5332 ARCSTAT_BUMP(arcstat_l2_feeds);
5333
5334 size = l2arc_write_size();
5335
5336 /*
5337 * Evict L2ARC buffers that will be overwritten.
5338 */
5339 l2arc_evict(dev, size, B_FALSE);
5340
5341 /*
5342 * Write ARC buffers.
5343 */
5344 wrote = l2arc_write_buffers(spa, dev, size, &headroom_boost);
5345
5346 /*
5347 * Calculate interval between writes.
5348 */
5349 next = l2arc_write_interval(begin, size, wrote);
5350 spa_config_exit(spa, SCL_L2ARC, dev);
5351 }
5352
5353 l2arc_thread_exit = 0;
5354 cv_broadcast(&l2arc_feed_thr_cv);
5355 CALLB_CPR_EXIT(&cpr); /* drops l2arc_feed_thr_lock */
5356 thread_exit();
5357 }
5358
5359 boolean_t
5360 l2arc_vdev_present(vdev_t *vd)
5361 {
5362 l2arc_dev_t *dev;
5363
5364 mutex_enter(&l2arc_dev_mtx);
5365 for (dev = list_head(l2arc_dev_list); dev != NULL;
5366 dev = list_next(l2arc_dev_list, dev)) {
5367 if (dev->l2ad_vdev == vd)
5368 break;
5369 }
5370 mutex_exit(&l2arc_dev_mtx);
5371
5372 return (dev != NULL);
5373 }
5374
5375 /*
5376 * Add a vdev for use by the L2ARC. By this point the spa has already
5377 * validated the vdev and opened it.
5378 */
5379 void
5380 l2arc_add_vdev(spa_t *spa, vdev_t *vd)
5381 {
5382 l2arc_dev_t *adddev;
5383
5384 ASSERT(!l2arc_vdev_present(vd));
5385
5386 /*
5387 * Create a new l2arc device entry.
5388 */
5389 adddev = kmem_zalloc(sizeof (l2arc_dev_t), KM_SLEEP);
5390 adddev->l2ad_spa = spa;
5391 adddev->l2ad_vdev = vd;
5392 adddev->l2ad_start = VDEV_LABEL_START_SIZE;
5393 adddev->l2ad_end = VDEV_LABEL_START_SIZE + vdev_get_min_asize(vd);
5394 adddev->l2ad_hand = adddev->l2ad_start;
5395 adddev->l2ad_evict = adddev->l2ad_start;
5396 adddev->l2ad_first = B_TRUE;
5397 adddev->l2ad_writing = B_FALSE;
5398 list_link_init(&adddev->l2ad_node);
5399
5400 /*
5401 * This is a list of all ARC buffers that are still valid on the
5402 * device.
5403 */
5404 adddev->l2ad_buflist = kmem_zalloc(sizeof (list_t), KM_SLEEP);
5405 list_create(adddev->l2ad_buflist, sizeof (arc_buf_hdr_t),
5406 offsetof(arc_buf_hdr_t, b_l2node));
5407
5408 vdev_space_update(vd, 0, 0, adddev->l2ad_end - adddev->l2ad_hand);
5409
5410 /*
5411 * Add device to global list
5412 */
5413 mutex_enter(&l2arc_dev_mtx);
5414 list_insert_head(l2arc_dev_list, adddev);
5415 atomic_inc_64(&l2arc_ndev);
5416 mutex_exit(&l2arc_dev_mtx);
5417 }
5418
5419 /*
5420 * Remove a vdev from the L2ARC.
5421 */
5422 void
5423 l2arc_remove_vdev(vdev_t *vd)
5424 {
5425 l2arc_dev_t *dev, *nextdev, *remdev = NULL;
5426
5427 /*
5428 * Find the device by vdev
5429 */
5430 mutex_enter(&l2arc_dev_mtx);
5431 for (dev = list_head(l2arc_dev_list); dev; dev = nextdev) {
5432 nextdev = list_next(l2arc_dev_list, dev);
5433 if (vd == dev->l2ad_vdev) {
5434 remdev = dev;
5435 break;
5436 }
5437 }
5438 ASSERT(remdev != NULL);
5439
5440 /*
5441 * Remove device from global list
5442 */
5443 list_remove(l2arc_dev_list, remdev);
5444 l2arc_dev_last = NULL; /* may have been invalidated */
5445 atomic_dec_64(&l2arc_ndev);
5446 mutex_exit(&l2arc_dev_mtx);
5447
5448 /*
5449 * Clear all buflists and ARC references. L2ARC device flush.
5450 */
5451 l2arc_evict(remdev, 0, B_TRUE);
5452 list_destroy(remdev->l2ad_buflist);
5453 kmem_free(remdev->l2ad_buflist, sizeof (list_t));
5454 kmem_free(remdev, sizeof (l2arc_dev_t));
5455 }
5456
5457 void
5458 l2arc_init(void)
5459 {
5460 l2arc_thread_exit = 0;
5461 l2arc_ndev = 0;
5462 l2arc_writes_sent = 0;
5463 l2arc_writes_done = 0;
5464
5465 mutex_init(&l2arc_feed_thr_lock, NULL, MUTEX_DEFAULT, NULL);
5466 cv_init(&l2arc_feed_thr_cv, NULL, CV_DEFAULT, NULL);
5467 mutex_init(&l2arc_dev_mtx, NULL, MUTEX_DEFAULT, NULL);
5468 mutex_init(&l2arc_buflist_mtx, NULL, MUTEX_DEFAULT, NULL);
5469 mutex_init(&l2arc_free_on_write_mtx, NULL, MUTEX_DEFAULT, NULL);
5470
5471 l2arc_dev_list = &L2ARC_dev_list;
5472 l2arc_free_on_write = &L2ARC_free_on_write;
5473 list_create(l2arc_dev_list, sizeof (l2arc_dev_t),
5474 offsetof(l2arc_dev_t, l2ad_node));
5475 list_create(l2arc_free_on_write, sizeof (l2arc_data_free_t),
5476 offsetof(l2arc_data_free_t, l2df_list_node));
5477 }
5478
5479 void
5480 l2arc_fini(void)
5481 {
5482 /*
5483 * This is called from dmu_fini(), which is called from spa_fini();
5484 * Because of this, we can assume that all l2arc devices have
5485 * already been removed when the pools themselves were removed.
5486 */
5487
5488 l2arc_do_free_on_write();
5489
5490 mutex_destroy(&l2arc_feed_thr_lock);
5491 cv_destroy(&l2arc_feed_thr_cv);
5492 mutex_destroy(&l2arc_dev_mtx);
5493 mutex_destroy(&l2arc_buflist_mtx);
5494 mutex_destroy(&l2arc_free_on_write_mtx);
5495
5496 list_destroy(l2arc_dev_list);
5497 list_destroy(l2arc_free_on_write);
5498 }
5499
5500 void
5501 l2arc_start(void)
5502 {
5503 if (!(spa_mode_global & FWRITE))
5504 return;
5505
5506 (void) thread_create(NULL, 0, l2arc_feed_thread, NULL, 0, &p0,
5507 TS_RUN, minclsyspri);
5508 }
5509
5510 void
5511 l2arc_stop(void)
5512 {
5513 if (!(spa_mode_global & FWRITE))
5514 return;
5515
5516 mutex_enter(&l2arc_feed_thr_lock);
5517 cv_signal(&l2arc_feed_thr_cv); /* kick thread out of startup */
5518 l2arc_thread_exit = 1;
5519 while (l2arc_thread_exit != 0)
5520 cv_wait(&l2arc_feed_thr_cv, &l2arc_feed_thr_lock);
5521 mutex_exit(&l2arc_feed_thr_lock);
5522 }
5523
5524 #if defined(_KERNEL) && defined(HAVE_SPL)
5525 EXPORT_SYMBOL(arc_read);
5526 EXPORT_SYMBOL(arc_buf_remove_ref);
5527 EXPORT_SYMBOL(arc_buf_info);
5528 EXPORT_SYMBOL(arc_getbuf_func);
5529 EXPORT_SYMBOL(arc_add_prune_callback);
5530 EXPORT_SYMBOL(arc_remove_prune_callback);
5531
5532 module_param(zfs_arc_min, ulong, 0644);
5533 MODULE_PARM_DESC(zfs_arc_min, "Min arc size");
5534
5535 module_param(zfs_arc_max, ulong, 0644);
5536 MODULE_PARM_DESC(zfs_arc_max, "Max arc size");
5537
5538 module_param(zfs_arc_meta_limit, ulong, 0644);
5539 MODULE_PARM_DESC(zfs_arc_meta_limit, "Meta limit for arc size");
5540
5541 module_param(zfs_arc_meta_prune, int, 0644);
5542 MODULE_PARM_DESC(zfs_arc_meta_prune, "Bytes of meta data to prune");
5543
5544 module_param(zfs_arc_grow_retry, int, 0644);
5545 MODULE_PARM_DESC(zfs_arc_grow_retry, "Seconds before growing arc size");
5546
5547 module_param(zfs_arc_shrink_shift, int, 0644);
5548 MODULE_PARM_DESC(zfs_arc_shrink_shift, "log2(fraction of arc to reclaim)");
5549
5550 module_param(zfs_arc_p_min_shift, int, 0644);
5551 MODULE_PARM_DESC(zfs_arc_p_min_shift, "arc_c shift to calc min/max arc_p");
5552
5553 module_param(zfs_disable_dup_eviction, int, 0644);
5554 MODULE_PARM_DESC(zfs_disable_dup_eviction, "disable duplicate buffer eviction");
5555
5556 module_param(zfs_arc_memory_throttle_disable, int, 0644);
5557 MODULE_PARM_DESC(zfs_arc_memory_throttle_disable, "disable memory throttle");
5558
5559 module_param(zfs_arc_min_prefetch_lifespan, int, 0644);
5560 MODULE_PARM_DESC(zfs_arc_min_prefetch_lifespan, "Min life of prefetch block");
5561
5562 module_param(l2arc_write_max, ulong, 0644);
5563 MODULE_PARM_DESC(l2arc_write_max, "Max write bytes per interval");
5564
5565 module_param(l2arc_write_boost, ulong, 0644);
5566 MODULE_PARM_DESC(l2arc_write_boost, "Extra write bytes during device warmup");
5567
5568 module_param(l2arc_headroom, ulong, 0644);
5569 MODULE_PARM_DESC(l2arc_headroom, "Number of max device writes to precache");
5570
5571 module_param(l2arc_headroom_boost, ulong, 0644);
5572 MODULE_PARM_DESC(l2arc_headroom_boost, "Compressed l2arc_headroom multiplier");
5573
5574 module_param(l2arc_feed_secs, ulong, 0644);
5575 MODULE_PARM_DESC(l2arc_feed_secs, "Seconds between L2ARC writing");
5576
5577 module_param(l2arc_feed_min_ms, ulong, 0644);
5578 MODULE_PARM_DESC(l2arc_feed_min_ms, "Min feed interval in milliseconds");
5579
5580 module_param(l2arc_noprefetch, int, 0644);
5581 MODULE_PARM_DESC(l2arc_noprefetch, "Skip caching prefetched buffers");
5582
5583 module_param(l2arc_nocompress, int, 0644);
5584 MODULE_PARM_DESC(l2arc_nocompress, "Skip compressing L2ARC buffers");
5585
5586 module_param(l2arc_feed_again, int, 0644);
5587 MODULE_PARM_DESC(l2arc_feed_again, "Turbo L2ARC warmup");
5588
5589 module_param(l2arc_norw, int, 0644);
5590 MODULE_PARM_DESC(l2arc_norw, "No reads during writes");
5591
5592 #endif