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