kmem.c revision 9dd77bc84fd62eb844d67cc7311833ea3ea6c889
/*
* 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 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
/*
* Kernel memory allocator, as described in the following two papers and a
* statement about the consolidator:
*
* Jeff Bonwick,
* The Slab Allocator: An Object-Caching Kernel Memory Allocator.
* Proceedings of the Summer 1994 Usenix Conference.
*
* Jeff Bonwick and Jonathan Adams,
* Magazines and vmem: Extending the Slab Allocator to Many CPUs and
* Arbitrary Resources.
* Proceedings of the 2001 Usenix Conference.
*
* kmem Slab Consolidator Big Theory Statement:
*
* 1. Motivation
*
* As stated in Bonwick94, slabs provide the following advantages over other
* allocation structures in terms of memory fragmentation:
*
* - Internal fragmentation (per-buffer wasted space) is minimal.
* - Severe external fragmentation (unused buffers on the free list) is
* unlikely.
*
* Segregating objects by size eliminates one source of external fragmentation,
* and according to Bonwick:
*
* The other reason that slabs reduce external fragmentation is that all
* objects in a slab are of the same type, so they have the same lifetime
* distribution. The resulting segregation of short-lived and long-lived
* objects at slab granularity reduces the likelihood of an entire page being
* held hostage due to a single long-lived allocation [Barrett93, Hanson90].
*
* While unlikely, severe external fragmentation remains possible. Clients that
* allocate both short- and long-lived objects from the same cache cannot
* anticipate the distribution of long-lived objects within the allocator's slab
* implementation. Even a small percentage of long-lived objects distributed
* randomly across many slabs can lead to a worst case scenario where the client
* frees the majority of its objects and the system gets back almost none of the
* slabs. Despite the client doing what it reasonably can to help the system
* reclaim memory, the allocator cannot shake free enough slabs because of
* lonely allocations stubbornly hanging on. Although the allocator is in a
* position to diagnose the fragmentation, there is nothing that the allocator
* by itself can do about it. It only takes a single allocated object to prevent
* an entire slab from being reclaimed, and any object handed out by
* kmem_cache_alloc() is by definition in the client's control. Conversely,
* although the client is in a position to move a long-lived object, it has no
* way of knowing if the object is causing fragmentation, and if so, where to
* move it. A solution necessarily requires further cooperation between the
* allocator and the client.
*
* 2. Move Callback
*
* The kmem slab consolidator therefore adds a move callback to the
* kmem caches that supply a function to move objects from one memory location
* to another. In a situation of low memory kmem attempts to consolidate all of
* a cache's slabs at once; otherwise it works slowly to bring external
* fragmentation within the 1/8 limit guaranteed for internal fragmentation,
* thereby helping to avoid a low memory situation in the future.
*
* The callback has the following signature:
*
* kmem_cbrc_t move(void *old, void *new, size_t size, void *user_arg)
*
* It supplies the kmem client with two addresses: the allocated object that
* kmem wants to move and a buffer selected by kmem for the client to use as the
* copy destination. The callback is kmem's way of saying "Please get off of
* this buffer and use this one instead." kmem knows where it wants to move the
* object in order to best reduce fragmentation. All the client needs to know
* about the second argument (void *new) is that it is an allocated, constructed
* object ready to take the contents of the old object. When the move function
* is called, the system is likely to be low on memory, and the new object
* spares the client from having to worry about allocating memory for the
* requested move. The third argument supplies the size of the object, in case a
* single move function handles multiple caches whose objects differ only in
* size (such as zio_buf_512, zio_buf_1024, etc). Finally, the same optional
* user argument passed to the constructor, destructor, and reclaim functions is
* also passed to the move callback.
*
* 2.1 Setting the Move Callback
*
* The client sets the move callback after creating the cache and before
* allocating from it:
*
* object_cache = kmem_cache_create(...);
* kmem_cache_set_move(object_cache, object_move);
*
* 2.2 Move Callback Return Values
*
* Only the client knows about its own data and when is a good time to move it.
* The client is cooperating with kmem to return unused memory to the system,
* and kmem respectfully accepts this help at the client's convenience. When
* asked to move an object, the client can respond with any of the following:
*
* typedef enum kmem_cbrc {
* KMEM_CBRC_YES,
* KMEM_CBRC_NO,
* KMEM_CBRC_LATER,
* KMEM_CBRC_DONT_NEED,
* KMEM_CBRC_DONT_KNOW
* } kmem_cbrc_t;
*
* The client must not explicitly kmem_cache_free() either of the objects passed
* to the callback, since kmem wants to free them directly to the slab layer
* (bypassing the per-CPU magazine layer). The response tells kmem which of the
* objects to free:
*
* YES: (Did it) The client moved the object, so kmem frees the old one.
* NO: (Never) The client refused, so kmem frees the new object (the
* unused copy destination). kmem also marks the slab of the old
* object so as not to bother the client with further callbacks for
* that object as long as the slab remains on the partial slab list.
* (The system won't be getting the slab back as long as the
* immovable object holds it hostage, so there's no point in moving
* any of its objects.)
* LATER: The client is using the object and cannot move it now, so kmem
* frees the new object (the unused copy destination). kmem still
* attempts to move other objects off the slab, since it expects to
* succeed in clearing the slab in a later callback. The client
* should use LATER instead of NO if the object is likely to become
* movable very soon.
* DONT_NEED: The client no longer needs the object, so kmem frees the old along
* with the new object (the unused copy destination). This response
* is the client's opportunity to be a model citizen and give back as
* much as it can.
* DONT_KNOW: The client does not know about the object because
* a) the client has just allocated the object and not yet put it
* wherever it expects to find known objects
* b) the client has removed the object from wherever it expects to
* find known objects and is about to free it, or
* c) the client has freed the object.
* In all these cases (a, b, and c) kmem frees the new object (the
* unused copy destination) and searches for the old object in the
* magazine layer. If found, the object is removed from the magazine
* layer and freed to the slab layer so it will no longer hold the
* slab hostage.
*
* 2.3 Object States
*
* Neither kmem nor the client can be assumed to know the object's whereabouts
* at the time of the callback. An object belonging to a kmem cache may be in
* any of the following states:
*
* 1. Uninitialized on the slab
* 2. Allocated from the slab but not constructed (still uninitialized)
* 3. Allocated from the slab, constructed, but not yet ready for business
* (not in a valid state for the move callback)
* 4. In use (valid and known to the client)
* 5. About to be freed (no longer in a valid state for the move callback)
* 6. Freed to a magazine (still constructed)
* 7. Allocated from a magazine, not yet ready for business (not in a valid
* state for the move callback), and about to return to state #4
* 8. Deconstructed on a magazine that is about to be freed
* 9. Freed to the slab
*
* Since the move callback may be called at any time while the object is in any
* of the above states (except state #1), the client needs a safe way to
* determine whether or not it knows about the object. Specifically, the client
* needs to know whether or not the object is in state #4, the only state in
* which a move is valid. If the object is in any other state, the client should
* immediately return KMEM_CBRC_DONT_KNOW, since it is unsafe to access any of
* the object's fields.
*
* Note that although an object may be in state #4 when kmem initiates the move
* request, the object may no longer be in that state by the time kmem actually
* calls the move function. Not only does the client free objects
* asynchronously, kmem itself puts move requests on a queue where thay are
* pending until kmem processes them from another context. Also, objects freed
* to a magazine appear allocated from the point of view of the slab layer, so
* kmem may even initiate requests for objects in a state other than state #4.
*
* 2.3.1 Magazine Layer
*
* An important insight revealed by the states listed above is that the magazine
* layer is populated only by kmem_cache_free(). Magazines of constructed
* objects are never populated directly from the slab layer (which contains raw,
* unconstructed objects). Whenever an allocation request cannot be satisfied
* from the magazine layer, the magazines are bypassed and the request is
* satisfied from the slab layer (creating a new slab if necessary). kmem calls
* the object constructor only when allocating from the slab layer, and only in
* response to kmem_cache_alloc() or to prepare the destination buffer passed in
* the move callback. kmem does not preconstruct objects in anticipation of
* kmem_cache_alloc().
*
* 2.3.2 Object Constructor and Destructor
*
* If the client supplies a destructor, it must be valid to call the destructor
* on a newly created object (immediately after the constructor).
*
* 2.4 Recognizing Known Objects
*
* There is a simple test to determine safely whether or not the client knows
* about a given object in the move callback. It relies on the fact that kmem
* guarantees that the object of the move callback has only been touched by the
* client itself or else by kmem. kmem does this by ensuring that none of the
* cache's slabs are freed to the virtual memory (VM) subsystem while a move
* callback is pending. When the last object on a slab is freed, if there is a
* pending move, kmem puts the slab on a per-cache dead list and defers freeing
* slabs on that list until all pending callbacks are completed. That way,
* clients can be certain that the object of a move callback is in one of the
* states listed above, making it possible to distinguish known objects (in
* state #4) using the two low order bits of any pointer member (with the
* exception of 'char *' or 'short *' which may not be 4-byte aligned on some
* platforms).
*
* The test works as long as the client always transitions objects from state #4
* (known, in use) to state #5 (about to be freed, invalid) by setting the low
* order bit of the client-designated pointer member. Since kmem only writes
* invalid memory patterns, such as 0xbaddcafe to uninitialized memory and
* 0xdeadbeef to freed memory, any scribbling on the object done by kmem is
* guaranteed to set at least one of the two low order bits. Therefore, given an
* object with a back pointer to a 'container_t *o_container', the client can
* test
*
* container_t *container = object->o_container;
* if ((uintptr_t)container & 0x3) {
* return (KMEM_CBRC_DONT_KNOW);
* }
*
* Typically, an object will have a pointer to some structure with a list or
* hash where objects from the cache are kept while in use. Assuming that the
* client has some way of knowing that the container structure is valid and will
* not go away during the move, and assuming that the structure includes a lock
* to protect whatever collection is used, then the client would continue as
* follows:
*
* // Ensure that the container structure does not go away.
* if (container_hold(container) == 0) {
* return (KMEM_CBRC_DONT_KNOW);
* }
* mutex_enter(&container->c_objects_lock);
* if (container != object->o_container) {
* mutex_exit(&container->c_objects_lock);
* container_rele(container);
* return (KMEM_CBRC_DONT_KNOW);
* }
*
* At this point the client knows that the object cannot be freed as long as
* c_objects_lock is held. Note that after acquiring the lock, the client must
* recheck the o_container pointer in case the object was removed just before
* acquiring the lock.
*
* When the client is about to free an object, it must first remove that object
* from the list, hash, or other structure where it is kept. At that time, to
* mark the object so it can be distinguished from the remaining, known objects,
* the client sets the designated low order bit:
*
* mutex_enter(&container->c_objects_lock);
* object->o_container = (void *)((uintptr_t)object->o_container | 0x1);
* list_remove(&container->c_objects, object);
* mutex_exit(&container->c_objects_lock);
*
* In the common case, the object is freed to the magazine layer, where it may
* be reused on a subsequent allocation without the overhead of calling the
* constructor. While in the magazine it appears allocated from the point of
* view of the slab layer, making it a candidate for the move callback. Most
* objects unrecognized by the client in the move callback fall into this
* category and are cheaply distinguished from known objects by the test
* described earlier. Since recognition is cheap for the client, and searching
* magazines is expensive for kmem, kmem defers searching until the client first
* returns KMEM_CBRC_DONT_KNOW. As long as the needed effort is reasonable, kmem
* elsewhere does what it can to avoid bothering the client unnecessarily.
*
* Invalidating the designated pointer member before freeing the object marks
* the object to be avoided in the callback, and conversely, assigning a valid
* value to the designated pointer member after allocating the object makes the
* object fair game for the callback:
*
* ... allocate object ...
* ... set any initial state not set by the constructor ...
*
* mutex_enter(&container->c_objects_lock);
* list_insert_tail(&container->c_objects, object);
* membar_producer();
* object->o_container = container;
* mutex_exit(&container->c_objects_lock);
*
* Note that everything else must be valid before setting o_container makes the
* object fair game for the move callback. The membar_producer() call ensures
* that all the object's state is written to memory before setting the pointer
* that transitions the object from state #3 or #7 (allocated, constructed, not
* yet in use) to state #4 (in use, valid). That's important because the move
* function has to check the validity of the pointer before it can safely
* acquire the lock protecting the collection where it expects to find known
* objects.
*
* This method of distinguishing known objects observes the usual symmetry:
* invalidating the designated pointer is the first thing the client does before
* freeing the object, and setting the designated pointer is the last thing the
* client does after allocating the object. Of course, the client is not
* required to use this method. Fundamentally, how the client recognizes known
* objects is completely up to the client, but this method is recommended as an
* efficient and safe way to take advantage of the guarantees made by kmem. If
* the entire object is arbitrary data without any markable bits from a suitable
* pointer member, then the client must find some other method, such as
* searching a hash table of known objects.
*
* 2.5 Preventing Objects From Moving
*
* Besides a way to distinguish known objects, the other thing that the client
* needs is a strategy to ensure that an object will not move while the client
* is actively using it. The details of satisfying this requirement tend to be
* highly cache-specific. It might seem that the same rules that let a client
* remove an object safely should also decide when an object can be moved
* safely. However, any object state that makes a removal attempt invalid is
* likely to be long-lasting for objects that the client does not expect to
* remove. kmem knows nothing about the object state and is equally likely (from
* the client's point of view) to request a move for any object in the cache,
* whether prepared for removal or not. Even a low percentage of objects stuck
* in place by unremovability will defeat the consolidator if the stuck objects
* are the same long-lived allocations likely to hold slabs hostage.
* Fundamentally, the consolidator is not aimed at common cases. Severe external
* fragmentation is a worst case scenario manifested as sparsely allocated
* slabs, by definition a low percentage of the cache's objects. When deciding
* what makes an object movable, keep in mind the goal of the consolidator: to
* bring worst-case external fragmentation within the limits guaranteed for
* internal fragmentation. Removability is a poor criterion if it is likely to
* exclude more than an insignificant percentage of objects for long periods of
* time.
*
* A tricky general solution exists, and it has the advantage of letting you
* move any object at almost any moment, practically eliminating the likelihood
* that an object can hold a slab hostage. However, if there is a cache-specific
* way to ensure that an object is not actively in use in the vast majority of
* cases, a simpler solution that leverages this cache-specific knowledge is
* preferred.
*
* 2.5.1 Cache-Specific Solution
*
* As an example of a cache-specific solution, the ZFS znode cache takes
* advantage of the fact that the vast majority of znodes are only being
* referenced from the DNLC. (A typical case might be a few hundred in active
* use and a hundred thousand in the DNLC.) In the move callback, after the ZFS
* client has established that it recognizes the znode and can access its fields
* safely (using the method described earlier), it then tests whether the znode
* is referenced by anything other than the DNLC. If so, it assumes that the
* znode may be in active use and is unsafe to move, so it drops its locks and
* returns KMEM_CBRC_LATER. The advantage of this strategy is that everywhere
* else znodes are used, no change is needed to protect against the possibility
* of the znode moving. The disadvantage is that it remains possible for an
* application to hold a znode slab hostage with an open file descriptor.
* However, this case ought to be rare and the consolidator has a way to deal
* with it: If the client responds KMEM_CBRC_LATER repeatedly for the same
* object, kmem eventually stops believing it and treats the slab as if the
* client had responded KMEM_CBRC_NO. Having marked the hostage slab, kmem can
* then focus on getting it off of the partial slab list by allocating rather
* than freeing all of its objects. (Either way of getting a slab off the
* free list reduces fragmentation.)
*
* 2.5.2 General Solution
*
* The general solution, on the other hand, requires an explicit hold everywhere
* the object is used to prevent it from moving. To keep the client locking
* strategy as uncomplicated as possible, kmem guarantees the simplifying
* assumption that move callbacks are sequential, even across multiple caches.
* Internally, a global queue processed by a single thread supports all caches
* implementing the callback function. No matter how many caches supply a move
* function, the consolidator never moves more than one object at a time, so the
* client does not have to worry about tricky lock ordering involving several
* related objects from different kmem caches.
*
* The general solution implements the explicit hold as a read-write lock, which
* allows multiple readers to access an object from the cache simultaneously
* while a single writer is excluded from moving it. A single rwlock for the
* entire cache would lock out all threads from using any of the cache's objects
* even though only a single object is being moved, so to reduce contention,
* the client can fan out the single rwlock into an array of rwlocks hashed by
* the object address, making it probable that moving one object will not
* prevent other threads from using a different object. The rwlock cannot be a
* member of the object itself, because the possibility of the object moving
* makes it unsafe to access any of the object's fields until the lock is
* acquired.
*
* Assuming a small, fixed number of locks, it's possible that multiple objects
* will hash to the same lock. A thread that needs to use multiple objects in
* the same function may acquire the same lock multiple times. Since rwlocks are
* reentrant for readers, and since there is never more than a single writer at
* a time (assuming that the client acquires the lock as a writer only when
* moving an object inside the callback), there would seem to be no problem.
* However, a client locking multiple objects in the same function must handle
* one case of potential deadlock: Assume that thread A needs to prevent both
* object 1 and object 2 from moving, and thread B, the callback, meanwhile
* tries to move object 3. It's possible, if objects 1, 2, and 3 all hash to the
* same lock, that thread A will acquire the lock for object 1 as a reader
* before thread B sets the lock's write-wanted bit, preventing thread A from
* reacquiring the lock for object 2 as a reader. Unable to make forward
* progress, thread A will never release the lock for object 1, resulting in
* deadlock.
*
* There are two ways of avoiding the deadlock just described. The first is to
* use rw_tryenter() rather than rw_enter() in the callback function when
* attempting to acquire the lock as a writer. If tryenter discovers that the
* same object (or another object hashed to the same lock) is already in use, it
* aborts the callback and returns KMEM_CBRC_LATER. The second way is to use
* rprwlock_t (declared in common/fs/zfs/sys/rprwlock.h) instead of rwlock_t,
* since it allows a thread to acquire the lock as a reader in spite of a
* waiting writer. This second approach insists on moving the object now, no
* matter how many readers the move function must wait for in order to do so,
* and could delay the completion of the callback indefinitely (blocking
* callbacks to other clients). In practice, a less insistent callback using
* rw_tryenter() returns KMEM_CBRC_LATER infrequently enough that there seems
* little reason to use anything else.
*
* Avoiding deadlock is not the only problem that an implementation using an
* explicit hold needs to solve. Locking the object in the first place (to
* prevent it from moving) remains a problem, since the object could move
* between the time you obtain a pointer to the object and the time you acquire
* the rwlock hashed to that pointer value. Therefore the client needs to
* recheck the value of the pointer after acquiring the lock, drop the lock if
* the value has changed, and try again. This requires a level of indirection:
* something that points to the object rather than the object itself, that the
* client can access safely while attempting to acquire the lock. (The object
* itself cannot be referenced safely because it can move at any time.)
* The following lock-acquisition function takes whatever is safe to reference
* (arg), follows its pointer to the object (using function f), and tries as
* often as necessary to acquire the hashed lock and verify that the object
* still has not moved:
*
* object_t *
* object_hold(object_f f, void *arg)
* {
* object_t *op;
*
* op = f(arg);
* if (op == NULL) {
* return (NULL);
* }
*
* rw_enter(OBJECT_RWLOCK(op), RW_READER);
* while (op != f(arg)) {
* rw_exit(OBJECT_RWLOCK(op));
* op = f(arg);
* if (op == NULL) {
* break;
* }
* rw_enter(OBJECT_RWLOCK(op), RW_READER);
* }
*
* return (op);
* }
*
* The OBJECT_RWLOCK macro hashes the object address to obtain the rwlock. The
* lock reacquisition loop, while necessary, almost never executes. The function
* pointer f (used to obtain the object pointer from arg) has the following type
* definition:
*
* typedef object_t *(*object_f)(void *arg);
*
* An object_f implementation is likely to be as simple as accessing a structure
* member:
*
* object_t *
* s_object(void *arg)
* {
* something_t *sp = arg;
* return (sp->s_object);
* }
*
* The flexibility of a function pointer allows the path to the object to be
* arbitrarily complex and also supports the notion that depending on where you
* are using the object, you may need to get it from someplace different.
*
* The function that releases the explicit hold is simpler because it does not
* have to worry about the object moving:
*
* void
* object_rele(object_t *op)
* {
* rw_exit(OBJECT_RWLOCK(op));
* }
*
* The caller is spared these details so that obtaining and releasing an
* explicit hold feels like a simple mutex_enter()/mutex_exit() pair. The caller
* of object_hold() only needs to know that the returned object pointer is valid
* if not NULL and that the object will not move until released.
*
* Although object_hold() prevents an object from moving, it does not prevent it
* from being freed. The caller must take measures before calling object_hold()
* (afterwards is too late) to ensure that the held object cannot be freed. The
* caller must do so without accessing the unsafe object reference, so any lock
* or reference count used to ensure the continued existence of the object must
* live outside the object itself.
*
* Obtaining a new object is a special case where an explicit hold is impossible
* for the caller. Any function that returns a newly allocated object (either as
* a return value, or as an in-out paramter) must return it already held; after
* the caller gets it is too late, since the object cannot be safely accessed
* without the level of indirection described earlier. The following
* object_alloc() example uses the same code shown earlier to transition a new
* object into the state of being recognized (by the client) as a known object.
* The function must acquire the hold (rw_enter) before that state transition
* makes the object movable:
*
* static object_t *
* object_alloc(container_t *container)
* {
* object_t *object = kmem_cache_alloc(object_cache, 0);
* ... set any initial state not set by the constructor ...
* rw_enter(OBJECT_RWLOCK(object), RW_READER);
* mutex_enter(&container->c_objects_lock);
* list_insert_tail(&container->c_objects, object);
* membar_producer();
* object->o_container = container;
* mutex_exit(&container->c_objects_lock);
* return (object);
* }
*
* Functions that implicitly acquire an object hold (any function that calls
* object_alloc() to supply an object for the caller) need to be carefully noted
* so that the matching object_rele() is not neglected. Otherwise, leaked holds
* prevent all objects hashed to the affected rwlocks from ever being moved.
*
* The pointer to a held object can be hashed to the holding rwlock even after
* the object has been freed. Although it is possible to release the hold
* after freeing the object, you may decide to release the hold implicitly in
* whatever function frees the object, so as to release the hold as soon as
* possible, and for the sake of symmetry with the function that implicitly
* acquires the hold when it allocates the object. Here, object_free() releases
* the hold acquired by object_alloc(). Its implicit object_rele() forms a
* matching pair with object_hold():
*
* void
* object_free(object_t *object)
* {
* container_t *container;
*
* ASSERT(object_held(object));
* container = object->o_container;
* mutex_enter(&container->c_objects_lock);
* object->o_container =
* (void *)((uintptr_t)object->o_container | 0x1);
* list_remove(&container->c_objects, object);
* mutex_exit(&container->c_objects_lock);
* object_rele(object);
* kmem_cache_free(object_cache, object);
* }
*
* Note that object_free() cannot safely accept an object pointer as an argument
* unless the object is already held. Any function that calls object_free()
* needs to be carefully noted since it similarly forms a matching pair with
* object_hold().
*
* To complete the picture, the following callback function implements the
* general solution by moving objects only if they are currently unheld:
*
* static kmem_cbrc_t
* object_move(void *buf, void *newbuf, size_t size, void *arg)
* {
* object_t *op = buf, *np = newbuf;
* container_t *container;
*
* container = op->o_container;
* if ((uintptr_t)container & 0x3) {
* return (KMEM_CBRC_DONT_KNOW);
* }
*
* // Ensure that the container structure does not go away.
* if (container_hold(container) == 0) {
* return (KMEM_CBRC_DONT_KNOW);
* }
*
* mutex_enter(&container->c_objects_lock);
* if (container != op->o_container) {
* mutex_exit(&container->c_objects_lock);
* container_rele(container);
* return (KMEM_CBRC_DONT_KNOW);
* }
*
* if (rw_tryenter(OBJECT_RWLOCK(op), RW_WRITER) == 0) {
* mutex_exit(&container->c_objects_lock);
* container_rele(container);
* return (KMEM_CBRC_LATER);
* }
*
* object_move_impl(op, np); // critical section
* rw_exit(OBJECT_RWLOCK(op));
*
* op->o_container = (void *)((uintptr_t)op->o_container | 0x1);
* list_link_replace(&op->o_link_node, &np->o_link_node);
* mutex_exit(&container->c_objects_lock);
* container_rele(container);
* return (KMEM_CBRC_YES);
* }
*
* Note that object_move() must invalidate the designated o_container pointer of
* the old object in the same way that object_free() does, since kmem will free
* the object in response to the KMEM_CBRC_YES return value.
*
* The lock order in object_move() differs from object_alloc(), which locks
* OBJECT_RWLOCK first and &container->c_objects_lock second, but as long as the
* callback uses rw_tryenter() (preventing the deadlock described earlier), it's
* not a problem. Holding the lock on the object list in the example above
* through the entire callback not only prevents the object from going away, it
* also allows you to lock the list elsewhere and know that none of its elements
* will move during iteration.
*
* Adding an explicit hold everywhere an object from the cache is used is tricky
* and involves much more change to client code than a cache-specific solution
* that leverages existing state to decide whether or not an object is
* movable. However, this approach has the advantage that no object remains
* immovable for any significant length of time, making it extremely unlikely
* that long-lived allocations can continue holding slabs hostage; and it works
* for any cache.
*
* 3. Consolidator Implementation
*
* Once the client supplies a move function that a) recognizes known objects and
* b) avoids moving objects that are actively in use, the remaining work is up
* to the consolidator to decide which objects to move and when to issue
* callbacks.
*
* The consolidator relies on the fact that a cache's slabs are ordered by
* usage. Each slab has a fixed number of objects. Depending on the slab's
* "color" (the offset of the first object from the beginning of the slab;
* offsets are staggered to mitigate false sharing of cache lines) it is either
* the maximum number of objects per slab determined at cache creation time or
* else the number closest to the maximum that fits within the space remaining
* after the initial offset. A completely allocated slab may contribute some
* internal fragmentation (per-slab overhead) but no external fragmentation, so
* it is of no interest to the consolidator. At the other extreme, slabs whose
* objects have all been freed to the slab are released to the virtual memory
* (VM) subsystem (objects freed to magazines are still allocated as far as the
* slab is concerned). External fragmentation exists when there are slabs
* somewhere between these extremes. A partial slab has at least one but not all
* of its objects allocated. The more partial slabs, and the fewer allocated
* objects on each of them, the higher the fragmentation. Hence the
* consolidator's overall strategy is to reduce the number of partial slabs by
* moving allocated objects from the least allocated slabs to the most allocated
* slabs.
*
* Partial slabs are kept in an AVL tree ordered by usage. Completely allocated
* slabs are kept separately in an unordered list. Since the majority of slabs
* tend to be completely allocated (a typical unfragmented cache may have
* thousands of complete slabs and only a single partial slab), separating
* complete slabs improves the efficiency of partial slab ordering, since the
* complete slabs do not affect the depth or balance of the AVL tree. This
* ordered sequence of partial slabs acts as a "free list" supplying objects for
* allocation requests.
*
* Objects are always allocated from the first partial slab in the free list,
* where the allocation is most likely to eliminate a partial slab (by
* completely allocating it). Conversely, when a single object from a completely
* allocated slab is freed to the slab, that slab is added to the front of the
* free list. Since most free list activity involves highly allocated slabs
* coming and going at the front of the list, slabs tend naturally toward the
* ideal order: highly allocated at the front, sparsely allocated at the back.
* Slabs with few allocated objects are likely to become completely free if they
* keep a safe distance away from the front of the free list. Slab misorders
* interfere with the natural tendency of slabs to become completely free or
* completely allocated. For example, a slab with a single allocated object
* needs only a single free to escape the cache; its natural desire is
* frustrated when it finds itself at the front of the list where a second
* allocation happens just before the free could have released it. Another slab
* with all but one object allocated might have supplied the buffer instead, so
* that both (as opposed to neither) of the slabs would have been taken off the
* free list.
*
* Although slabs tend naturally toward the ideal order, misorders allowed by a
* simple list implementation defeat the consolidator's strategy of merging
* least- and most-allocated slabs. Without an AVL tree to guarantee order, kmem
* needs another way to fix misorders to optimize its callback strategy. One
* approach is to periodically scan a limited number of slabs, advancing a
* marker to hold the current scan position, and to move extreme misorders to
* the front or back of the free list and to the front or back of the current
* scan range. By making consecutive scan ranges overlap by one slab, the least
* allocated slab in the current range can be carried along from the end of one
* scan to the start of the next.
*
* Maintaining partial slabs in an AVL tree relieves kmem of this additional
* task, however. Since most of the cache's activity is in the magazine layer,
* and allocations from the slab layer represent only a startup cost, the
* overhead of maintaining a balanced tree is not a significant concern compared
* to the opportunity of reducing complexity by eliminating the partial slab
* scanner just described. The overhead of an AVL tree is minimized by
* maintaining only partial slabs in the tree and keeping completely allocated
* slabs separately in a list. To avoid increasing the size of the slab
* structure the AVL linkage pointers are reused for the slab's list linkage,
* since the slab will always be either partial or complete, never stored both
* ways at the same time. To further minimize the overhead of the AVL tree the
* compare function that orders partial slabs by usage divides the range of
* allocated object counts into bins such that counts within the same bin are
* considered equal. Binning partial slabs makes it less likely that allocating
* or freeing a single object will change the slab's order, requiring a tree
* reinsertion (an avl_remove() followed by an avl_add(), both potentially
* requiring some rebalancing of the tree). Allocation counts closest to
* completely free and completely allocated are left unbinned (finely sorted) to
* better support the consolidator's strategy of merging slabs at either
* extreme.
*
* 3.1 Assessing Fragmentation and Selecting Candidate Slabs
*
* The consolidator piggybacks on the kmem maintenance thread and is called on
* the same interval as kmem_cache_update(), once per cache every fifteen
* seconds. kmem maintains a running count of unallocated objects in the slab
* layer (cache_bufslab). The consolidator checks whether that number exceeds
* 12.5% (1/8) of the total objects in the cache (cache_buftotal), and whether
* there is a significant number of slabs in the cache (arbitrarily a minimum
* 101 total slabs). Unused objects that have fallen out of the magazine layer's
* working set are included in the assessment, and magazines in the depot are
* reaped if those objects would lift cache_bufslab above the fragmentation
* threshold. Once the consolidator decides that a cache is fragmented, it looks
* for a candidate slab to reclaim, starting at the end of the partial slab free
* list and scanning backwards. At first the consolidator is choosy: only a slab
* with fewer than 12.5% (1/8) of its objects allocated qualifies (or else a
* single allocated object, regardless of percentage). If there is difficulty
* finding a candidate slab, kmem raises the allocation threshold incrementally,
* up to a maximum 87.5% (7/8), so that eventually the consolidator will reduce
* external fragmentation (unused objects on the free list) below 12.5% (1/8),
* even in the worst case of every slab in the cache being almost 7/8 allocated.
* The threshold can also be lowered incrementally when candidate slabs are easy
* to find, and the threshold is reset to the minimum 1/8 as soon as the cache
* is no longer fragmented.
*
* 3.2 Generating Callbacks
*
* Once an eligible slab is chosen, a callback is generated for every allocated
* object on the slab, in the hope that the client will move everything off the
* slab and make it reclaimable. Objects selected as move destinations are
* chosen from slabs at the front of the free list. Assuming slabs in the ideal
* order (most allocated at the front, least allocated at the back) and a
* cooperative client, the consolidator will succeed in removing slabs from both
* ends of the free list, completely allocating on the one hand and completely
* freeing on the other. Objects selected as move destinations are allocated in
* the kmem maintenance thread where move requests are enqueued. A separate
* callback thread removes pending callbacks from the queue and calls the
* client. The separate thread ensures that client code (the move function) does
* not interfere with internal kmem maintenance tasks. A map of pending
* callbacks keyed by object address (the object to be moved) is checked to
* ensure that duplicate callbacks are not generated for the same object.
* Allocating the move destination (the object to move to) prevents subsequent
* callbacks from selecting the same destination as an earlier pending callback.
*
* Move requests can also be generated by kmem_cache_reap() when the system is
* desperate for memory and by kmem_cache_move_notify(), called by the client to
* notify kmem that a move refused earlier with KMEM_CBRC_LATER is now possible.
* The map of pending callbacks is protected by the same lock that protects the
* slab layer.
*
* When the system is desperate for memory, kmem does not bother to determine
* whether or not the cache exceeds the fragmentation threshold, but tries to
* consolidate as many slabs as possible. Normally, the consolidator chews
* slowly, one sparsely allocated slab at a time during each maintenance
* interval that the cache is fragmented. When desperate, the consolidator
* starts at the last partial slab and enqueues callbacks for every allocated
* object on every partial slab, working backwards until it reaches the first
* partial slab. The first partial slab, meanwhile, advances in pace with the
* consolidator as allocations to supply move destinations for the enqueued
* callbacks use up the highly allocated slabs at the front of the free list.
* Ideally, the overgrown free list collapses like an accordion, starting at
* both ends and ending at the center with a single partial slab.
*
* 3.3 Client Responses
*
* When the client returns KMEM_CBRC_NO in response to the move callback, kmem
* marks the slab that supplied the stuck object non-reclaimable and moves it to
* front of the free list. The slab remains marked as long as it remains on the
* free list, and it appears more allocated to the partial slab compare function
* than any unmarked slab, no matter how many of its objects are allocated.
* Since even one immovable object ties up the entire slab, the goal is to
* completely allocate any slab that cannot be completely freed. kmem does not
* bother generating callbacks to move objects from a marked slab unless the
* system is desperate.
*
* When the client responds KMEM_CBRC_LATER, kmem increments a count for the
* slab. If the client responds LATER too many times, kmem disbelieves and
* treats the response as a NO. The count is cleared when the slab is taken off
* the partial slab list or when the client moves one of the slab's objects.
*
* 4. Observability
*
* A kmem cache's external fragmentation is best observed with 'mdb -k' using
* the ::kmem_slabs dcmd. For a complete description of the command, enter
* '::help kmem_slabs' at the mdb prompt.
*/
#include <sys/kmem_impl.h>
#include <sys/vmem_impl.h>
#include <sys/sysmacros.h>
#include <sys/tuneable.h>
#include <vm/seg_kmem.h>
#include <sys/netstack.h>
#ifdef DEBUG
#endif
extern void streams_msg_init(void);
extern int segkp_fromheap;
extern void segkp_cache_free(void);
struct kmem_cache_kstat {
} kmem_cache_kstat = {
{ "buf_size", KSTAT_DATA_UINT64 },
{ "align", KSTAT_DATA_UINT64 },
{ "chunk_size", KSTAT_DATA_UINT64 },
{ "slab_size", KSTAT_DATA_UINT64 },
{ "alloc", KSTAT_DATA_UINT64 },
{ "alloc_fail", KSTAT_DATA_UINT64 },
{ "free", KSTAT_DATA_UINT64 },
{ "depot_alloc", KSTAT_DATA_UINT64 },
{ "depot_free", KSTAT_DATA_UINT64 },
{ "depot_contention", KSTAT_DATA_UINT64 },
{ "slab_alloc", KSTAT_DATA_UINT64 },
{ "slab_free", KSTAT_DATA_UINT64 },
{ "buf_constructed", KSTAT_DATA_UINT64 },
{ "buf_avail", KSTAT_DATA_UINT64 },
{ "buf_inuse", KSTAT_DATA_UINT64 },
{ "buf_total", KSTAT_DATA_UINT64 },
{ "buf_max", KSTAT_DATA_UINT64 },
{ "slab_create", KSTAT_DATA_UINT64 },
{ "slab_destroy", KSTAT_DATA_UINT64 },
{ "vmem_source", KSTAT_DATA_UINT64 },
{ "hash_size", KSTAT_DATA_UINT64 },
{ "hash_lookup_depth", KSTAT_DATA_UINT64 },
{ "hash_rescale", KSTAT_DATA_UINT64 },
{ "full_magazines", KSTAT_DATA_UINT64 },
{ "empty_magazines", KSTAT_DATA_UINT64 },
{ "magazine_size", KSTAT_DATA_UINT64 },
{ "reap", KSTAT_DATA_UINT64 },
{ "defrag", KSTAT_DATA_UINT64 },
{ "scan", KSTAT_DATA_UINT64 },
{ "move_callbacks", KSTAT_DATA_UINT64 },
{ "move_yes", KSTAT_DATA_UINT64 },
{ "move_no", KSTAT_DATA_UINT64 },
{ "move_later", KSTAT_DATA_UINT64 },
{ "move_dont_need", KSTAT_DATA_UINT64 },
{ "move_dont_know", KSTAT_DATA_UINT64 },
{ "move_hunt_found", KSTAT_DATA_UINT64 },
{ "move_slabs_freed", KSTAT_DATA_UINT64 },
{ "move_reclaimable", KSTAT_DATA_UINT64 },
};
static kmutex_t kmem_cache_kstat_lock;
/*
* The default set of caches to back kmem_alloc().
* These sizes should be reevaluated periodically.
*
* We want allocations that are multiples of the coherency granularity
* (64 bytes) to be satisfied from a cache which is a multiple of 64
* bytes, so that it will be 64-byte aligned. For all multiples of 64,
* the next kmem_cache_size greater than or equal to it must be a
* multiple of 64.
*
* We split the table into two sections: size <= 4k and size > 4k. This
* saves a lot of space and cache footprint in our cache tables.
*/
static const int kmem_alloc_sizes[] = {
1 * 8,
2 * 8,
3 * 8,
4 * 8, 5 * 8, 6 * 8, 7 * 8,
4 * 16, 5 * 16, 6 * 16, 7 * 16,
4 * 32, 5 * 32, 6 * 32, 7 * 32,
4 * 64, 5 * 64, 6 * 64, 7 * 64,
4 * 128, 5 * 128, 6 * 128, 7 * 128,
};
static const int kmem_big_alloc_sizes[] = {
2 * 4096, 3 * 4096,
2 * 8192, 3 * 8192,
4 * 8192, 5 * 8192, 6 * 8192, 7 * 8192,
8 * 8192, 9 * 8192, 10 * 8192, 11 * 8192,
12 * 8192, 13 * 8192, 14 * 8192, 15 * 8192,
16 * 8192
};
#define KMEM_MAXBUF 4096
#define KMEM_BIG_MAXBUF_32BIT 32768
#define KMEM_BIG_MAXBUF 131072
static kmem_magtype_t kmem_magtype[] = {
{ 1, 8, 3200, 65536 },
{ 3, 16, 256, 32768 },
{ 7, 32, 64, 16384 },
{ 15, 64, 0, 8192 },
{ 31, 64, 0, 4096 },
{ 47, 64, 0, 2048 },
{ 63, 64, 0, 1024 },
{ 95, 64, 0, 512 },
{ 143, 64, 0, 0 },
};
static uint32_t kmem_reaping;
static uint32_t kmem_reaping_idspace;
/*
* kmem tunables
*/
#ifdef _LP64
#else
#endif
#ifdef DEBUG
#else
int kmem_flags = 0;
#endif
int kmem_ready;
static kmem_cache_t *kmem_slab_cache;
static kmem_cache_t *kmem_bufctl_cache;
static kmem_cache_t *kmem_bufctl_audit_cache;
static list_t kmem_caches;
static taskq_t *kmem_taskq;
static kmutex_t kmem_flags_lock;
static vmem_t *kmem_metadata_arena;
static vmem_t *kmem_cache_arena;
static vmem_t *kmem_hash_arena;
static vmem_t *kmem_log_arena;
static vmem_t *kmem_oversize_arena;
static vmem_t *kmem_va_arena;
static vmem_t *kmem_default_arena;
static vmem_t *kmem_firewall_va_arena;
static vmem_t *kmem_firewall_arena;
/*
* Define KMEM_STATS to turn on statistic gathering. By default, it is only
* turned on when DEBUG is also defined.
*/
#ifdef DEBUG
#define KMEM_STATS
#endif /* DEBUG */
#ifdef KMEM_STATS
#else
#endif /* KMEM_STATS */
/*
* kmem slab consolidator thresholds (tunables)
*/
/*
* Maximum number of slabs from which to move buffers during a single
* maintenance interval while the system is not low on memory.
*/
/*
* Number of slabs to scan backwards from the end of the partial slab list
* when searching for buffers to relocate.
*/
#ifdef KMEM_STATS
static struct {
#endif /* KMEM_STATS */
/* consolidator knobs */
static boolean_t kmem_move_noreap;
static boolean_t kmem_move_blocked;
static boolean_t kmem_move_fulltilt;
static boolean_t kmem_move_any_partial;
#ifdef DEBUG
/*
* kmem consolidator debug tunables:
* Ensure code coverage by occasionally running the consolidator even when the
* caches are not fragmented (they may never be). These intervals are mean time
* in cache maintenance intervals (kmem_cache_update).
*/
#endif /* DEBUG */
static kmem_cache_t *kmem_defrag_cache;
static kmem_cache_t *kmem_move_cache;
static taskq_t *kmem_move_taskq;
static void kmem_cache_scan(kmem_cache_t *);
static void kmem_cache_defrag(kmem_cache_t *);
static int kmem_lite_count; /* # of PCs in kmem_buftag_lite_t */
if ((count) > 0) { \
/* memmove() the old entries down one notch */ \
}
#define KMERR_MODIFIED 0 /* buffer modified while on freelist */
struct {
int kmp_error; /* type of kmem error */
void *kmp_buffer; /* buffer that induced panic */
void *kmp_realbuf; /* real start address for buffer */
static void
{
}
static void *
{
return (buf);
return (NULL);
}
static void *
{
return (buf);
}
}
return (NULL);
}
static void
{
tqflag);
else
}
static void
{
continue;
tqflag);
else
}
}
/*
* Debugging support. Given a buffer address, find its slab.
*/
static kmem_slab_t *
{
return (sp);
}
}
return (sp);
}
}
return (NULL);
}
static void
{
kmem_logging = 0; /* stop logging when a bad thing happens */
break;
}
}
} else {
else
break;
}
}
}
printf("kernel memory allocator: ");
switch (error) {
case KMERR_MODIFIED:
printf("buffer modified after being freed\n");
printf("modification occurred at offset 0x%lx "
"(0x%llx replaced by 0x%llx)\n",
break;
case KMERR_REDZONE:
printf("redzone violation: write past end of buffer\n");
break;
case KMERR_BADADDR:
printf("invalid free: buffer not in cache\n");
break;
case KMERR_DUPFREE:
printf("duplicate free: buffer freed twice\n");
break;
case KMERR_BADBUFTAG:
printf("boundary tag corrupted\n");
printf("bcp ^ bxstat = %lx, should be %lx\n",
break;
case KMERR_BADBUFCTL:
printf("bufctl corrupted\n");
break;
case KMERR_BADCACHE:
printf("buffer freed to wrong cache\n");
break;
case KMERR_BADSIZE:
printf("bad free: free size (%u) != alloc size (%u)\n",
break;
case KMERR_BADBASE:
printf("bad free: free address (%p) != alloc address (%p)\n",
break;
}
printf("buffer=%p bufctl=%p cache: %s\n",
error != KMERR_BADBUFCTL) {
int d;
printf("thread=%p time=T-%ld.%09ld slab=%p cache: %s\n",
}
}
if (kmem_panic > 0)
panic("kernel heap corruption detected");
if (kmem_panic == 0)
}
static kmem_log_header_t *
{
int i;
/*
* Make sure that lhp->lh_cpu[] is nicely aligned
* to prevent false sharing of cache lines.
*/
for (i = 0; i < max_ncpus; i++) {
}
return (lhp);
}
static void *
{
void *logspace;
return (NULL);
}
return (logspace);
}
{ \
}
static void
{
}
/*
* Create a new slab for cache cp.
*/
static kmem_slab_t *
{
goto vmem_alloc_failure;
/*
* Reverify what was already checked in kmem_cache_set_move(), since the
* consolidator depends (for correctness) on slabs being initialized
* with the 0xbaddcafe memory pattern (setting a low order bit usable by
* clients to distinguish uninitialized memory from known objects).
*/
if (cache_flags & KMF_HASH) {
goto slab_alloc_failure;
} else {
}
sp->slab_refcnt = 0;
sp->slab_later_count = 0;
sp->slab_flags = 0;
while (chunks-- != 0) {
if (cache_flags & KMF_HASH) {
goto bufctl_alloc_failure;
if (cache_flags & KMF_AUDIT) {
}
} else {
}
if (cache_flags & KMF_BUFTAG) {
if (cache_flags & KMF_DEADBEEF) {
cp->cache_verify);
}
}
}
return (sp);
}
return (NULL);
}
/*
* Destroy a slab.
*/
static void
{
}
}
}
static void *
{
void *buf;
/*
* kmem_slab_alloc() drops cache_lock when it creates a new slab, so we
* can't ASSERT(avl_is_empty(&cp->cache_partial_slabs)) here when the
* slab is newly created (sp->slab_refcnt == 0).
*/
cp->cache_slab_alloc++;
cp->cache_bufslab--;
sp->slab_refcnt++;
} else {
}
} else {
} else {
/*
* The slab is now more allocated than it was, so the
* order remains unchanged.
*/
}
}
/*
* Add buffer to allocated-address hash table.
*/
*hash_bucket = bcp;
}
} else {
}
return (buf);
}
/*
* Allocate a raw (unconstructed) buffer from cp's slab layer.
*/
static void *
{
void *buf;
/*
* The freelist is empty. Create a new slab.
*/
return (NULL);
}
cp->cache_slab_create++;
}
/*
* On the first kmem_slab_alloc(), assert that it is valid to
* call the destructor on a newly constructed object without any
* client involvement.
*/
kmflag) == 0) {
}
cp->cache_bufsize);
}
}
return (buf);
}
/*
* Free a raw (unconstructed) buffer to cp's slab layer.
*/
static void
{
cp->cache_slab_free++;
/*
* Look up buffer in allocated-address hash table.
*/
break;
}
cp->cache_lookup_depth++;
}
} else {
}
return;
}
/*
* If this is the buffer that prevented the consolidator from
* clearing the slab, we can reset the slab flags now that the
* buffer is freed. (It makes sense to do this in
* kmem_cache_free(), where the client gives up ownership of the
* buffer, but on the hot path the test is too expensive.)
*/
}
cp->cache_contents);
}
cp->cache_bufslab++;
if (--sp->slab_refcnt == 0) {
/*
* There are no outstanding allocations from this slab,
* so we can reclaim the memory.
*/
} else {
}
/*
* Defer releasing the slab to the virtual memory subsystem
* while there is a pending move callback, since we guarantee
* that buffers passed to the move callback have only been
* touched by kmem or by the client itself. Since the memory
* patterns baddcafe (uninitialized) and deadbeef (freed) both
* set at least one of the two lowest order bits, the client can
* test those bits in the move callback to determine whether or
* not it knows about the buffer (assuming that the client also
* sets one of those low order bits whenever it frees a buffer).
*/
cp->cache_slab_destroy++;
} else {
/*
* Slabs are inserted at both ends of the deadlist to
* distinguish between slabs freed while move callbacks
* are pending (list head) and a slab freed while the
* lock is dropped in kmem_move_buffers() (list tail) so
* that in both cases slab_destroy() is called from the
* right context.
*/
} else {
}
}
return;
}
/* Transition the slab from completely allocated to partial. */
} else {
#ifdef DEBUG
} else {
}
#else
#endif
}
}
/*
* Return -1 if kmem_error, 1 if constructor fails, 0 if successful.
*/
static int
{
return (-1);
}
return (-1);
}
return (-1);
}
else
} else {
construct = 1;
cp->cache_verify)) {
return (-1);
}
}
}
} else {
mtbf = 0;
}
return (1);
}
}
}
return (0);
}
static int
{
return (-1);
}
else
return (-1);
}
return (-1);
}
return (-1);
}
}
}
}
return (0);
}
/*
* Free each object in magazine mp to cp's slab layer, and free mp itself.
*/
static void
{
int round;
continue;
}
}
}
}
}
/*
* Allocate a magazine from the depot.
*/
static kmem_magazine_t *
{
/*
* If we can't get the depot lock without contention,
* update our contention count. We use the depot
* contention rate to determine whether we need to
* increase the magazine size for better scalability.
*/
}
}
return (mp);
}
/*
* Free a magazine to the depot.
*/
static void
{
}
/*
* Update the working set statistics for cp's depot.
*/
static void
{
}
/*
* Reap all magazines that have fallen out of the depot's working set.
*/
static void
{
long reap;
}
static void
{
}
/*
* changing kmem state while memory is being saved to the dump device.
* Otherwise, ::kmem_verify will report "corrupt buffers". Note that
* there are no locks because only one CPU calls kmem during a crash
* dump. To enable this feature, first create the associated vmem
* arena with VMC_DUMPSAFE.
*/
static void *kmem_dump_start; /* start of pre-reserved heap */
static void *kmem_dump_end; /* end of heap area */
static void *kmem_dump_curr; /* current free heap pointer */
/* append to each buf created in the pre-reserved heap */
typedef struct kmem_dumpctl {
void *kdc_next; /* cache dump free list linkage */
sizeof (void *)))
/* Keep some simple stats. */
#define KMEM_DUMP_LOGS (100)
typedef struct kmem_dump_log {
static kmem_dump_log_t *kmem_dump_log;
static int kmem_dump_log_idx;
kmem_dump_log_t *kdl; \
} else if (kmem_dump_log_idx < KMEM_DUMP_LOGS) { \
} \
}
/* set non zero for full report */
uint_t kmem_dump_verbose = 0;
/* stats for overize heap */
static void
{
char *p = *pp;
if (p < e) {
int n;
*pp = p + n;
}
}
/*
* Called when dumpadm(1M) configures dump parameters.
*/
void
{
if (kmem_dump_start != NULL)
if (kmem_dump_log == NULL)
sizeof (kmem_dump_log_t), KM_SLEEP);
if (kmem_dump_start != NULL) {
} else {
kmem_dump_size = 0;
}
}
/*
* Set flag for each kmem_cache_t if is safe to use alternate dump
* memory. Called just before panic crash dump starts. Set the flag
* for the calling CPU.
*/
void
kmem_dump_begin(void)
{
if (kmem_dump_start != NULL) {
} else {
}
}
}
}
/*
* finished dump intercept
* print any warnings on the console
* return verbose information to dumpsys() in the given buffer
*/
{
int kdi_idx;
int kdi_end = kmem_dump_log_idx;
int percent = 0;
int header = 0;
int warn = 0;
char *p = buf;
if (kmem_dump_size == 0 || kmem_dump_verbose == 0)
return (0);
kmem_dumppr(&p, e, "Oversize allocs,%d\n",
kmem_dumppr(&p, e, "Oversize max size,%ld\n",
break;
if (kdl->kdl_alloc_fails)
++warn;
if (header == 0) {
kmem_dumppr(&p, e,
"Cache Name,Allocs,Frees,Alloc Fails,"
header = 1;
}
kmem_dumppr(&p, e, "%s,%d,%d,%d,%d,%d\n",
kdl->kdl_unsafe);
}
/* return buffer size used */
if (p < e)
bzero(p, e - p);
return (p - buf);
}
/*
* Allocate a constructed object from alternate dump memory.
*/
void *
{
void *buf;
void *curr;
char *bufend;
/* return a constructed object */
return (buf);
}
/* create a new constructed object */
/* hat layer objects cannot cross a page boundary */
}
}
/* fall back to normal alloc if reserved area is used up */
if (bufend > (char *)kmem_dump_end) {
return (NULL);
}
/*
* Must advance curr pointer before calling a constructor that
* may also allocate memory.
*/
/* run constructor */
!= 0) {
#ifdef DEBUG
printf("name='%s' cache=0x%p: kmem cache constructor failed\n",
#endif
/* reset curr pointer iff no allocs were done */
if (kmem_dump_curr == bufend)
/* fall back to normal alloc if the constructor fails */
return (NULL);
}
return (buf);
}
/*
* Free a constructed object in alternate dump memory.
*/
int
{
/* save constructed buffers for next time */
if ((char *)buf >= (char *)kmem_dump_start &&
(char *)buf < (char *)kmem_dump_end) {
return (0);
}
/* count all non-dump buf frees */
/* just drop buffers that were allocated before dump started */
if (kmem_dump_curr < kmem_dump_end)
return (0);
/* fall back to normal free if reserved area is used up */
return (1);
}
/*
* Allocate a constructed object from cache cp.
*/
void *
{
void *buf;
for (;;) {
/*
* If there's an object available in the current CPU's
* loaded magazine, just take it and return.
*/
}
caller()) != 0) {
if (kmflag & KM_NOSLEEP)
return (NULL);
continue;
}
}
return (buf);
}
/*
* The loaded magazine is empty. If the previously loaded
* magazine was full, exchange them and try again.
*/
if (ccp->cc_prounds > 0) {
continue;
}
/*
* Return an alternate buffer at dump time to preserve
* the heap.
*/
/* log it so that we can warn about it */
} else {
NULL) {
return (buf);
}
break; /* fall back to slab layer */
}
}
/*
* If the magazine layer is disabled, break out now.
*/
if (ccp->cc_magsize == 0)
break;
/*
* Try to get a full magazine from the depot.
*/
ccp->cc_ploaded);
continue;
}
/*
* There are no full magazines in the depot,
* so fall through to the slab layer.
*/
break;
}
/*
* We couldn't allocate a constructed object from the magazine layer,
* so get a raw buffer from the slab layer and apply its constructor.
*/
return (NULL);
/*
* Make kmem_cache_alloc_debug() apply the constructor for us.
*/
if (rc != 0) {
if (kmflag & KM_NOSLEEP)
return (NULL);
/*
* kmem_cache_alloc_debug() detected corruption
* but didn't panic (kmem_panic <= 0). We should not be
* here because the constructor failed (indicated by a
* return code of 1). Try again.
*/
}
return (buf);
}
return (NULL);
}
return (buf);
}
/*
* The freed argument tells whether or not kmem_cache_free_debug() has already
* been called so that we can avoid the duplicate free error. For example, a
* buffer on a magazine has already been freed by the client but is still
* constructed.
*/
static void
{
return;
/*
* Note that if KMF_DEADBEEF is in effect and KMF_LITE is not,
* kmem_cache_free_debug() will have already applied the destructor.
*/
} else {
}
}
}
/*
* Free a constructed object to cache cp.
*/
void
{
/*
* The client must not free either of the buffers passed to the move
* callback function.
*/
/* log it so that we can warn about it */
return;
}
return;
}
}
for (;;) {
/*
* If there's a slot available in the current CPU's
* loaded magazine, just put the object there and return.
*/
return;
}
/*
* The loaded magazine is full. If the previously loaded
* magazine was empty, exchange them and try again.
*/
if (ccp->cc_prounds == 0) {
continue;
}
/*
* If the magazine layer is disabled, break out now.
*/
if (ccp->cc_magsize == 0)
break;
/*
* Try to get an empty magazine from the depot.
*/
ccp->cc_ploaded);
continue;
}
/*
* There are no empty magazines in the depot,
* so try to allocate a new one. We must drop all locks
* across kmem_cache_alloc() because lower layers may
* attempt to allocate from this cache.
*/
/*
* We successfully allocated an empty magazine.
* However, we had to drop ccp->cc_lock to do it,
* so the cache's magazine size may have changed.
* If so, free the magazine and try again.
*/
continue;
}
/*
* We got a magazine of the right size. Add it to
* the depot and try the whole dance again.
*/
continue;
}
/*
* We couldn't allocate an empty magazine,
* so fall through to the slab layer.
*/
break;
}
/*
* We couldn't free our constructed object to the magazine layer,
* so apply its destructor and free it to the slab layer.
*/
}
void *
{
void *buf;
kmem_lite_count, caller());
}
}
}
} else {
}
return (buf);
}
void *
{
void *buf;
/* fall through to kmem_cache_alloc() */
/* fall through to kmem_cache_alloc() */
} else {
if (size == 0)
return (NULL);
kmflag & KM_VMFLAGS);
(void *)size);
else if (KMEM_DUMP(kmem_slab_cache)) {
/* stats for dump intercept */
if (size > kmem_dump_oversize_max)
}
return (buf);
}
}
}
return (buf);
}
void
{
/* fall through to kmem_cache_free() */
/* fall through to kmem_cache_free() */
} else {
return;
return;
}
return;
}
} else {
}
return;
}
return;
}
caller());
}
}
}
void *
{
void *addr;
/*
* Annoying edge case: if 'size' is just shy of ULONG_MAX, adding
* vm_quantum will cause integer wraparound. Check for this, and
* blow off the firewall page in this case. Note that such a
* giant allocation (the entire kernel address space) can never
* be satisfied, so it will either fail immediately (VM_NOSLEEP)
* or sleep forever (VM_SLEEP). Thus, there is no need for a
* corresponding check in kmem_firewall_va_free().
*/
/*
* While boot still owns resource management, make sure that this
* redzone virtual address allocation is properly accounted for in
* OBPs "virtual-memory" "available" lists because we're
* effectively claiming them for a red zone. If we don't do this,
* the available lists become too fragmented and too large for the
*/
return (addr);
}
void
{
}
/*
* Try to allocate at least `size' bytes of memory without sleeping or
* panicking. Return actual allocated size in `asize'. If allocation failed,
* try final allocation with sleep or panic allowed.
*/
void *
{
void *p;
do {
if (p != NULL)
return (p);
*asize += KMEM_ALIGN;
}
/*
* Reclaim all unused memory from a cache.
*/
static void
{
cp->cache_reap++;
/*
* Ask the cache's owner to free some memory if possible.
* The idea is to handle things like the inode cache, which
* typically sits on a bunch of memory that it doesn't truly
* *need*. Reclaim policy is entirely up to the owner; this
* callback is just an advisory plea for help.
*/
long delta;
/*
* Reclaimed memory should be reapable (not included in the
* depot's working set).
*/
if (delta > 0) {
}
}
}
}
static void
kmem_reap_timeout(void *flag_arg)
{
*flag = 0;
}
static void
kmem_reap_done(void *flag)
{
}
static void
kmem_reap_start(void *flag)
{
if (flag == &kmem_reaping) {
/*
* if we have segkp under heap, reap segkp cache.
*/
if (segkp_fromheap)
}
else
/*
* We use taskq_dispatch() to schedule a timeout to clear
* the flag so that kmem_reap() becomes self-throttling:
* we won't reap again until the current reap completes *and*
* at least kmem_reap_interval ticks have elapsed.
*/
}
static void
kmem_reap_common(void *flag_arg)
{
return;
/*
* It may not be kosher to do memory allocation when a reap is called
* is called (for example, if vmem_populate() is in the call chain).
* So we start the reap going with a TQ_NOALLOC dispatch. If the
* dispatch fails, we reset the flag, and the next reap will try again.
*/
*flag = 0;
}
/*
* Reclaim all unused memory from all caches. Called from the VM system
* when memory gets tight.
*/
void
kmem_reap(void)
{
}
/*
* Reclaim all unused memory from identifier arenas, called when a vmem
* arena not back by memory is exhausted. Since reaping memory-backed caches
* cannot help with identifier exhaustion, we avoid both a large amount of
* work and unwanted side-effects from reclaim callbacks.
*/
void
kmem_reap_idspace(void)
{
}
/*
* Purge all magazines from a cache and set its magazine limit to zero.
* All calls are serialized by the kmem_taskq lock, except for the final
* call from kmem_cache_destroy().
*/
static void
{
ccp->cc_magsize = 0;
if (mp)
if (pmp)
}
/*
* Updating the working set statistics twice in a row has the
* effect of setting the working set size to zero, so everything
* is eligible for reaping.
*/
}
/*
* Enable per-cpu magazines on a cache.
*/
static void
{
int cpu_seqid;
return;
}
}
/*
* Reap (almost) everything right now. See kmem_cache_magazine_purge()
* for explanation of the back-to-back kmem_depot_ws_update() calls.
*/
void
{
(void) taskq_dispatch(kmem_taskq,
}
/*
* Recompute a cache's magazine size. The trade-off is that larger magazines
* provide a higher transfer rate with the depot, while smaller magazines
* reduce memory consumption. Magazine resizing is an expensive operation;
* it should not be done frequently.
*
* Changes to the magazine size are serialized by the kmem_taskq lock.
*
* Note: at present this only grows the magazine size. It might be useful
* to allow shrinkage too.
*/
static void
{
}
}
/*
* Rescale a cache's hash table, so that the table size is roughly the
* cache size. We want the average lookup time to be extremely small.
*/
static void
{
return;
return;
cp->cache_rescale++;
for (h = 0; h < old_size; h++) {
*hash_bucket = bcp;
}
}
}
/*
* Perform periodic maintenance on a cache: hash rescaling, depot working-set
* update, magazine resizing, and slab consolidation.
*/
static void
{
int need_hash_rescale = 0;
int need_magazine_resize = 0;
/*
* If the cache has become much larger or smaller than its hash table,
* fire off a request to rescale the hash table.
*/
need_hash_rescale = 1;
/*
* Update the depot working set statistics.
*/
/*
* If there's a lot of contention in the depot,
* increase the magazine size.
*/
(int)(cp->cache_depot_contention -
need_magazine_resize = 1;
if (need_hash_rescale)
(void) taskq_dispatch(kmem_taskq,
if (need_magazine_resize)
(void) taskq_dispatch(kmem_taskq,
(void) taskq_dispatch(kmem_taskq,
}
static void kmem_update(void *);
static void
kmem_update_timeout(void *dummy)
{
}
static void
kmem_update(void *dummy)
{
/*
* We use taskq_dispatch() to reschedule the timeout so that
* kmem_update() becomes self-throttling: it won't schedule
* new tasks until all previous tasks have completed.
*/
}
static int
{
int cpu_seqid;
long reap;
if (rw == KSTAT_WRITE)
return (EACCES);
cpu_buf_avail = 0;
if (ccp->cc_prounds > 0)
}
} else {
}
return (0);
}
/*
* Return a named statistic about a particular cache.
* This shouldn't be called very often, so it's currently designed for
* simplicity (leverages existing kstat support) rather than efficiency.
*/
{
int i;
break;
}
}
}
return (value);
}
/*
* Return an estimate of currently available kernel heap memory.
* On 32-bit systems, physical memory may exceed virtual memory,
* we just truncate the result at 1GB.
*/
kmem_avail(void)
{
}
/*
* Return the maximum amount of memory that is (in theory) allocatable
* from the heap. This may be used as an estimate only since there
* is no guarentee this space will still be available when an allocation
* request is made, nor that the space may be allocated in one big request
* due to kernel heap fragmentation.
*/
kmem_maxavail(void)
{
}
/*
* Indicate whether memory-intensive kmem debugging is enabled.
*/
int
kmem_debugging(void)
{
}
/* binning function, sorts finely at the two extremes */
? -(sp)->slab_refcnt \
/*
* Minimizing the number of partial slabs on the freelist minimizes
* fragmentation (the ratio of unused buffers held by the slab layer). There are
* two ways to get a slab off of the freelist: 1) free all the buffers on the
* slab, and 2) allocate all the buffers on the slab. It follows that we want
* the most-used slabs at the front of the list where they have the best chance
* of being completely allocated, and the least-used slabs at a safe distance
* from the front to improve the odds that the few remaining buffers will all be
* freed before another allocation can tie up the slab. For that reason a slab
* with a higher slab_refcnt sorts less than than a slab with a lower
* slab_refcnt.
*
* However, if a slab has at least one buffer that is deemed unfreeable, we
* would rather have that slab at the front of the list regardless of
* slab_refcnt, since even one unfreeable buffer makes the entire slab
* unfreeable. If the client returns KMEM_CBRC_NO in response to a cache_move()
* callback, the slab is marked unfreeable for as long as it remains on the
* freelist.
*/
static int
{
const kmem_cache_t *cp;
/* weight of first slab */
}
/* weight of second slab */
}
return (-1);
return (1);
/* compare pointer values */
return (-1);
return (1);
return (0);
}
/*
* It must be valid to call the destructor (if any) on a newly created object.
* That is, the constructor (if any) must leave the object in a valid state for
* the destructor.
*/
char *name, /* descriptive name for this cache */
int (*constructor)(void *, void *, int), /* object constructor */
void (*destructor)(void *, void *), /* object destructor */
void (*reclaim)(void *), /* memory reclaim callback */
int cflags) /* cache creation flags */
{
int cpu_seqid;
#ifdef DEBUG
/*
* Cache names should conform to the rules for valid C identifiers
*/
if (!strident_valid(name)) {
"kmem_cache_create: '%s' is an invalid cache name\n"
"cache names must conform to the rules for "
"C identifiers\n", name);
}
#endif /* DEBUG */
/*
* If this kmem cache has an identifier vmem arena as its source, mark
* it such to allow kmem_reap_idspace().
*/
cflags |= KMC_IDENTIFIER;
/*
* Get a kmem_cache structure. We arrange that cp->cache_cpu[]
* is aligned on a KMEM_CPU_CACHE_SIZE boundary to prevent
* false sharing of per-CPU data.
*/
if (align == 0)
align = KMEM_ALIGN;
/*
* If we're not at least KMEM_ALIGN aligned, we can't use free
* memory to hold bufctl information (because we can't safely
* perform word loads and stores on it).
*/
if (align < KMEM_ALIGN)
cflags |= KMC_NOTOUCH;
if (kmem_flags & KMF_RANDOMIZE)
/*
* Make sure all the various flags are reasonable.
*/
if (bufsize >= kmem_lite_minsize &&
align <= kmem_lite_maxalign &&
} else {
}
}
if (cflags & KMC_NODEBUG)
if (cflags & KMC_NOTOUCH)
if (cflags & KMC_NOHASH)
if (cflags & KMC_NOMAGAZINE)
}
/*
* Set cache properties.
*/
/*
* Determine the chunk size.
*/
if (align >= KMEM_ALIGN) {
}
else
chunksize += sizeof (kmem_buftag_t);
}
}
/*
* Now that we know the chunk size, determine the optimal slab size.
*/
if (vmp == kmem_firewall_arena) {
cp->cache_mincolor = 0;
cp->cache_maxcolor =
} else {
vmp->vm_quantum);
}
}
if (cflags & KMC_QCACHE)
cp->cache_mincolor = 0;
}
}
/*
* Initialize the rest of the slab layer.
*/
/* LINTED: E_TRUE_LOGICAL_EXPR */
/* reuse partial slab AVL linkage for complete slab list linkage */
KMEM_HASH_INITIAL * sizeof (void *), VM_SLEEP);
KMEM_HASH_INITIAL * sizeof (void *));
}
/*
* Initialize the depot.
*/
continue;
/*
* Initialize the CPU layer.
*/
}
/*
* Create the cache's kstats.
*/
"kmem_cache", KSTAT_TYPE_NAMED,
sizeof (kmem_cache_kstat) / sizeof (kstat_named_t),
KSTAT_FLAG_VIRTUAL)) != NULL) {
}
/*
* Add the cache to the global list. This makes it visible
* to kmem_update(), so the cache must be ready for business.
*/
if (kmem_ready)
return (cp);
}
static int
kmem_move_cmp(const void *buf, const void *p)
{
const kmem_move_t *kmm = p;
}
static void
{
}
/*
* Initially, when choosing candidate slabs for buffers to move, we want to be
* very selective and take only slabs that are less than
* (1 / KMEM_VOID_FRACTION) allocated. If we have difficulty finding candidate
* slabs, then we raise the allocation ceiling incrementally. The reclaim
* threshold is reset to (1 / KMEM_VOID_FRACTION) as soon as the cache is no
* longer fragmented.
*/
static void
{
if (direction > 0) {
/* make it easier to find a candidate slab */
kmd->kmd_reclaim_numer++;
}
} else {
/* be more selective */
kmd->kmd_reclaim_numer--;
}
}
}
void
{
/*
* The consolidator does not support NOTOUCH caches because kmem cannot
* initialize their slabs with the 0xbaddcafe memory pattern, which sets
* a low order bit usable by clients to distinguish uninitialized memory
* from known objects (see kmem_slab_create).
*/
/*
* We should not be holding anyone's cache lock when calling
* kmem_cache_alloc(), so allocate in all cases before acquiring the
* lock.
*/
if (KMEM_IS_MOVABLE(cp)) {
kmem_move_cmp, sizeof (kmem_move_t),
/* LINTED: E_TRUE_LOGICAL_EXPR */
/* reuse the slab's AVL linkage for deadlist linkage */
sizeof (kmem_slab_t),
}
}
}
}
void
{
int cpu_seqid;
/*
* Remove the cache from the global cache list so that no one else
* can schedule tasks on its behalf, wait for any pending tasks to
* complete, purge the cache, and then destroy it.
*/
if (kmem_taskq != NULL)
if (kmem_move_taskq != NULL)
if (cp->cache_buftotal != 0)
}
/*
* The cache is now dead. There should be no further activity. We
* enforce this by setting land mines in the constructor, destructor,
* reclaim, and move routines that induce a kernel text fault if
* invoked.
*/
}
/*ARGSUSED*/
static int
{
if (what == CPU_UNCONFIG) {
}
return (0);
}
static void
{
int i;
for (i = 0; i < count; i++) {
/* if the table has an entry for maxbuf, we're done */
break;
/* cache size must be a multiple of the table unit */
/*
* If they allocate a multiple of the coherency granularity,
* they get a coherency-granularity-aligned address.
*/
align = 64;
"kmem_alloc_%lu", cache_size);
while (size <= cache_size) {
size += table_unit;
}
}
}
static void
{
int i;
for (i = 0; i < sizeof (kmem_magtype) / sizeof (*mtp); i++) {
mtp = &kmem_magtype[i];
}
if (pass == 2) {
if (use_large_pages) {
0, VMC_DUMPSAFE | VM_SLEEP);
} else {
0, VMC_DUMPSAFE | VM_SLEEP);
}
/* Figure out what our maximum cache size is */
if (maxbuf <= KMEM_MAXBUF) {
maxbuf = 0;
} else {
sizeof (kmem_big_alloc_sizes) / sizeof (int);
/*
* Round maxbuf up to an existing cache size. If maxbuf
* is larger than the largest cache, we truncate it to
* the largest cache's size.
*/
for (i = 0; i < max; i++) {
size = kmem_big_alloc_sizes[i];
break;
}
}
/*
* The big alloc table may not be completely overwritten, so
* we clear out any stale cache pointers from the first pass.
*/
} else {
/*
* During the first pass, the kmem_alloc_* caches
* are treated as metadata.
*/
}
/*
* Set up the default caches to back kmem_alloc()
*/
kmem_alloc_sizes, sizeof (kmem_alloc_sizes) / sizeof (int),
kmem_big_alloc_sizes, sizeof (kmem_big_alloc_sizes) / sizeof (int),
}
void
kmem_init(void)
{
int old_kmem_flags = kmem_flags;
int use_large_pages = 0;
kstat_init();
/*
* Small-memory systems (< 24 MB) can't handle kmem_flags overhead.
*/
kmem_flags = 0;
/*
* Don't do firewalled allocations if the heap is less than 1TB
* (i.e. on a 32-bit kernel)
* The resulting VM_NEXTFIT allocations would create too much
* fragmentation in a small heap.
*/
#if defined(_LP64)
#else
#endif
/* LINTED */
VMC_DUMPSAFE | VM_SLEEP);
0, VM_SLEEP);
VMC_DUMPSAFE | VM_SLEEP);
/* temporary oversize arena for mod_read_system_file */
/*
* needs to use the allocator. The simplest solution is to create
* caches we just created, and then create them all again in light
* of the (possibly) new kmem_flags and other kmem tunables.
*/
kmem_cache_init(1, 0);
if (old_kmem_flags & KMF_STICKY)
if (!(kmem_flags & KMF_AUDIT))
if (kmem_maxverify == 0)
if (kmem_minfirewall == 0)
/*
* give segkmem a chance to figure out if we are using large pages
* for the kernel heap
*/
/*
* To protect against corruption, we keep the actual number of callers
* KMF_LITE records seperate from the tunable. We arbitrarily clamp
* to 16, since the overhead for small buffers quickly gets out of
* hand.
*
* The real limit would depend on the needs of the largest KMC_NOHASH
* cache.
*/
/*
* Normally, we firewall oversized allocations when possible, but
* if we are using large pages for kernel memory, and we don't have
* any non-LITE debugging flags set, we want to allocate oversized
* buffers from large pages, and so skip the firewalling.
*/
if (use_large_pages &&
0, VMC_DUMPSAFE | VM_SLEEP);
} else {
VM_SLEEP);
}
if (kmem_transaction_log_size == 0)
}
if (kmem_content_log_size == 0)
}
/*
* Initialize STREAMS message caches so allocb() is available.
* This allows us to initialize the logging framework (cmn_err(9F),
* strlog(9F), etc) so we can start recording messages.
*/
/*
* Initialize the ZSD framework in Zones so modules loaded henceforth
* can register their callbacks.
*/
log_init();
taskq_init();
/*
* Warn about invalid or dangerous values of kmem_flags.
* Always warn about unsupported values.
*/
KMF_CONTENTS | KMF_LITE)) != 0) ||
"See the Solaris Tunable Parameters Reference Manual.",
#ifdef DEBUG
if ((kmem_flags & KMF_DEBUG) == 0)
#else
/*
* For non-debug kernels, the only "normal" flags are 0, KMF_LITE,
* KMF_REDZONE, and KMF_CONTENTS (the last because it is only enabled
* if KMF_AUDIT is set). We should warn the user about the performance
* penalty of KMF_AUDIT or KMF_DEADBEEF if they are set and KMF_LITE
* isn't set (since that disables AUDIT).
*/
if (!(kmem_flags & KMF_LITE) &&
"enabled (kmem_flags = 0x%x). Performance degradation "
"and large memory overhead possible. See the Solaris "
"Tunable Parameters Reference Manual.", kmem_flags);
#endif /* not DEBUG */
kmem_ready = 1;
/*
*/
ka_init();
/*
* Initialize 32-bit ID cache.
*/
id32_init();
/*
* Initialize the networking stack so modules loaded can
* register their callbacks.
*/
}
static void
kmem_move_init(void)
{
/*
* kmem guarantees that move callbacks are sequential and that even
* across multiple caches no two moves ever execute simultaneously.
* Move callbacks are processed on a separate taskq so that client code
* does not interfere with internal maintenance tasks.
*/
}
void
kmem_thread_init(void)
{
}
void
kmem_mp_init(void)
{
}
/*
* Return the slab of the allocated buffer, or NULL if the buffer is not
* allocated. This function may be called with a known slab address to determine
* whether or not the buffer is allocated, or with a NULL slab address to obtain
* an allocated buffer's slab.
*/
static kmem_slab_t *
{
continue;
}
}
}
continue;
}
}
static boolean_t
{
/*
* For code coverage we want to be able to move an object within the
* same slab (the only partial slab) even if allocating the destination
* buffer resulted in a completely allocated slab.
*/
return ((flags & KMM_DESPERATE) ||
}
/* If we're desperate, we don't care if the client said NO. */
if (flags & KMM_DESPERATE) {
}
return (B_FALSE);
}
}
/*
* The reclaim threshold is adjusted at each kmem_cache_scan() so that
* slabs with a progressively higher percentage of used buffers can be
* reclaimed until the cache as a whole is no longer fragmented.
*
* sp->slab_refcnt kmd_reclaim_numer
* --------------- < ------------------
* sp->slab_chunks KMEM_VOID_FRACTION
*/
return ((refcnt * KMEM_VOID_FRACTION) <
}
static void *
void *tbuf)
{
int i; /* magazine round index */
for (i = 0; i < n; i++) {
caller());
}
return (buf);
}
}
return (NULL);
}
/*
* Hunt the magazine layer for the given buffer. If found, the buffer is
* removed from the magazine layer and returned, otherwise NULL is returned.
* The state of the returned buffer is freed and constructed.
*/
static void *
{
kmem_magazine_t *m;
int cpu_seqid;
int n; /* magazine rounds */
void *tbuf; /* temporary swap buffer */
/*
* Allocated a buffer to swap with the one we hope to pull out of a
* magazine when found.
*/
return (NULL);
}
}
return (buf);
}
/* Hunt the depot. */
return (buf);
}
}
/* Hunt the per-CPU magazines. */
return (buf);
}
m = ccp->cc_ploaded;
n = ccp->cc_prounds;
return (buf);
}
}
return (NULL);
}
/*
* May be called from the kmem_move_taskq, from kmem_cache_move_notify_task(),
* or when the buffer is freed.
*/
static void
{
if (!KMEM_SLAB_IS_PARTIAL(sp)) {
return;
}
}
} else {
sp->slab_later_count = 0;
}
}
static void
{
if (!KMEM_SLAB_IS_PARTIAL(sp)) {
return;
}
sp->slab_later_count = 0;
}
/*
* The move callback takes two buffer addresses, the buffer to be moved, and a
* newly allocated and constructed buffer selected by kmem as the destination.
* It also takes the size of the buffer and an optional user argument specified
* at cache creation time. kmem guarantees that the buffer to be moved has not
* been unmapped by the virtual memory subsystem. Beyond that, it cannot
* guarantee the present whereabouts of the buffer to be moved, so it is up to
* the client to safely determine whether or not it is still using the buffer.
* The client must not free either of the buffers passed to the move callback,
* since kmem wants to free them directly to the slab layer. The client response
* tells kmem which of the two buffers to free:
*
* YES kmem frees the old buffer (the move was successful)
* NO kmem frees the new buffer, marks the slab of the old buffer
* non-reclaimable to avoid bothering the client again
* LATER kmem frees the new buffer, increments slab_later_count
* DONT_KNOW kmem frees the new buffer, searches mags for the old buffer
* DONT_NEED kmem frees both the old buffer and the new buffer
*
* The pending callback argument now being processed contains both of the
* buffers (old and new) passed to the move callback function, the slab of the
* old buffer, and flags related to the move request, such as whether or not the
* system was desperate for memory.
*
* Slabs are not freed while there is a pending callback, but instead are kept
* on a deadlist, which is drained after the last callback completes. This means
* that slabs are safe to access until kmem_move_end(), no matter how many of
* their buffers have been freed. Once slab_refcnt reaches zero, it stays at
* zero for as long as the slab remains on the deadlist and until the slab is
* freed.
*/
static void
{
/*
* The number of allocated buffers on the slab may have changed since we
* last checked the slab's reclaimability (when the pending move was
* enqueued), or the client may have responded NO when asked to move
* another buffer on the same slab.
*/
return;
}
/*
* Hunting magazines is expensive, so we'll wait to do that until the
* client responds KMEM_CBRC_DONT_KNOW. However, checking the slab layer
* is cheap, so we might as well do that here in case we can avoid
* bothering the client.
*/
if (free_on_slab) {
return;
}
/*
* Make kmem_cache_alloc_debug() apply the constructor for us.
*/
return;
}
KM_NOSLEEP) != 0) {
return;
}
callback);
if (response == KMEM_CBRC_YES) {
/* slab safe to access until kmem_move_end() */
if (sp->slab_refcnt == 0)
return;
}
switch (response) {
case KMEM_CBRC_NO:
break;
case KMEM_CBRC_LATER:
if (!KMEM_SLAB_IS_PARTIAL(sp)) {
break;
}
}
break;
case KMEM_CBRC_DONT_NEED:
if (sp->slab_refcnt == 0)
break;
case KMEM_CBRC_DONT_KNOW:
B_TRUE);
if (sp->slab_refcnt == 0)
}
break;
default:
panic("'%s' (%p) unexpected move callback response %d\n",
}
}
/* Return B_FALSE if there is insufficient memory for the move request. */
static boolean_t
{
void *to_buf;
ulong_t n;
return (B_FALSE);
}
return (B_TRUE); /* there is no need for the move request */
}
/*
* If the move is already pending and we're desperate now,
* update the move flags.
*/
if (flags & KMM_DESPERATE) {
}
return (B_TRUE);
}
callback, TQ_NOSLEEP)) {
return (B_FALSE);
}
return (B_TRUE);
}
static void
{
/*
* The last pending move completed. Release all slabs from the
* front of the dead list except for any slab at the tail that
* needs to be released from the context of kmem_move_buffers().
* kmem deferred unmapping the buffers on these slabs in order
* to guarantee that buffers passed to the move callback have
* been touched only by kmem or by the client itself.
*/
break;
}
cp->cache_slab_destroy++;
}
}
}
/*
* Move buffers from least used slabs first by scanning backwards from the end
* of the partial slab list. Scan at most max_scan candidate slabs and move
* buffers from at most max_slabs slabs (0 for all partial slabs in both cases).
* If desperate to reclaim memory, move buffers from any partial slab, otherwise
* skip slabs with a ratio of allocated buffers at or above the current
* threshold. Return the number of unskipped slabs (at most max_slabs, -1 if the
* scan is aborted) so that the caller can adjust the reclaimability threshold
* depending on how many reclaimable slabs it finds.
*
* kmem_move_buffers() drops and reacquires cache_lock every time it issues a
* move request, since it is not valid for kmem_move_begin() to call
* kmem_cache_alloc() or taskq_dispatch() with cache_lock held.
*/
static int
int flags)
{
void *buf;
int i, j; /* slab index, buffer index */
int s; /* reclaimable slabs */
int b; /* allocated (movable) buffers on reclaimable slab */
int refcnt;
int nomove;
if (kmem_move_blocked) {
return (0);
}
if (kmem_move_fulltilt) {
flags |= KMM_DESPERATE;
}
/*
* Scan as many slabs as needed to find the desired number of
* candidate slabs.
*/
}
/* Find as many candidate slabs as possible. */
}
continue;
}
s++;
/* Look for allocated buffers to move. */
continue;
}
b++;
/*
* Prevent the slab from being destroyed while we drop
* cache_lock and while the pending move is not yet
* registered. Flag the pending move while
* kmd_moves_pending may still be empty, since we can't
* yet rely on a non-zero pending move count to prevent
* the slab from being destroyed.
*/
/*
* Recheck refcnt and nomove after reacquiring the lock,
* since these control the order of partial slabs, and
* we want to know if we can pick up the scan where we
* left off.
*/
/*
* Now, before the lock is reacquired, kmem could
* process all pending move requests and purge the
* deadlist, so that upon reacquiring the lock, sp has
* been remapped. Or, the client may free all the
* objects on the slab while the pending moves are still
* on the taskq. Therefore, the KMEM_SLAB_MOVE_PENDING
* flag causes the slab to be put at the end of the
* deadlist and prevents it from being destroyed, since
* we plan to destroy it here after reacquiring the
* lock.
*/
if (sp->slab_refcnt == 0) {
if (!avl_is_empty(
/*
* A pending move makes it unsafe to
* destroy the slab, because even though
* the move is no longer needed, the
* context where that is determined
* requires the slab to exist.
* Fortunately, a pending move also
* means we don't need to destroy the
* slab here, since it will get
* destroyed along with any other slabs
* on the deadlist after the last
* pending move completes.
*/
return (-1);
}
/*
* Destroy the slab now if it was completely
* freed while we dropped cache_lock and there
* are no pending moves. Since slab_refcnt
* cannot change once it reaches zero, no new
* pending moves from that slab are possible.
*/
cp->cache_slab_destroy++;
/*
* Since we can't pick up the scan where we left
* off, abort the scan and say nothing about the
* number of reclaimable slabs.
*/
return (-1);
}
if (!success) {
/*
* Abort the scan if there is not enough memory
* for the request and say nothing about the
* number of reclaimable slabs.
*/
return (-1);
}
/*
* The slab's position changed while the lock was
* dropped, so we don't know where we are in the
* sequence any more.
*/
/*
* If this is a KMM_DEBUG move, the slab_refcnt
* may have changed because we allocated a
* destination buffer on the same slab. In that
* case, we're not interested in counting it.
*/
(s < max_slabs),
return (-1);
}
return (-1);
}
/*
* Generating a move request allocates a destination
* buffer from the slab layer, bumping the first partial
* slab if it is completely allocated. If the current
* slab becomes the first partial slab as a result, we
* can't continue to scan backwards.
*
* If this is a KMM_DEBUG move and we allocated the
* destination buffer from the last partial slab, then
* the buffer we're moving is on the same slab and our
* slab_refcnt has changed, causing us to return before
* reaching here if there are no partial slabs left.
*/
/*
* We're not interested in a second KMM_DEBUG
* move.
*/
goto end_scan;
}
}
}
(s < max_slabs) &&
return (s);
}
typedef struct kmem_move_notify_args {
void *kmna_buf;
static void
kmem_cache_move_notify_task(void *arg)
{
/* Ignore the notification if the buffer is no longer allocated. */
return;
}
/* Ignore the notification if there's no reason to move the buffer. */
/*
* So far the notification is not ignored. Ignore the
* notification if the slab is not marked by an earlier refusal
* to move a buffer.
*/
(sp->slab_later_count == 0)) {
return;
}
/* see kmem_move_buffers() about dropping the lock */
if (sp->slab_refcnt == 0) {
if (!avl_is_empty(
return;
}
cp->cache_slab_destroy++;
return;
}
} else {
}
}
void
{
if (!taskq_dispatch(kmem_taskq,
}
}
static void
{
size_t n;
if (n > 1) {
/* kmem_move_buffers() drops and reacquires cache_lock */
}
}
/* Is this cache above the fragmentation threshold? */
static boolean_t
{
/*
* nfree kmem_frag_numer
* ------------------ > ---------------
* cp->cache_buftotal kmem_frag_denom
*/
return ((nfree * kmem_frag_denom) >
}
static boolean_t
{
if (kmem_move_fulltilt) {
return (B_TRUE);
}
} else {
return (B_FALSE);
}
}
/*
* Free buffers in the magazine layer appear allocated from the point of
* view of the slab layer. We want to know if the slab layer would
* appear fragmented if we included free buffers from magazines that
* have fallen out of the working set.
*/
if (!fragmented) {
long reap;
}
}
return (fragmented);
}
/* Called periodically from kmem_taskq */
static void
{
if (kmd->kmd_consolidate > 0) {
kmd->kmd_consolidate--;
return;
}
/*
* Consolidate reclaimable slabs from the end of the partial
* slab list (scan at most kmem_reclaim_scan_range slabs to find
* reclaimable slabs). Keep track of how many candidate slabs we
* looked for and how many we actually found so we can adjust
* the definition of a candidate slab if we're having trouble
* finding them.
*
* kmem_move_buffers() drops and reacquires cache_lock.
*/
if (slabs_found >= 0) {
}
/*
* If we had difficulty finding candidate slabs in
* previous scans, adjust the threshold so that
* candidates are easier to find.
*/
kmd->kmd_slabs_sought) {
}
kmd->kmd_slabs_sought = 0;
kmd->kmd_slabs_found = 0;
}
} else {
#ifdef DEBUG
/*
* In a debug kernel we want the consolidator to
* run occasionally even when there is plenty of
* memory.
*/
if (!kmem_move_noreap &&
((debug_rand % kmem_mtb_reap) == 0)) {
return;
} else if ((debug_rand % kmem_mtb_move) == 0) {
(void) kmem_move_buffers(cp,
}
}
#endif /* DEBUG */
}
if (reap) {
}
}