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