arc.c revision cee972f85776929f50e2703975d7fa1767457344
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
/*
* DVA-based Adjustable Relpacement Cache
*
* While much of the theory of operation and algorithms used here
* are based on the self-tuning, low overhead replacement cache
* presented by Megiddo and Modha at FAST 2003, there are some
* significant differences:
*
* 1. The Megiddo and Modha model assumes any page is evictable.
* Pages in its cache cannot be "locked" into memory. This makes
* the eviction algorithm simple: evict the last page in the list.
* This also make the performance characteristics easy to reason
* about. Our cache is not so simple. At any given moment, some
* subset of the blocks in the cache are un-evictable because we
* have handed out a reference to them. Blocks are only evictable
* when there are no external references active. This makes
* eviction far more problematic: we choose to evict the evictable
* blocks that are the "lowest" in the list.
*
* There are times when it is not possible to evict the requested
* space. In these circumstances we are unable to adjust the cache
* size. To prevent the cache growing unbounded at these times we
* implement a "cache throttle" that slowes the flow of new data
* into the cache until we can make space avaiable.
*
* 2. The Megiddo and Modha model assumes a fixed cache size.
* Pages are evicted when the cache is full and there is a cache
* miss. Our model has a variable sized cache. It grows with
* high use, but also tries to react to memory preasure from the
* operating system: decreasing its size when system memory is
* tight.
*
* 3. The Megiddo and Modha model assumes a fixed page size. All
* elements of the cache are therefor exactly the same size. So
* when adjusting the cache size following a cache miss, its simply
* a matter of choosing a single page to evict. In our model, we
* have variable sized cache blocks (rangeing from 512 bytes to
* 128K bytes). We therefor choose a set of blocks to evict to make
* space for a cache miss that approximates as closely as possible
* the space used by the new block.
*
* See also: "ARC: A Self-Tuning, Low Overhead Replacement Cache"
* by N. Megiddo & D. Modha, FAST 2003
*/
/*
* The locking model:
*
* A new reference to a cache buffer can be obtained in two
* ways: 1) via a hash table lookup using the DVA as a key,
* or 2) via one of the ARC lists. The arc_read() inerface
* uses method 1, while the internal arc algorithms for
* adjusting the cache use method 2. We therefor provide two
* types of locks: 1) the hash table lock array, and 2) the
* arc list locks.
*
* Buffers do not have their own mutexs, rather they rely on the
* hash table mutexs for the bulk of their protection (i.e. most
* fields in the arc_buf_hdr_t are protected by these mutexs).
*
* buf_hash_find() returns the appropriate mutex (held) when it
* locates the requested buffer in the hash table. It returns
* NULL for the mutex if the buffer was not in the table.
*
* buf_hash_remove() expects the appropriate hash mutex to be
* already held before it is invoked.
*
* Each arc state also has a mutex which is used to protect the
* buffer list associated with the state. When attempting to
* obtain a hash table lock while holding an arc list lock you
* must use: mutex_tryenter() to avoid deadlock. Also note that
* the "top" state mutex must be held before the "bot" state mutex.
*
* Note that the majority of the performance stats are manipulated
* with atomic operations.
*/
#include <sys/zfs_context.h>
#include <sys/refcount.h>
#ifdef _KERNEL
#endif
static kmutex_t arc_reclaim_thr_lock;
static uint8_t arc_thread_exit;
#define ARC_REDUCE_DNLC_PERCENT 3
typedef enum arc_reclaim_strategy {
ARC_RECLAIM_AGGR, /* Aggressive reclaim strategy */
ARC_RECLAIM_CONS /* Conservative reclaim strategy */
/* number of seconds before growing cache again */
static int arc_grow_retry = 60;
static kmutex_t arc_reclaim_lock;
static int arc_dead;
/*
* Note that buffers can be on one of 5 states:
* ARC_anon - anonymous (discussed below)
* ARC_mru_top - recently used, currently cached
* ARC_mru_bot - recentely used, no longer in cache
* ARC_mfu_top - frequently used, currently cached
* ARC_mfu_bot - frequently used, no longer in cache
* When there are no active references to the buffer, they
* are linked onto one of the lists in arc. These are the
* only buffers that can be evicted or deleted.
*
* Anonymous buffers are buffers that are not associated with
* a DVA. These are buffers that hold dirty block copies
* before they are written to stable storage. By definition,
* they are "ref'd" and are considered part of arc_mru_top
* that cannot be freed. Generally, they will aquire a DVA
* as they are written and migrate onto the arc_mru_top list.
*/
typedef struct arc_state {
} arc_state_t;
/* The 5 states: */
static arc_state_t ARC_anon;
static arc_state_t ARC_mru_top;
static arc_state_t ARC_mru_bot;
static arc_state_t ARC_mfu_top;
static arc_state_t ARC_mfu_bot;
static struct arc {
uint64_t p; /* Target size (in bytes) of mru_top */
uint64_t c; /* Target size of cache (in bytes) */
/* performance stats */
int no_grow; /* Don't try to grow cache size */
} arc;
/* Default amount to grow arc.incr */
/* > 0 ==> time to increment arc.c */
static uint64_t arc_tempreserve;
typedef struct arc_callback arc_callback_t;
struct arc_callback {
void *acb_private;
};
struct arc_buf_hdr {
/* immutable */
/* protected by hash lock */
/* protected by arc state mutex */
/* updated atomically */
/* self protecting */
};
/*
* Private ARC flags. These flags are private ARC only flags that will show up
* in b_flags in the arc_hdr_buf_t. Some flags are publicly declared, and can
* be passed in as arc_flags in things like arc_read. However, these flags
* should never be passed and should only be set by ARC code. When adding new
* public flags, make sure not to smash the private ones.
*/
/*
* Hash table routines
*/
#define HT_LOCK_PAD 64
struct ht_lock {
#ifdef _KERNEL
#endif
};
#define BUF_LOCKS 256
typedef struct buf_hash_table {
static buf_hash_table_t buf_hash_table;
static uint64_t
{
int i;
for (i = 0; i < sizeof (dva_t); i++)
return (crc);
}
static arc_buf_hdr_t *
{
return (buf);
}
}
return (NULL);
}
/*
* Insert an entry into the hash table. If there is already an element
* equal to elem in the hash table, then the already existing element
* will be returned and the new element will not be inserted.
* Otherwise returns NULL.
*/
static kthread_t *fbufs_lastthread;
static arc_buf_hdr_t *
{
return (fbuf);
}
/* collect some hash table performance data */
if (i > 0) {
if (i == 1)
}
continue;
}
return (NULL);
}
static void
{
}
/* collect some hash table performance data */
}
/*
* Global data structures and functions for the buf kmem cache.
*/
static kmem_cache_t *hdr_cache;
static kmem_cache_t *buf_cache;
static void
buf_fini(void)
{
int i;
for (i = 0; i < BUF_LOCKS; i++)
}
/*
* Constructor callback - called when the cache is empty
* and a new buf is requested.
*/
/* ARGSUSED */
static int
{
return (0);
}
/*
* Destructor callback - called when a cached buf is
* no longer required.
*/
/* ARGSUSED */
static void
{
}
void arc_kmem_reclaim(void);
/*
* Reclaim callback -- invoked when memory is low.
*/
/* ARGSUSED */
static void
{
dprintf("hdr_recl called\n");
}
static void
buf_init(void)
{
int i, j;
/*
* The hash table is big enough to fill all of physical memory
* with an average 4k block size. The table will take up
* pointers).
*/
hsize <<= 1;
for (i = 0; i < 256; i++)
for (i = 0; i < BUF_LOCKS; i++) {
}
}
#define ARC_TAG (void *)0x05201962
static void
{
}
}
static int
{
int cnt;
}
return (cnt);
}
/*
* Move the supplied buffer to the indicated state. The mutex
* for the buffer must be held by the caller.
*/
static void
{
/*
* If this buffer is evictable, transfer it from the
* old state list to the new state list.
*/
int drop_mutex = FALSE;
drop_mutex = TRUE;
}
if (drop_mutex)
}
int drop_mutex = FALSE;
drop_mutex = TRUE;
}
if (drop_mutex)
}
}
}
/*
* If this buffer isn't being transferred to the MRU-top
* state, it's safe to clear its prefetch flag
*/
}
/* we should only be here if we are deleting state */
} else while (buf) {
}
}
{
hdr->b_arc_access = 0;
return (buf);
}
static void
{
/*
* We can be called with an arc state lock held,
* so we can't hold a hash lock here.
* ASSERT(not in hash table)
*/
}
}
}
void
{
int freeable;
}
return;
}
/* don't free buffers that are in the middle of an async write */
if (freeable)
}
int
{
}
/*
* Evict buffers from list until we've removed the specified number of
* bytes. Move the removed buffers to the appropriate evict state.
*/
static uint64_t
{
uint64_t bytes_evicted = 0;
else
if (mutex_tryenter(hash_lock)) {
if (bytes_evicted >= bytes)
break;
} else {
}
}
if (bytes_evicted < bytes)
dprintf("only evicted %lld bytes from %x",
return (bytes_evicted);
}
/*
* Remove buffers from list until we've removed the specified number of
* bytes. Destroy the buffers that are removed.
*/
static void
{
uint_t bufs_skipped = 0;
uint64_t bytes_deleted = 0;
top:
if (mutex_tryenter(hash_lock)) {
break;
} else {
if (bytes < 0) {
goto top;
}
bufs_skipped += 1;
}
}
if (bufs_skipped) {
}
if (bytes_deleted < bytes)
dprintf("only deleted %lld bytes from %p",
}
static void
arc_adjust(void)
{
}
if (mru_over > 0) {
}
}
}
- arc.c*2;
}
}
}
/*
* Flush all *evictable* data from the cache.
* NOTE: this will not touch "active" (i.e. referenced) data.
*/
void
arc_flush(void)
{
}
void
arc_kmem_reclaim(void)
{
/* Remove 6.25% */
/*
* We need arc_reclaim_lock because we don't want multiple
* threads trying to reclaim concurrently.
*/
/*
* umem calls the reclaim func when we destroy the buf cache,
* which is after we do arc_fini(). So we set a flag to prevent
* accessing the destroyed mutexes and lists.
*/
if (arc_dead)
return;
arc_adjust();
/* Cool it for a while */
}
static int
arc_reclaim_needed(void)
{
#ifdef _KERNEL
/*
* take 'desfree' extra pages, so we reclaim sooner, rather than later
*/
/*
* check that we're out of range of the pageout scanner. It starts to
* schedule paging if freemem is less than lotsfree and needfree.
* lotsfree is the high-water mark for pageout, and needfree is the
* number of needed free pages. We add extra pages here to make sure
* the scanner doesn't start up while we're freeing memory.
*/
return (1);
/*
* check to make sure that swapfs has enough space so that anon
* reservations can still succeeed. anon_resvmem() checks that the
* availrmem is greater than swapfs_minfree, and the number of reserved
* swap pages. We also add a bit of extra here just to prevent
* circumstances from getting really dire.
*/
return (1);
/*
* If we're on an i386 platform, it's possible that we'll exhaust the
* kernel heap space before we ever run out of available physical
* memory. Most checks of the size of the heap_area compare against
* tune.t_minarmem, which is the minimum available real memory that we
* can have in the system. However, this is generally fixed at 25 pages
* which is so low that it's useless. In this comparison, we seek to
* calculate the total heap-size, and reclaim if more than 3/4ths of the
* heap is allocated. (Or, in the caclulation, if less than 1/4th is
* free)
*/
#if defined(__i386)
return (1);
#endif
#else
if (spa_get_random(100) == 0)
return (1);
#endif
return (0);
}
static void
{
size_t i;
extern kmem_cache_t *zio_buf_cache[];
#ifdef _KERNEL
/*
* First purge some DNLC entries, in case the DNLC is using
* up too much memory.
*/
#endif
/*
* an agressive reclamation will shrink the cache size as well as reap
* free kmem buffers. The arc_kmem_reclaim function is called when the
* header-cache is reaped, so we only reap the header cache if we're
* performing an agressive reclaim. If we're not, just clean the kmem
* buffer caches.
*/
if (strat == ARC_RECLAIM_AGGR)
for (i = 0; i < SPA_MAXBLOCKSIZE >> SPA_MINBLOCKSHIFT; i++) {
if (zio_buf_cache[i] != prev_cache) {
prev_cache = zio_buf_cache[i];
}
}
}
static void
arc_reclaim_thread(void)
{
while (arc_thread_exit == 0) {
if (arc_reclaim_needed()) {
if (last_reclaim == ARC_RECLAIM_CONS) {
} else {
}
} else {
}
/* reset the growth delay for every reclaim */
}
/* block until needed, or one second, whichever is shorter */
(void) cv_timedwait(&arc_reclaim_thr_cv,
}
arc_thread_exit = 0;
thread_exit();
}
static void
{
/*
* If we're within (2 * maxblocksize) bytes of the target
* cache size, increment the target cache size
*/
if (arc_reclaim_needed()) {
return;
}
return;
/*
* return true if we successfully grow, or if there's enough space that
* we don't have to grow. Above, we return false if we can't grow, or
* if we shouldn't because a reclaim is in progress.
*/
if (arc.size_check > 0) {
}
else
if (arc.size_check > 0) {
}
else
}
}
/*
* check if the cache has reached its limits and eviction is required prior to
* insert. In this situation, we want to evict if no_grow is set Otherwise, the
* cache is either big enough that we can insert, or a arc_try_grow will result
* in more space being made available.
*/
static int
{
if (arc_reclaim_needed())
return (1);
return (1);
return (0);
}
/*
* The state, supplied as the first argument, is going to have something
* inserted on its behalf. So, determine which cache must be victimized to
* satisfy an insertion for this state. We have the following cases:
*
* 1. Insert for MRU, p > sizeof(arc.anon + arc.mru_top) ->
* In this situation if we're out of space, but the resident size of the MFU is
* under the limit, victimize the MFU cache to satisfy this insertion request.
*
* 2. Insert for MRU, p <= sizeof(arc.anon + arc.mru_top) ->
* Here, we've used up all of the available space for the MRU, so we need to
* evict from our own cache instead. Evict from the set of resident MRU
* entries.
*
* 3. Insert for MFU (c - p) > sizeof(arc.mfu_top) ->
* c minus p represents the MFU space in the cache, since p is the size of the
* cache that is dedicated to the MRU. In this situation there's still space on
* the MFU side, so the MRU side needs to be victimized.
*
* 4. Insert for MFU (c - p) < sizeof(arc.mfu_top) ->
* MFU's resident set is consuming more space than it has been allotted. In
* this situation, we must victimize our own cache, the MFU, for this insertion.
*/
static void
{
/* case 1 */
arc_adjust();
}
} else {
/* case 2 */
arc_adjust();
}
}
} else {
/* MFU_top case */
/* case 3 */
arc_adjust();
}
} else {
/* case 4 */
arc_adjust();
}
}
}
}
/*
* This routine is called whenever a buffer is accessed.
*/
static void
{
/*
* This buffer is not in the cache, and does not
* appear in our "ghost" list. Add the new buffer
* to the MRU state.
*/
if (arc_evict_needed()) {
}
buf);
/*
* If we are using less than 2/3 of our total target
* cache size, bump up the target size for the MRU
* list.
*/
}
/*
* If this buffer is in the MRU-top state and has the prefetch
* flag, the first read was actually part of a prefetch. In
* this situation, we simply want to clear the flag and return.
* A subsequent access should bump this into the MFU state.
*/
return;
}
/*
* This buffer has been "accessed" only once so far,
* but it is still in the cache. Move it to the MFU
* state.
*/
/*
* More than 125ms have passed since we
* instantiated this buffer. Move it to the
* most frequently used state.
*/
arc_buf_hdr_t *, buf);
}
/*
* This buffer has been "accessed" recently, but
* was evicted from the cache. Move it to the
* MFU state.
*/
arc_buf_hdr_t *, buf);
} else {
arc_buf_hdr_t *, buf);
}
if (arc_evict_needed()) {
}
/* Bump up the target size of the MRU list */
/*
* This buffer has been accessed more than once and is
* still in the cache. Keep it in the MFU state.
*
* NOTE: the add_reference() that occurred when we did
* the arc_read() should have kicked this off the list,
* so even if it was a prefetch, it will be put back at
* the head of the list when we remove_reference().
*/
/*
* This buffer has been accessed more than once but has
* been evicted from the cache. Move it back to the
* MFU state.
*/
if (arc_evict_needed()) {
}
/* Bump up the target size for the MFU list */
arc_buf_hdr_t *, buf);
} else {
ASSERT(!"invalid arc state");
}
}
/* a generic arc_done_func_t which you can use */
/* ARGSUSED */
void
{
}
/* a generic arc_done_func_t which you can use */
void
{
} else {
}
}
static void
{
if (!HDR_FREED_IN_READ(hdr)) {
&hash_lock);
/*
* Buffer was inserted into hash-table and removed from lists
* prior to starting I/O. We should find this header, since
* it's in the hash table, and it should be legit since it's
* not possible to evict it during the I/O.
*/
}
/* byteswap if necessary */
/* create copies of the data buffer for the callers */
}
} else {
/*
* The caller did not provide a callback function.
* In this case, we should just remove the reference.
*/
if (HDR_FREED_IN_READ(hdr)) {
acb->acb_private);
} else {
acb->acb_private);
}
}
}
}
if (!HDR_FREED_IN_READ(hdr)) {
/*
* Only call arc_access on anonymous buffers. This is because
* if we've issued an I/O for an evicted buffer, we've already
* called arc_access (to prevent any simultaneous readers from
* getting confused).
*/
} else {
/*
* This block was freed while we waited for the read to
* complete. It has been removed from the hash table and
* moved to the anonymous state (so that it won't show up
* in the cache).
*/
}
/* execute each callback and free its structure */
}
}
if (freeable)
}
/*
* "Read" the block block at the specified DVA (in bp) via the
* cache. If the block is found in the cache, invoke the provided
* callback immediately and return. Note that the `zio' parameter
* in the callback will be NULL in this case, since no IO was
* required. If the block is not in the cache pass the read request
* on to the spa with a substitute callback function, so that the
* requested block will be added to the cache.
*
* If a read request arrives for a block that has a read in-progress,
* either wait for the in-progress read to complete (and return the
* results); or, if this is a read with a "done" func, add a record
* to the read to invoke the "done" func when the read completes,
* and return; or just return.
*
* arc_read_done() will invoke all the requested "done" functions
* for readers of this block.
*/
int
{
top:
(HDR_IO_IN_PROGRESS(hdr))));
if (HDR_IO_IN_PROGRESS(hdr)) {
KM_SLEEP);
return (0);
goto top;
}
return (0);
}
/*
* If there is already a reference on this block, create
* a new copy of the data so that we will be guaranteed
* that arc_release() will always succeed.
*/
if (done)
} else {
}
if (done)
} else {
/* this block is not in the cache */
if (exists) {
/* somebody beat us to the hash insert */
goto top; /* restart the IO request */
}
} else {
/* this block is in the ghost cache */
}
/*
* If this DVA is part of a prefetch, mark the buf
* header with the prefetch flag
*/
if (arc_flags & ARC_PREFETCH)
/*
* If the buffer has been evicted, migrate it to a present state
* before issuing the I/O. Once we drop the hash-table lock,
* the header will be marked as I/O in progress and have an
* attached buffer. At this point, anybody who finds this
* buffer ought to notice that it's legit but has a pending I/O.
*/
}
return (0);
}
/*
* arc_read() variant to support pool traversal. If the block is already
* in the ARC, make a copy of it; otherwise, the caller will do the I/O.
* The idea is that we don't want pool traversal filling up memory, but
* if the ARC already has the data anyway, we shouldn't pay for the I/O.
*/
int
{
int rc = 0;
else
if (hash_mtx)
return (rc);
}
/*
* Release this buffer from the cache. This must be done
* after a read and prior to modifying the buffer contents.
* If the buffer has more than one reference, we must make
* make a new hdr for the buffer.
*/
void
{
/* this buffer is not on any list */
/* this buffer is already released */
return;
}
/*
* Pull the data off of this buf and attach it to
* a new anonymous buf.
*/
}
nhdr->b_arc_access = 0;
} else {
hdr->b_arc_access = 0;
}
}
int
{
}
static void
{
/* this buffer is on no lists and is not in the hash table */
/* clear the "in-write" flag */
/* This write may be all-zero */
if (exists) {
/*
* This can only happen if we overwrite for
* sync-to-convergence, because we remove
* buffers from the hash table when we arc_free().
*/
}
}
}
if (acb)
}
int
{
/* this is a private buffer - no locking required */
return (0);
}
int
{
/*
* If this buffer is in the cache, release it, so it
* can be re-used.
*/
/*
* The checksum of blocks to free is not always
* preserved (eg. on the deadlist). However, if it is
* nonzero, it should match what we have in the cache.
*/
} else {
if (HDR_IO_IN_PROGRESS(ab))
ab->b_arc_access = 0;
}
}
return (0);
}
void
{
}
int
{
#ifdef ZFS_DEBUG
/*
* Once in a while, fail for no reason. Everything should cope.
*/
if (spa_get_random(10000) == 0) {
dprintf("forcing random failure\n");
return (ERESTART);
}
#endif
if (tempreserve > arc.c)
return (ENOMEM);
/*
* Throttle writes when the amount of dirty data in the cache
* gets too large. We try to keep the cache less than half full
* of dirty blocks so that our sync times don't grow too large.
* Note: if two requests come in concurrently, we might let them
* both succeed, when one of them should fail. Not a huge deal.
*
* XXX The limit should be adjusted dynamically to keep the time
* to sync a dataset fixed (around 1-5 seconds?).
*/
dprintf("failing, arc_tempreserve=%lluK anon=%lluK "
"tempreserve=%lluK arc.c=%lluK\n",
return (ERESTART);
}
return (0);
}
void
arc_init(void)
{
/* Start out with 1/8 of all memory */
#ifdef _KERNEL
/*
* On architectures where the physical memory can be larger
* than the addressable space (intel in 32-bit mode), we may
* need to limit the cache to 1/8 of VM size.
*/
#endif
/* set min cache to 1/32 of all memory, or 64MB, whichever is more */
/* set max to 3/4 of all memory, or all but 1GB, whichever is more */
else
/* if kmem_flags are set, lets try to use less memory */
if (kmem_debugging())
buf_init();
arc_thread_exit = 0;
}
void
arc_fini(void)
{
arc_thread_exit = 1;
while (arc_thread_exit != 0)
arc_flush();
buf_fini();
}