17c478bdstevel@tonic-gate/*
27c478bdstevel@tonic-gate * CDDL HEADER START
37c478bdstevel@tonic-gate *
47c478bdstevel@tonic-gate * The contents of this file are subject to the terms of the
57d69246dp * Common Development and Distribution License (the "License").
67d69246dp * You may not use this file except in compliance with the License.
77c478bdstevel@tonic-gate *
87c478bdstevel@tonic-gate * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
97c478bdstevel@tonic-gate * or http://www.opensolaris.org/os/licensing.
107c478bdstevel@tonic-gate * See the License for the specific language governing permissions
117c478bdstevel@tonic-gate * and limitations under the License.
127c478bdstevel@tonic-gate *
137c478bdstevel@tonic-gate * When distributing Covered Code, include this CDDL HEADER in each
147c478bdstevel@tonic-gate * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
157c478bdstevel@tonic-gate * If applicable, add the following below this CDDL HEADER, with the
167c478bdstevel@tonic-gate * fields enclosed by brackets "[]" replaced with your own identifying
177c478bdstevel@tonic-gate * information: Portions Copyright [yyyy] [name of copyright owner]
187c478bdstevel@tonic-gate *
197c478bdstevel@tonic-gate * CDDL HEADER END
207c478bdstevel@tonic-gate */
217c478bdstevel@tonic-gate/*
22b942e89David Valin * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
23929d5b4Matthew Ahrens * Copyright (c) 2012, 2017 by Delphix. All rights reserved.
240c833d6Josef 'Jeff' Sipek * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
2536a64e6Tim Kordas * Copyright 2018, Joyent, Inc.
267c478bdstevel@tonic-gate */
277c478bdstevel@tonic-gate
287c478bdstevel@tonic-gate/*
29b5fca8ftomee * Kernel memory allocator, as described in the following two papers and a
30b5fca8ftomee * statement about the consolidator:
317c478bdstevel@tonic-gate *
327c478bdstevel@tonic-gate * Jeff Bonwick,
337c478bdstevel@tonic-gate * The Slab Allocator: An Object-Caching Kernel Memory Allocator.
347c478bdstevel@tonic-gate * Proceedings of the Summer 1994 Usenix Conference.
357c478bdstevel@tonic-gate * Available as /shared/sac/PSARC/1994/028/materials/kmem.pdf.
367c478bdstevel@tonic-gate *
377c478bdstevel@tonic-gate * Jeff Bonwick and Jonathan Adams,
387c478bdstevel@tonic-gate * Magazines and vmem: Extending the Slab Allocator to Many CPUs and
397c478bdstevel@tonic-gate * Arbitrary Resources.
407c478bdstevel@tonic-gate * Proceedings of the 2001 Usenix Conference.
417c478bdstevel@tonic-gate * Available as /shared/sac/PSARC/2000/550/materials/vmem.pdf.
42b5fca8ftomee *
43b5fca8ftomee * kmem Slab Consolidator Big Theory Statement:
44b5fca8ftomee *
45b5fca8ftomee * 1. Motivation
46b5fca8ftomee *
47b5fca8ftomee * As stated in Bonwick94, slabs provide the following advantages over other
48b5fca8ftomee * allocation structures in terms of memory fragmentation:
49b5fca8ftomee *
50b5fca8ftomee *  - Internal fragmentation (per-buffer wasted space) is minimal.
51b5fca8ftomee *  - Severe external fragmentation (unused buffers on the free list) is
52b5fca8ftomee *    unlikely.
53b5fca8ftomee *
54b5fca8ftomee * Segregating objects by size eliminates one source of external fragmentation,
55b5fca8ftomee * and according to Bonwick:
56b5fca8ftomee *
57b5fca8ftomee *   The other reason that slabs reduce external fragmentation is that all
58b5fca8ftomee *   objects in a slab are of the same type, so they have the same lifetime
59b5fca8ftomee *   distribution. The resulting segregation of short-lived and long-lived
60b5fca8ftomee *   objects at slab granularity reduces the likelihood of an entire page being
61b5fca8ftomee *   held hostage due to a single long-lived allocation [Barrett93, Hanson90].
62b5fca8ftomee *
63b5fca8ftomee * While unlikely, severe external fragmentation remains possible. Clients that
64b5fca8ftomee * allocate both short- and long-lived objects from the same cache cannot
65b5fca8ftomee * anticipate the distribution of long-lived objects within the allocator's slab
66b5fca8ftomee * implementation. Even a small percentage of long-lived objects distributed
67b5fca8ftomee * randomly across many slabs can lead to a worst case scenario where the client
68b5fca8ftomee * frees the majority of its objects and the system gets back almost none of the
69b5fca8ftomee * slabs. Despite the client doing what it reasonably can to help the system
70b5fca8ftomee * reclaim memory, the allocator cannot shake free enough slabs because of
71b5fca8ftomee * lonely allocations stubbornly hanging on. Although the allocator is in a
72b5fca8ftomee * position to diagnose the fragmentation, there is nothing that the allocator
73b5fca8ftomee * by itself can do about it. It only takes a single allocated object to prevent
74b5fca8ftomee * an entire slab from being reclaimed, and any object handed out by
75b5fca8ftomee * kmem_cache_alloc() is by definition in the client's control. Conversely,
76b5fca8ftomee * although the client is in a position to move a long-lived object, it has no
77b5fca8ftomee * way of knowing if the object is causing fragmentation, and if so, where to
78b5fca8ftomee * move it. A solution necessarily requires further cooperation between the
79b5fca8ftomee * allocator and the client.
80b5fca8ftomee *
81b5fca8ftomee * 2. Move Callback
82b5fca8ftomee *
83b5fca8ftomee * The kmem slab consolidator therefore adds a move callback to the
84b5fca8ftomee * allocator/client interface, improving worst-case external fragmentation in
85b5fca8ftomee * kmem caches that supply a function to move objects from one memory location
86b5fca8ftomee * to another. In a situation of low memory kmem attempts to consolidate all of
87b5fca8ftomee * a cache's slabs at once; otherwise it works slowly to bring external
88b5fca8ftomee * fragmentation within the 1/8 limit guaranteed for internal fragmentation,
89b5fca8ftomee * thereby helping to avoid a low memory situation in the future.
90b5fca8ftomee *
91b5fca8ftomee * The callback has the following signature:
92b5fca8ftomee *
93b5fca8ftomee *   kmem_cbrc_t move(void *old, void *new, size_t size, void *user_arg)
94b5fca8ftomee *
95b5fca8ftomee * It supplies the kmem client with two addresses: the allocated object that
96b5fca8ftomee * kmem wants to move and a buffer selected by kmem for the client to use as the
97b5fca8ftomee * copy destination. The callback is kmem's way of saying "Please get off of
98b5fca8ftomee * this buffer and use this one instead." kmem knows where it wants to move the
99b5fca8ftomee * object in order to best reduce fragmentation. All the client needs to know
100b5fca8ftomee * about the second argument (void *new) is that it is an allocated, constructed
101b5fca8ftomee * object ready to take the contents of the old object. When the move function
102b5fca8ftomee * is called, the system is likely to be low on memory, and the new object
103b5fca8ftomee * spares the client from having to worry about allocating memory for the
104b5fca8ftomee * requested move. The third argument supplies the size of the object, in case a
105b5fca8ftomee * single move function handles multiple caches whose objects differ only in
106b5fca8ftomee * size (such as zio_buf_512, zio_buf_1024, etc). Finally, the same optional
107b5fca8ftomee * user argument passed to the constructor, destructor, and reclaim functions is
108b5fca8ftomee * also passed to the move callback.
109b5fca8ftomee *
110b5fca8ftomee * 2.1 Setting the Move Callback
111b5fca8ftomee *
112b5fca8ftomee * The client sets the move callback after creating the cache and before
113b5fca8ftomee * allocating from it:
114b5fca8ftomee *
115b5fca8ftomee *	object_cache = kmem_cache_create(...);
116b5fca8ftomee *      kmem_cache_set_move(object_cache, object_move);
117b5fca8ftomee *
118b5fca8ftomee * 2.2 Move Callback Return Values
119b5fca8ftomee *
120b5fca8ftomee * Only the client knows about its own data and when is a good time to move it.
121b5fca8ftomee * The client is cooperating with kmem to return unused memory to the system,
122b5fca8ftomee * and kmem respectfully accepts this help at the client's convenience. When
123b5fca8ftomee * asked to move an object, the client can respond with any of the following:
124b5fca8ftomee *
125b5fca8ftomee *   typedef enum kmem_cbrc {
126b5fca8ftomee *           KMEM_CBRC_YES,
127b5fca8ftomee *           KMEM_CBRC_NO,
128b5fca8ftomee *           KMEM_CBRC_LATER,
129b5fca8ftomee *           KMEM_CBRC_DONT_NEED,
130b5fca8ftomee *           KMEM_CBRC_DONT_KNOW
131b5fca8ftomee *   } kmem_cbrc_t;
132b5fca8ftomee *
133b5fca8ftomee * The client must not explicitly kmem_cache_free() either of the objects passed
134b5fca8ftomee * to the callback, since kmem wants to free them directly to the slab layer
135b5fca8ftomee * (bypassing the per-CPU magazine layer). The response tells kmem which of the
136b5fca8ftomee * objects to free:
137b5fca8ftomee *
138b5fca8ftomee *       YES: (Did it) The client moved the object, so kmem frees the old one.
139b5fca8ftomee *        NO: (Never) The client refused, so kmem frees the new object (the
140b5fca8ftomee *            unused copy destination). kmem also marks the slab of the old
141b5fca8ftomee *            object so as not to bother the client with further callbacks for
142b5fca8ftomee *            that object as long as the slab remains on the partial slab list.
143b5fca8ftomee *            (The system won't be getting the slab back as long as the
144b5fca8ftomee *            immovable object holds it hostage, so there's no point in moving
145b5fca8ftomee *            any of its objects.)
146b5fca8ftomee *     LATER: The client is using the object and cannot move it now, so kmem
147b5fca8ftomee *            frees the new object (the unused copy destination). kmem still
148b5fca8ftomee *            attempts to move other objects off the slab, since it expects to
149b5fca8ftomee *            succeed in clearing the slab in a later callback. The client
150b5fca8ftomee *            should use LATER instead of NO if the object is likely to become
151b5fca8ftomee *            movable very soon.
152b5fca8ftomee * DONT_NEED: The client no longer needs the object, so kmem frees the old along
153b5fca8ftomee *            with the new object (the unused copy destination). This response
154b5fca8ftomee *            is the client's opportunity to be a model citizen and give back as
155b5fca8ftomee *            much as it can.
156b5fca8ftomee * DONT_KNOW: The client does not know about the object because
157b5fca8ftomee *            a) the client has just allocated the object and not yet put it
158b5fca8ftomee *               wherever it expects to find known objects
159b5fca8ftomee *            b) the client has removed the object from wherever it expects to
160b5fca8ftomee *               find known objects and is about to free it, or
161b5fca8ftomee *            c) the client has freed the object.
162b5fca8ftomee *            In all these cases (a, b, and c) kmem frees the new object (the
163d7db73dBryan Cantrill *            unused copy destination).  In the first case, the object is in
164d7db73dBryan Cantrill *            use and the correct action is that for LATER; in the latter two
165d7db73dBryan Cantrill *            cases, we know that the object is either freed or about to be
166d7db73dBryan Cantrill *            freed, in which case it is either already in a magazine or about
167d7db73dBryan Cantrill *            to be in one.  In these cases, we know that the object will either
168d7db73dBryan Cantrill *            be reallocated and reused, or it will end up in a full magazine
169d7db73dBryan Cantrill *            that will be reaped (thereby liberating the slab).  Because it
170d7db73dBryan Cantrill *            is prohibitively expensive to differentiate these cases, and
171d7db73dBryan Cantrill *            because the defrag code is executed when we're low on memory
172d7db73dBryan Cantrill *            (thereby biasing the system to reclaim full magazines) we treat
173d7db73dBryan Cantrill *            all DONT_KNOW cases as LATER and rely on cache reaping to
174d7db73dBryan Cantrill *            generally clean up full magazines.  While we take the same action
175d7db73dBryan Cantrill *            for these cases, we maintain their semantic distinction:  if
176d7db73dBryan Cantrill *            defragmentation is not occurring, it is useful to know if this
177d7db73dBryan Cantrill *            is due to objects in use (LATER) or objects in an unknown state
178d7db73dBryan Cantrill *            of transition (DONT_KNOW).
179b5fca8ftomee *
180b5fca8ftomee * 2.3 Object States
181b5fca8ftomee *
182b5fca8ftomee * Neither kmem nor the client can be assumed to know the object's whereabouts
183b5fca8ftomee * at the time of the callback. An object belonging to a kmem cache may be in
184b5fca8ftomee * any of the following states:
185b5fca8ftomee *
186b5fca8ftomee * 1. Uninitialized on the slab
187b5fca8ftomee * 2. Allocated from the slab but not constructed (still uninitialized)
188b5fca8ftomee * 3. Allocated from the slab, constructed, but not yet ready for business
189b5fca8ftomee *    (not in a valid state for the move callback)
190b5fca8ftomee * 4. In use (valid and known to the client)
191b5fca8ftomee * 5. About to be freed (no longer in a valid state for the move callback)
192b5fca8ftomee * 6. Freed to a magazine (still constructed)
193b5fca8ftomee * 7. Allocated from a magazine, not yet ready for business (not in a valid
194b5fca8ftomee *    state for the move callback), and about to return to state #4
195b5fca8ftomee * 8. Deconstructed on a magazine that is about to be freed
196b5fca8ftomee * 9. Freed to the slab
197b5fca8ftomee *
198b5fca8ftomee * Since the move callback may be called at any time while the object is in any
199b5fca8ftomee * of the above states (except state #1), the client needs a safe way to
200b5fca8ftomee * determine whether or not it knows about the object. Specifically, the client
201b5fca8ftomee * needs to know whether or not the object is in state #4, the only state in
202b5fca8ftomee * which a move is valid. If the object is in any other state, the client should
203b5fca8ftomee * immediately return KMEM_CBRC_DONT_KNOW, since it is unsafe to access any of
204b5fca8ftomee * the object's fields.
205b5fca8ftomee *
206b5fca8ftomee * Note that although an object may be in state #4 when kmem initiates the move
207b5fca8ftomee * request, the object may no longer be in that state by the time kmem actually
208b5fca8ftomee * calls the move function. Not only does the client free objects
209b5fca8ftomee * asynchronously, kmem itself puts move requests on a queue where thay are
210b5fca8ftomee * pending until kmem processes them from another context. Also, objects freed
211b5fca8ftomee * to a magazine appear allocated from the point of view of the slab layer, so
212b5fca8ftomee * kmem may even initiate requests for objects in a state other than state #4.
213b5fca8ftomee *
214b5fca8ftomee * 2.3.1 Magazine Layer
215b5fca8ftomee *
216b5fca8ftomee * An important insight revealed by the states listed above is that the magazine
217b5fca8ftomee * layer is populated only by kmem_cache_free(). Magazines of constructed
218b5fca8ftomee * objects are never populated directly from the slab layer (which contains raw,
219b5fca8ftomee * unconstructed objects). Whenever an allocation request cannot be satisfied
220b5fca8ftomee * from the magazine layer, the magazines are bypassed and the request is
221b5fca8ftomee * satisfied from the slab layer (creating a new slab if necessary). kmem calls
222b5fca8ftomee * the object constructor only when allocating from the slab layer, and only in
223b5fca8ftomee * response to kmem_cache_alloc() or to prepare the destination buffer passed in
224b5fca8ftomee * the move callback. kmem does not preconstruct objects in anticipation of
225b5fca8ftomee * kmem_cache_alloc().
226b5fca8ftomee *
227b5fca8ftomee * 2.3.2 Object Constructor and Destructor
228b5fca8ftomee *
229b5fca8ftomee * If the client supplies a destructor, it must be valid to call the destructor
230b5fca8ftomee * on a newly created object (immediately after the constructor).
231b5fca8ftomee *
232b5fca8ftomee * 2.4 Recognizing Known Objects
233b5fca8ftomee *
234b5fca8ftomee * There is a simple test to determine safely whether or not the client knows
235b5fca8ftomee * about a given object in the move callback. It relies on the fact that kmem
236b5fca8ftomee * guarantees that the object of the move callback has only been touched by the
237b5fca8ftomee * client itself or else by kmem. kmem does this by ensuring that none of the
238b5fca8ftomee * cache's slabs are freed to the virtual memory (VM) subsystem while a move
239b5fca8ftomee * callback is pending. When the last object on a slab is freed, if there is a
240b5fca8ftomee * pending move, kmem puts the slab on a per-cache dead list and defers freeing
241b5fca8ftomee * slabs on that list until all pending callbacks are completed. That way,
242b5fca8ftomee * clients can be certain that the object of a move callback is in one of the
243b5fca8ftomee * states listed above, making it possible to distinguish known objects (in
244b5fca8ftomee * state #4) using the two low order bits of any pointer member (with the
245b5fca8ftomee * exception of 'char *' or 'short *' which may not be 4-byte aligned on some
246b5fca8ftomee * platforms).
247b5fca8ftomee *
248b5fca8ftomee * The test works as long as the client always transitions objects from state #4
249b5fca8ftomee * (known, in use) to state #5 (about to be freed, invalid) by setting the low
250b5fca8ftomee * order bit of the client-designated pointer member. Since kmem only writes
251b5fca8ftomee * invalid memory patterns, such as 0xbaddcafe to uninitialized memory and
252b5fca8ftomee * 0xdeadbeef to freed memory, any scribbling on the object done by kmem is
253b5fca8ftomee * guaranteed to set at least one of the two low order bits. Therefore, given an
254b5fca8ftomee * object with a back pointer to a 'container_t *o_container', the client can
255b5fca8ftomee * test
256b5fca8ftomee *
257b5fca8ftomee *      container_t *container = object->o_container;
258b5fca8ftomee *      if ((uintptr_t)container & 0x3) {
259b5fca8ftomee *              return (KMEM_CBRC_DONT_KNOW);
260b5fca8ftomee *      }
261b5fca8ftomee *
262b5fca8ftomee * Typically, an object will have a pointer to some structure with a list or
263b5fca8ftomee * hash where objects from the cache are kept while in use. Assuming that the
264b5fca8ftomee * client has some way of knowing that the container structure is valid and will
265b5fca8ftomee * not go away during the move, and assuming that the structure includes a lock
266b5fca8ftomee * to protect whatever collection is used, then the client would continue as
267b5fca8ftomee * follows:
268b5fca8ftomee *
269b5fca8ftomee *	// Ensure that the container structure does not go away.
270b5fca8ftomee *      if (container_hold(container) == 0) {
271b5fca8ftomee *              return (KMEM_CBRC_DONT_KNOW);
272b5fca8ftomee *      }
273b5fca8ftomee *      mutex_enter(&container->c_objects_lock);
274b5fca8ftomee *      if (container != object->o_container) {
275b5fca8ftomee *              mutex_exit(&container->c_objects_lock);
276b5fca8ftomee *              container_rele(container);
277b5fca8ftomee *              return (KMEM_CBRC_DONT_KNOW);
278b5fca8ftomee *      }
279b5fca8ftomee *
280b5fca8ftomee * At this point the client knows that the object cannot be freed as long as
281b5fca8ftomee * c_objects_lock is held. Note that after acquiring the lock, the client must
282b5fca8ftomee * recheck the o_container pointer in case the object was removed just before
283b5fca8ftomee * acquiring the lock.
284b5fca8ftomee *
285b5fca8ftomee * When the client is about to free an object, it must first remove that object
286b5fca8ftomee * from the list, hash, or other structure where it is kept. At that time, to
287b5fca8ftomee * mark the object so it can be distinguished from the remaining, known objects,
288b5fca8ftomee * the client sets the designated low order bit:
289b5fca8ftomee *
290b5fca8ftomee *      mutex_enter(&container->c_objects_lock);
291b5fca8ftomee *      object->o_container = (void *)((uintptr_t)object->o_container | 0x1);
292b5fca8ftomee *      list_remove(&container->c_objects, object);
293b5fca8ftomee *      mutex_exit(&container->c_objects_lock);
294b5fca8ftomee *
295b5fca8ftomee * In the common case, the object is freed to the magazine layer, where it may
296b5fca8ftomee * be reused on a subsequent allocation without the overhead of calling the
297b5fca8ftomee * constructor. While in the magazine it appears allocated from the point of
298b5fca8ftomee * view of the slab layer, making it a candidate for the move callback. Most
299b5fca8ftomee * objects unrecognized by the client in the move callback fall into this
300b5fca8ftomee * category and are cheaply distinguished from known objects by the test
301d7db73dBryan Cantrill * described earlier. Because searching magazines is prohibitively expensive
302d7db73dBryan Cantrill * for kmem, clients that do not mark freed objects (and therefore return
303d7db73dBryan Cantrill * KMEM_CBRC_DONT_KNOW for large numbers of objects) may find defragmentation
304d7db73dBryan Cantrill * efficacy reduced.
305b5fca8ftomee *
306b5fca8ftomee * Invalidating the designated pointer member before freeing the object marks
307b5fca8ftomee * the object to be avoided in the callback, and conversely, assigning a valid
308b5fca8ftomee * value to the designated pointer member after allocating the object makes the
309b5fca8ftomee * object fair game for the callback:
310b5fca8ftomee *
311b5fca8ftomee *      ... allocate object ...
312b5fca8ftomee *      ... set any initial state not set by the constructor ...
313b5fca8ftomee *
314b5fca8ftomee *      mutex_enter(&container->c_objects_lock);
315b5fca8ftomee *      list_insert_tail(&container->c_objects, object);
316b5fca8ftomee *      membar_producer();
317b5fca8ftomee *      object->o_container = container;
318b5fca8ftomee *      mutex_exit(&container->c_objects_lock);
319b5fca8ftomee *
320b5fca8ftomee * Note that everything else must be valid before setting o_container makes the
321b5fca8ftomee * object fair game for the move callback. The membar_producer() call ensures
322b5fca8ftomee * that all the object's state is written to memory before setting the pointer
323b5fca8ftomee * that transitions the object from state #3 or #7 (allocated, constructed, not
324b5fca8ftomee * yet in use) to state #4 (in use, valid). That's important because the move
325b5fca8ftomee * function has to check the validity of the pointer before it can safely
326b5fca8ftomee * acquire the lock protecting the collection where it expects to find known
327b5fca8ftomee * objects.
328b5fca8ftomee *
329b5fca8ftomee * This method of distinguishing known objects observes the usual symmetry:
330b5fca8ftomee * invalidating the designated pointer is the first thing the client does before
331b5fca8ftomee * freeing the object, and setting the designated pointer is the last thing the
332b5fca8ftomee * client does after allocating the object. Of course, the client is not
333b5fca8ftomee * required to use this method. Fundamentally, how the client recognizes known
334b5fca8ftomee * objects is completely up to the client, but this method is recommended as an
335b5fca8ftomee * efficient and safe way to take advantage of the guarantees made by kmem. If
336b5fca8ftomee * the entire object is arbitrary data without any markable bits from a suitable
337b5fca8ftomee * pointer member, then the client must find some other method, such as
338b5fca8ftomee * searching a hash table of known objects.
339b5fca8ftomee *
340b5fca8ftomee * 2.5 Preventing Objects From Moving
341b5fca8ftomee *
342b5fca8ftomee * Besides a way to distinguish known objects, the other thing that the client
343b5fca8ftomee * needs is a strategy to ensure that an object will not move while the client
344b5fca8ftomee * is actively using it. The details of satisfying this requirement tend to be
345b5fca8ftomee * highly cache-specific. It might seem that the same rules that let a client
346b5fca8ftomee * remove an object safely should also decide when an object can be moved
347b5fca8ftomee * safely. However, any object state that makes a removal attempt invalid is
348b5fca8ftomee * likely to be long-lasting for objects that the client does not expect to
349b5fca8ftomee * remove. kmem knows nothing about the object state and is equally likely (from
350b5fca8ftomee * the client's point of view) to request a move for any object in the cache,
351b5fca8ftomee * whether prepared for removal or not. Even a low percentage of objects stuck
352b5fca8ftomee * in place by unremovability will defeat the consolidator if the stuck objects
353b5fca8ftomee * are the same long-lived allocations likely to hold slabs hostage.
354b5fca8ftomee * Fundamentally, the consolidator is not aimed at common cases. Severe external
355b5fca8ftomee * fragmentation is a worst case scenario manifested as sparsely allocated
356b5fca8ftomee * slabs, by definition a low percentage of the cache's objects. When deciding
357b5fca8ftomee * what makes an object movable, keep in mind the goal of the consolidator: to
358b5fca8ftomee * bring worst-case external fragmentation within the limits guaranteed for
359b5fca8ftomee * internal fragmentation. Removability is a poor criterion if it is likely to
360b5fca8ftomee * exclude more than an insignificant percentage of objects for long periods of
361b5fca8ftomee * time.
362b5fca8ftomee *
363b5fca8ftomee * A tricky general solution exists, and it has the advantage of letting you
364b5fca8ftomee * move any object at almost any moment, practically eliminating the likelihood
365b5fca8ftomee * that an object can hold a slab hostage. However, if there is a cache-specific
366b5fca8ftomee * way to ensure that an object is not actively in use in the vast majority of
367b5fca8ftomee * cases, a simpler solution that leverages this cache-specific knowledge is
368b5fca8ftomee * preferred.
369b5fca8ftomee *
370b5fca8ftomee * 2.5.1 Cache-Specific Solution
371b5fca8ftomee *
372b5fca8ftomee * As an example of a cache-specific solution, the ZFS znode cache takes
373b5fca8ftomee * advantage of the fact that the vast majority of znodes are only being
374b5fca8ftomee * referenced from the DNLC. (A typical case might be a few hundred in active
375b5fca8ftomee * use and a hundred thousand in the DNLC.) In the move callback, after the ZFS
376b5fca8ftomee * client has established that it recognizes the znode and can access its fields
377b5fca8ftomee * safely (using the method described earlier), it then tests whether the znode
378b5fca8ftomee * is referenced by anything other than the DNLC. If so, it assumes that the
379b5fca8ftomee * znode may be in active use and is unsafe to move, so it drops its locks and
380b5fca8ftomee * returns KMEM_CBRC_LATER. The advantage of this strategy is that everywhere
381b5fca8ftomee * else znodes are used, no change is needed to protect against the possibility
382b5fca8ftomee * of the znode moving. The disadvantage is that it remains possible for an
383b5fca8ftomee * application to hold a znode slab hostage with an open file descriptor.
384b5fca8ftomee * However, this case ought to be rare and the consolidator has a way to deal
385b5fca8ftomee * with it: If the client responds KMEM_CBRC_LATER repeatedly for the same
386b5fca8ftomee * object, kmem eventually stops believing it and treats the slab as if the
387b5fca8ftomee * client had responded KMEM_CBRC_NO. Having marked the hostage slab, kmem can
388b5fca8ftomee * then focus on getting it off of the partial slab list by allocating rather
389b5fca8ftomee * than freeing all of its objects. (Either way of getting a slab off the
390b5fca8ftomee * free list reduces fragmentation.)
391b5fca8ftomee *
392b5fca8ftomee * 2.5.2 General Solution
393b5fca8ftomee *
394b5fca8ftomee * The general solution, on the other hand, requires an explicit hold everywhere
395b5fca8ftomee * the object is used to prevent it from moving. To keep the client locking
396b5fca8ftomee * strategy as uncomplicated as possible, kmem guarantees the simplifying
397b5fca8ftomee * assumption that move callbacks are sequential, even across multiple caches.
398b5fca8ftomee * Internally, a global queue processed by a single thread supports all caches
399b5fca8ftomee * implementing the callback function. No matter how many caches supply a move
400b5fca8ftomee * function, the consolidator never moves more than one object at a time, so the
401b5fca8ftomee * client does not have to worry about tricky lock ordering involving several
402b5fca8ftomee * related objects from different kmem caches.
403b5fca8ftomee *
404b5fca8ftomee * The general solution implements the explicit hold as a read-write lock, which
405b5fca8ftomee * allows multiple readers to access an object from the cache simultaneously
406b5fca8ftomee * while a single writer is excluded from moving it. A single rwlock for the
407b5fca8ftomee * entire cache would lock out all threads from using any of the cache's objects
408b5fca8ftomee * even though only a single object is being moved, so to reduce contention,
409b5fca8ftomee * the client can fan out the single rwlock into an array of rwlocks hashed by
410b5fca8ftomee * the object address, making it probable that moving one object will not
411b5fca8ftomee * prevent other threads from using a different object. The rwlock cannot be a
412b5fca8ftomee * member of the object itself, because the possibility of the object moving
413b5fca8ftomee * makes it unsafe to access any of the object's fields until the lock is
414b5fca8ftomee * acquired.
415b5fca8ftomee *
416b5fca8ftomee * Assuming a small, fixed number of locks, it's possible that multiple objects
417b5fca8ftomee * will hash to the same lock. A thread that needs to use multiple objects in
418b5fca8ftomee * the same function may acquire the same lock multiple times. Since rwlocks are
419b5fca8ftomee * reentrant for readers, and since there is never more than a single writer at
420b5fca8ftomee * a time (assuming that the client acquires the lock as a writer only when
421b5fca8ftomee * moving an object inside the callback), there would seem to be no problem.
422b5fca8ftomee * However, a client locking multiple objects in the same function must handle
423b5fca8ftomee * one case of potential deadlock: Assume that thread A needs to prevent both
424b5fca8ftomee * object 1 and object 2 from moving, and thread B, the callback, meanwhile
425b5fca8ftomee * tries to move object 3. It's possible, if objects 1, 2, and 3 all hash to the
426b5fca8ftomee * same lock, that thread A will acquire the lock for object 1 as a reader
427b5fca8ftomee * before thread B sets the lock's write-wanted bit, preventing thread A from
428b5fca8ftomee * reacquiring the lock for object 2 as a reader. Unable to make forward
429b5fca8ftomee * progress, thread A will never release the lock for object 1, resulting in
430b5fca8ftomee * deadlock.
431b5fca8ftomee *
432b5fca8ftomee * There are two ways of avoiding the deadlock just described. The first is to
433b5fca8ftomee * use rw_tryenter() rather than rw_enter() in the callback function when
434b5fca8ftomee * attempting to acquire the lock as a writer. If tryenter discovers that the
435b5fca8ftomee * same object (or another object hashed to the same lock) is already in use, it
436b5fca8ftomee * aborts the callback and returns KMEM_CBRC_LATER. The second way is to use
437b5fca8ftomee * rprwlock_t (declared in common/fs/zfs/sys/rprwlock.h) instead of rwlock_t,
438b5fca8ftomee * since it allows a thread to acquire the lock as a reader in spite of a
439b5fca8ftomee * waiting writer. This second approach insists on moving the object now, no
440b5fca8ftomee * matter how many readers the move function must wait for in order to do so,
441b5fca8ftomee * and could delay the completion of the callback indefinitely (blocking
442b5fca8ftomee * callbacks to other clients). In practice, a less insistent callback using
443b5fca8ftomee * rw_tryenter() returns KMEM_CBRC_LATER infrequently enough that there seems
444b5fca8ftomee * little reason to use anything else.
445b5fca8ftomee *
446b5fca8ftomee * Avoiding deadlock is not the only problem that an implementation using an
447b5fca8ftomee * explicit hold needs to solve. Locking the object in the first place (to
448b5fca8ftomee * prevent it from moving) remains a problem, since the object could move
449b5fca8ftomee * between the time you obtain a pointer to the object and the time you acquire
450b5fca8ftomee * the rwlock hashed to that pointer value. Therefore the client needs to
451b5fca8ftomee * recheck the value of the pointer after acquiring the lock, drop the lock if
452b5fca8ftomee * the value has changed, and try again. This requires a level of indirection:
453b5fca8ftomee * something that points to the object rather than the object itself, that the
454b5fca8ftomee * client can access safely while attempting to acquire the lock. (The object
455b5fca8ftomee * itself cannot be referenced safely because it can move at any time.)
456b5fca8ftomee * The following lock-acquisition function takes whatever is safe to reference
457b5fca8ftomee * (arg), follows its pointer to the object (using function f), and tries as
458b5fca8ftomee * often as necessary to acquire the hashed lock and verify that the object
459b5fca8ftomee * still has not moved:
460b5fca8ftomee *
461b5fca8ftomee *      object_t *
462b5fca8ftomee *      object_hold(object_f f, void *arg)
463b5fca8ftomee *      {
464b5fca8ftomee *              object_t *op;
465b5fca8ftomee *
466b5fca8ftomee *              op = f(arg);
467b5fca8ftomee *              if (op == NULL) {
468b5fca8ftomee *                      return (NULL);
469b5fca8ftomee *              }
470b5fca8ftomee *
471b5fca8ftomee *              rw_enter(OBJECT_RWLOCK(op), RW_READER);
472b5fca8ftomee *              while (op != f(arg)) {
473b5fca8ftomee *                      rw_exit(OBJECT_RWLOCK(op));
474b5fca8ftomee *                      op = f(arg);
475b5fca8ftomee *                      if (op == NULL) {
476b5fca8ftomee *                              break;
477b5fca8ftomee *                      }
478b5fca8ftomee *                      rw_enter(OBJECT_RWLOCK(op), RW_READER);
479b5fca8ftomee *              }
480b5fca8ftomee *
481b5fca8ftomee *              return (op);
482b5fca8ftomee *      }
483b5fca8ftomee *
484b5fca8ftomee * The OBJECT_RWLOCK macro hashes the object address to obtain the rwlock. The
485b5fca8ftomee * lock reacquisition loop, while necessary, almost never executes. The function
486b5fca8ftomee * pointer f (used to obtain the object pointer from arg) has the following type
487b5fca8ftomee * definition:
488b5fca8ftomee *
489b5fca8ftomee *      typedef object_t *(*object_f)(void *arg);
490b5fca8ftomee *
491b5fca8ftomee * An object_f implementation is likely to be as simple as accessing a structure
492b5fca8ftomee * member:
493b5fca8ftomee *
494b5fca8ftomee *      object_t *
495b5fca8ftomee *      s_object(void *arg)
496b5fca8ftomee *      {
497b5fca8ftomee *              something_t *sp = arg;
498b5fca8ftomee *              return (sp->s_object);
499b5fca8ftomee *      }
500b5fca8ftomee *
501b5fca8ftomee * The flexibility of a function pointer allows the path to the object to be
502b5fca8ftomee * arbitrarily complex and also supports the notion that depending on where you
503b5fca8ftomee * are using the object, you may need to get it from someplace different.
504b5fca8ftomee *
505b5fca8ftomee * The function that releases the explicit hold is simpler because it does not
506b5fca8ftomee * have to worry about the object moving:
507b5fca8ftomee *
508b5fca8ftomee *      void
509b5fca8ftomee *      object_rele(object_t *op)
510b5fca8ftomee *      {
511b5fca8ftomee *              rw_exit(OBJECT_RWLOCK(op));
512b5fca8ftomee *      }
513b5fca8ftomee *
514b5fca8ftomee * The caller is spared these details so that obtaining and releasing an
515b5fca8ftomee * explicit hold feels like a simple mutex_enter()/mutex_exit() pair. The caller
516b5fca8ftomee * of object_hold() only needs to know that the returned object pointer is valid
517b5fca8ftomee * if not NULL and that the object will not move until released.
518b5fca8ftomee *
519b5fca8ftomee * Although object_hold() prevents an object from moving, it does not prevent it
520b5fca8ftomee * from being freed. The caller must take measures before calling object_hold()
521b5fca8ftomee * (afterwards is too late) to ensure that the held object cannot be freed. The
522b5fca8ftomee * caller must do so without accessing the unsafe object reference, so any lock
523b5fca8ftomee * or reference count used to ensure the continued existence of the object must
524b5fca8ftomee * live outside the object itself.
525b5fca8ftomee *
526b5fca8ftomee * Obtaining a new object is a special case where an explicit hold is impossible
527b5fca8ftomee * for the caller. Any function that returns a newly allocated object (either as
528b5fca8ftomee * a return value, or as an in-out paramter) must return it already held; after
529b5fca8ftomee * the caller gets it is too late, since the object cannot be safely accessed
530b5fca8ftomee * without the level of indirection described earlier. The following
531b5fca8ftomee * object_alloc() example uses the same code shown earlier to transition a new
532b5fca8ftomee * object into the state of being recognized (by the client) as a known object.
533b5fca8ftomee * The function must acquire the hold (rw_enter) before that state transition
534b5fca8ftomee * makes the object movable:
535b5fca8ftomee *
536b5fca8ftomee *      static object_t *
537b5fca8ftomee *      object_alloc(container_t *container)
538b5fca8ftomee *      {
5394d4c4c4Tom Erickson *              object_t *object = kmem_cache_alloc(object_cache, 0);
540b5fca8ftomee *              ... set any initial state not set by the constructor ...
541b5fca8ftomee *              rw_enter(OBJECT_RWLOCK(object), RW_READER);
542b5fca8ftomee *              mutex_enter(&container->c_objects_lock);
543b5fca8ftomee *              list_insert_tail(&container->c_objects, object);
544b5fca8ftomee *              membar_producer();
545b5fca8ftomee *              object->o_container = container;
546b5fca8ftomee *              mutex_exit(&container->c_objects_lock);
547b5fca8ftomee *              return (object);
548b5fca8ftomee *      }
549b5fca8ftomee *
550b5fca8ftomee * Functions that implicitly acquire an object hold (any function that calls
551b5fca8ftomee * object_alloc() to supply an object for the caller) need to be carefully noted
552b5fca8ftomee * so that the matching object_rele() is not neglected. Otherwise, leaked holds
553b5fca8ftomee * prevent all objects hashed to the affected rwlocks from ever being moved.
554b5fca8ftomee *
555b5fca8ftomee * The pointer to a held object can be hashed to the holding rwlock even after
556b5fca8ftomee * the object has been freed. Although it is possible to release the hold
557b5fca8ftomee * after freeing the object, you may decide to release the hold implicitly in
558b5fca8ftomee * whatever function frees the object, so as to release the hold as soon as
559b5fca8ftomee * possible, and for the sake of symmetry with the function that implicitly
560b5fca8ftomee * acquires the hold when it allocates the object. Here, object_free() releases
561b5fca8ftomee * the hold acquired by object_alloc(). Its implicit object_rele() forms a
562b5fca8ftomee * matching pair with object_hold():
563b5fca8ftomee *
564b5fca8ftomee *      void
565b5fca8ftomee *      object_free(object_t *object)
566b5fca8ftomee *      {
567b5fca8ftomee *              container_t *container;
568b5fca8ftomee *
569b5fca8ftomee *              ASSERT(object_held(object));
570b5fca8ftomee *              container = object->o_container;
571b5fca8ftomee *              mutex_enter(&container->c_objects_lock);
572b5fca8ftomee *              object->o_container =
573b5fca8ftomee *                  (void *)((uintptr_t)object->o_container | 0x1);
574b5fca8ftomee *              list_remove(&container->c_objects, object);
575b5fca8ftomee *              mutex_exit(&container->c_objects_lock);
576b5fca8ftomee *              object_rele(object);
577b5fca8ftomee *              kmem_cache_free(object_cache, object);
578b5fca8ftomee *      }
579b5fca8ftomee *
580b5fca8ftomee * Note that object_free() cannot safely accept an object pointer as an argument
581b5fca8ftomee * unless the object is already held. Any function that calls object_free()
582b5fca8ftomee * needs to be carefully noted since it similarly forms a matching pair with
583b5fca8ftomee * object_hold().
584b5fca8ftomee *
585b5fca8ftomee * To complete the picture, the following callback function implements the
586b5fca8ftomee * general solution by moving objects only if they are currently unheld:
587b5fca8ftomee *
588b5fca8ftomee *      static kmem_cbrc_t
589b5fca8ftomee *      object_move(void *buf, void *newbuf, size_t size, void *arg)
590b5fca8ftomee *      {
591b5fca8ftomee *              object_t *op = buf, *np = newbuf;
592b5fca8ftomee *              container_t *container;
593b5fca8ftomee *
594b5fca8ftomee *              container = op->o_container;
595b5fca8ftomee *              if ((uintptr_t)container & 0x3) {
596b5fca8ftomee *                      return (KMEM_CBRC_DONT_KNOW);
597b5fca8ftomee *              }
598b5fca8ftomee *
599b5fca8ftomee *	        // Ensure that the container structure does not go away.
600b5fca8ftomee *              if (container_hold(container) == 0) {
601b5fca8ftomee *                      return (KMEM_CBRC_DONT_KNOW);
602b5fca8ftomee *              }
603b5fca8ftomee *
604b5fca8ftomee *              mutex_enter(&container->c_objects_lock);
605b5fca8ftomee *              if (container != op->o_container) {
606b5fca8ftomee *                      mutex_exit(&container->c_objects_lock);
607b5fca8ftomee *                      container_rele(container);
608b5fca8ftomee *                      return (KMEM_CBRC_DONT_KNOW);
609b5fca8ftomee *              }
610b5fca8ftomee *
611b5fca8ftomee *              if (rw_tryenter(OBJECT_RWLOCK(op), RW_WRITER) == 0) {
612b5fca8ftomee *                      mutex_exit(&container->c_objects_lock);
613b5fca8ftomee *                      container_rele(container);
614b5fca8ftomee *                      return (KMEM_CBRC_LATER);
615b5fca8ftomee *              }
616b5fca8ftomee *
617b5fca8ftomee *              object_move_impl(op, np); // critical section
618b5fca8ftomee *              rw_exit(OBJECT_RWLOCK(op));
619b5fca8ftomee *
620b5fca8ftomee *              op->o_container = (void *)((uintptr_t)op->o_container | 0x1);
621b5fca8ftomee *              list_link_replace(&op->o_link_node, &np->o_link_node);
622b5fca8ftomee *              mutex_exit(&container->c_objects_lock);
623b5fca8ftomee *              container_rele(container);
624b5fca8ftomee *              return (KMEM_CBRC_YES);
625b5fca8ftomee *      }
626b5fca8ftomee *
627b5fca8ftomee * Note that object_move() must invalidate the designated o_container pointer of
628b5fca8ftomee * the old object in the same way that object_free() does, since kmem will free
629b5fca8ftomee * the object in response to the KMEM_CBRC_YES return value.
630b5fca8ftomee *
631b5fca8ftomee * The lock order in object_move() differs from object_alloc(), which locks
632b5fca8ftomee * OBJECT_RWLOCK first and &container->c_objects_lock second, but as long as the
633b5fca8ftomee * callback uses rw_tryenter() (preventing the deadlock described earlier), it's
634b5fca8ftomee * not a problem. Holding the lock on the object list in the example above
635b5fca8ftomee * through the entire callback not only prevents the object from going away, it
636b5fca8ftomee * also allows you to lock the list elsewhere and know that none of its elements
637b5fca8ftomee * will move during iteration.
638b5fca8ftomee *
639b5fca8ftomee * Adding an explicit hold everywhere an object from the cache is used is tricky
640b5fca8ftomee * and involves much more change to client code than a cache-specific solution
641b5fca8ftomee * that leverages existing state to decide whether or not an object is
642b5fca8ftomee * movable. However, this approach has the advantage that no object remains
643b5fca8ftomee * immovable for any significant length of time, making it extremely unlikely
644b5fca8ftomee * that long-lived allocations can continue holding slabs hostage; and it works
645b5fca8ftomee * for any cache.
646b5fca8ftomee *
647b5fca8ftomee * 3. Consolidator Implementation
648b5fca8ftomee *
649b5fca8ftomee * Once the client supplies a move function that a) recognizes known objects and
650b5fca8ftomee * b) avoids moving objects that are actively in use, the remaining work is up
651b5fca8ftomee * to the consolidator to decide which objects to move and when to issue
652b5fca8ftomee * callbacks.
653b5fca8ftomee *
654b5fca8ftomee * The consolidator relies on the fact that a cache's slabs are ordered by
655b5fca8ftomee * usage. Each slab has a fixed number of objects. Depending on the slab's
656b5fca8ftomee * "color" (the offset of the first object from the beginning of the slab;
657b5fca8ftomee * offsets are staggered to mitigate false sharing of cache lines) it is either
658b5fca8ftomee * the maximum number of objects per slab determined at cache creation time or
659b5fca8ftomee * else the number closest to the maximum that fits within the space remaining
660b5fca8ftomee * after the initial offset. A completely allocated slab may contribute some
661b5fca8ftomee * internal fragmentation (per-slab overhead) but no external fragmentation, so
662b5fca8ftomee * it is of no interest to the consolidator. At the other extreme, slabs whose
663b5fca8ftomee * objects have all been freed to the slab are released to the virtual memory
664b5fca8ftomee * (VM) subsystem (objects freed to magazines are still allocated as far as the
665b5fca8ftomee * slab is concerned). External fragmentation exists when there are slabs
666b5fca8ftomee * somewhere between these extremes. A partial slab has at least one but not all
667b5fca8ftomee * of its objects allocated. The more partial slabs, and the fewer allocated
668b5fca8ftomee * objects on each of them, the higher the fragmentation. Hence the
669b5fca8ftomee * consolidator's overall strategy is to reduce the number of partial slabs by
670b5fca8ftomee * moving allocated objects from the least allocated slabs to the most allocated
671b5fca8ftomee * slabs.
672b5fca8ftomee *
673b5fca8ftomee * Partial slabs are kept in an AVL tree ordered by usage. Completely allocated
674b5fca8ftomee * slabs are kept separately in an unordered list. Since the majority of slabs
675b5fca8ftomee * tend to be completely allocated (a typical unfragmented cache may have
676b5fca8ftomee * thousands of complete slabs and only a single partial slab), separating
677b5fca8ftomee * complete slabs improves the efficiency of partial slab ordering, since the
678b5fca8ftomee * complete slabs do not affect the depth or balance of the AVL tree. This
679b5fca8ftomee * ordered sequence of partial slabs acts as a "free list" supplying objects for
680b5fca8ftomee * allocation requests.
681b5fca8ftomee *
682b5fca8ftomee * Objects are always allocated from the first partial slab in the free list,
683b5fca8ftomee * where the allocation is most likely to eliminate a partial slab (by
684b5fca8ftomee * completely allocating it). Conversely, when a single object from a completely
685b5fca8ftomee * allocated slab is freed to the slab, that slab is added to the front of the
686b5fca8ftomee * free list. Since most free list activity involves highly allocated slabs
687b5fca8ftomee * coming and going at the front of the list, slabs tend naturally toward the
688b5fca8ftomee * ideal order: highly allocated at the front, sparsely allocated at the back.
689b5fca8ftomee * Slabs with few allocated objects are likely to become completely free if they
690b5fca8ftomee * keep a safe distance away from the front of the free list. Slab misorders
691b5fca8ftomee * interfere with the natural tendency of slabs to become completely free or
692b5fca8ftomee * completely allocated. For example, a slab with a single allocated object
693b5fca8ftomee * needs only a single free to escape the cache; its natural desire is
694b5fca8ftomee * frustrated when it finds itself at the front of the list where a second
695b5fca8ftomee * allocation happens just before the free could have released it. Another slab
696b5fca8ftomee * with all but one object allocated might have supplied the buffer instead, so
697b5fca8ftomee * that both (as opposed to neither) of the slabs would have been taken off the
698b5fca8ftomee * free list.
699b5fca8ftomee *
700b5fca8ftomee * Although slabs tend naturally toward the ideal order, misorders allowed by a
701b5fca8ftomee * simple list implementation defeat the consolidator's strategy of merging
702b5fca8ftomee * least- and most-allocated slabs. Without an AVL tree to guarantee order, kmem
703b5fca8ftomee * needs another way to fix misorders to optimize its callback strategy. One
704b5fca8ftomee * approach is to periodically scan a limited number of slabs, advancing a
705b5fca8ftomee * marker to hold the current scan position, and to move extreme misorders to
706b5fca8ftomee * the front or back of the free list and to the front or back of the current
707b5fca8ftomee * scan range. By making consecutive scan ranges overlap by one slab, the least
708b5fca8ftomee * allocated slab in the current range can be carried along from the end of one
709b5fca8ftomee * scan to the start of the next.
710b5fca8ftomee *
711b5fca8ftomee * Maintaining partial slabs in an AVL tree relieves kmem of this additional
712b5fca8ftomee * task, however. Since most of the cache's activity is in the magazine layer,
713b5fca8ftomee * and allocations from the slab layer represent only a startup cost, the
714b5fca8ftomee * overhead of maintaining a balanced tree is not a significant concern compared
715b5fca8ftomee * to the opportunity of reducing complexity by eliminating the partial slab
716b5fca8ftomee * scanner just described. The overhead of an AVL tree is minimized by
717b5fca8ftomee * maintaining only partial slabs in the tree and keeping completely allocated
718b5fca8ftomee * slabs separately in a list. To avoid increasing the size of the slab
719b5fca8ftomee * structure the AVL linkage pointers are reused for the slab's list linkage,
720b5fca8ftomee * since the slab will always be either partial or complete, never stored both
721b5fca8ftomee * ways at the same time. To further minimize the overhead of the AVL tree the
722b5fca8ftomee * compare function that orders partial slabs by usage divides the range of
723b5fca8ftomee * allocated object counts into bins such that counts within the same bin are
724b5fca8ftomee * considered equal. Binning partial slabs makes it less likely that allocating
725b5fca8ftomee * or freeing a single object will change the slab's order, requiring a tree
726b5fca8ftomee * reinsertion (an avl_remove() followed by an avl_add(), both potentially
727b5fca8ftomee * requiring some rebalancing of the tree). Allocation counts closest to
728b5fca8ftomee * completely free and completely allocated are left unbinned (finely sorted) to
729b5fca8ftomee * better support the consolidator's strategy of merging slabs at either
730b5fca8ftomee * extreme.
731b5fca8ftomee *
732b5fca8ftomee * 3.1 Assessing Fragmentation and Selecting Candidate Slabs
733b5fca8ftomee *
734b5fca8ftomee * The consolidator piggybacks on the kmem maintenance thread and is called on
735b5fca8ftomee * the same interval as kmem_cache_update(), once per cache every fifteen
736b5fca8ftomee * seconds. kmem maintains a running count of unallocated objects in the slab
737b5fca8ftomee * layer (cache_bufslab). The consolidator checks whether that number exceeds
738b5fca8ftomee * 12.5% (1/8) of the total objects in the cache (cache_buftotal), and whether
739b5fca8ftomee * there is a significant number of slabs in the cache (arbitrarily a minimum
740b5fca8ftomee * 101 total slabs). Unused objects that have fallen out of the magazine layer's
741b5fca8ftomee * working set are included in the assessment, and magazines in the depot are
742b5fca8ftomee * reaped if those objects would lift cache_bufslab above the fragmentation
743b5fca8ftomee * threshold. Once the consolidator decides that a cache is fragmented, it looks
744b5fca8ftomee * for a candidate slab to reclaim, starting at the end of the partial slab free
745b5fca8ftomee * list and scanning backwards. At first the consolidator is choosy: only a slab
746b5fca8ftomee * with fewer than 12.5% (1/8) of its objects allocated qualifies (or else a
747b5fca8ftomee * single allocated object, regardless of percentage). If there is difficulty
748b5fca8ftomee * finding a candidate slab, kmem raises the allocation threshold incrementally,
749b5fca8ftomee * up to a maximum 87.5% (7/8), so that eventually the consolidator will reduce
750b5fca8ftomee * external fragmentation (unused objects on the free list) below 12.5% (1/8),
751b5fca8ftomee * even in the worst case of every slab in the cache being almost 7/8 allocated.
752b5fca8ftomee * The threshold can also be lowered incrementally when candidate slabs are easy
753b5fca8ftomee * to find, and the threshold is reset to the minimum 1/8 as soon as the cache
754b5fca8ftomee * is no longer fragmented.
755b5fca8ftomee *
756b5fca8ftomee * 3.2 Generating Callbacks
757b5fca8ftomee *
758b5fca8ftomee * Once an eligible slab is chosen, a callback is generated for every allocated
759b5fca8ftomee * object on the slab, in the hope that the client will move everything off the
760b5fca8ftomee * slab and make it reclaimable. Objects selected as move destinations are
761b5fca8ftomee * chosen from slabs at the front of the free list. Assuming slabs in the ideal
762b5fca8ftomee * order (most allocated at the front, least allocated at the back) and a
763b5fca8ftomee * cooperative client, the consolidator will succeed in removing slabs from both
764b5fca8ftomee * ends of the free list, completely allocating on the one hand and completely
765b5fca8ftomee * freeing on the other. Objects selected as move destinations are allocated in
766b5fca8ftomee * the kmem maintenance thread where move requests are enqueued. A separate
767b5fca8ftomee * callback thread removes pending callbacks from the queue and calls the
768b5fca8ftomee * client. The separate thread ensures that client code (the move function) does
769b5fca8ftomee * not interfere with internal kmem maintenance tasks. A map of pending
770b5fca8ftomee * callbacks keyed by object address (the object to be moved) is checked to
771b5fca8ftomee * ensure that duplicate callbacks are not generated for the same object.
772b5fca8ftomee * Allocating the move destination (the object to move to) prevents subsequent
773b5fca8ftomee * callbacks from selecting the same destination as an earlier pending callback.
774b5fca8ftomee *
775b5fca8ftomee * Move requests can also be generated by kmem_cache_reap() when the system is
776b5fca8ftomee * desperate for memory and by kmem_cache_move_notify(), called by the client to
777b5fca8ftomee * notify kmem that a move refused earlier with KMEM_CBRC_LATER is now possible.
778b5fca8ftomee * The map of pending callbacks is protected by the same lock that protects the
779b5fca8ftomee * slab layer.
780b5fca8ftomee *
781b5fca8ftomee * When the system is desperate for memory, kmem does not bother to determine
782b5fca8ftomee * whether or not the cache exceeds the fragmentation threshold, but tries to
783b5fca8ftomee * consolidate as many slabs as possible. Normally, the consolidator chews
784b5fca8ftomee * slowly, one sparsely allocated slab at a time during each maintenance
785b5fca8ftomee * interval that the cache is fragmented. When desperate, the consolidator
786b5fca8ftomee * starts at the last partial slab and enqueues callbacks for every allocated
787b5fca8ftomee * object on every partial slab, working backwards until it reaches the first
788b5fca8ftomee * partial slab. The first partial slab, meanwhile, advances in pace with the
789b5fca8ftomee * consolidator as allocations to supply move destinations for the enqueued
790b5fca8ftomee * callbacks use up the highly allocated slabs at the front of the free list.
791b5fca8ftomee * Ideally, the overgrown free list collapses like an accordion, starting at
792b5fca8ftomee * both ends and ending at the center with a single partial slab.
793b5fca8ftomee *
794b5fca8ftomee * 3.3 Client Responses
795b5fca8ftomee *
796b5fca8ftomee * When the client returns KMEM_CBRC_NO in response to the move callback, kmem
797b5fca8ftomee * marks the slab that supplied the stuck object non-reclaimable and moves it to
798b5fca8ftomee * front of the free list. The slab remains marked as long as it remains on the
799b5fca8ftomee * free list, and it appears more allocated to the partial slab compare function
800b5fca8ftomee * than any unmarked slab, no matter how many of its objects are allocated.
801b5fca8ftomee * Since even one immovable object ties up the entire slab, the goal is to
802b5fca8ftomee * completely allocate any slab that cannot be completely freed. kmem does not
803b5fca8ftomee * bother generating callbacks to move objects from a marked slab unless the
804b5fca8ftomee * system is desperate.
805b5fca8ftomee *
806b5fca8ftomee * When the client responds KMEM_CBRC_LATER, kmem increments a count for the
807b5fca8ftomee * slab. If the client responds LATER too many times, kmem disbelieves and
808b5fca8ftomee * treats the response as a NO. The count is cleared when the slab is taken off
809b5fca8ftomee * the partial slab list or when the client moves one of the slab's objects.
810b5fca8ftomee *
811b5fca8ftomee * 4. Observability
812b5fca8ftomee *
813b5fca8ftomee * A kmem cache's external fragmentation is best observed with 'mdb -k' using
814b5fca8ftomee * the ::kmem_slabs dcmd. For a complete description of the command, enter
815b5fca8ftomee * '::help kmem_slabs' at the mdb prompt.
8167c478bdstevel@tonic-gate */
8177c478bdstevel@tonic-gate
8187c478bdstevel@tonic-gate#include <sys/kmem_impl.h>
8197c478bdstevel@tonic-gate#include <sys/vmem_impl.h>
8207c478bdstevel@tonic-gate#include <sys/param.h>
8217c478bdstevel@tonic-gate#include <sys/sysmacros.h>
8227c478bdstevel@tonic-gate#include <sys/vm.h>
8237c478bdstevel@tonic-gate#include <sys/proc.h>
8247c478bdstevel@tonic-gate#include <sys/tuneable.h>
8257c478bdstevel@tonic-gate#include <sys/systm.h>
8267c478bdstevel@tonic-gate#include <sys/cmn_err.h>
8277c478bdstevel@tonic-gate#include <sys/debug.h>
828b5fca8ftomee#include <sys/sdt.h>
8297c478bdstevel@tonic-gate#include <sys/mutex.h>
8307c478bdstevel@tonic-gate#include <sys/bitmap.h>
8317c478bdstevel@tonic-gate#include <sys/atomic.h>
8327c478bdstevel@tonic-gate#include <sys/kobj.h>
8337c478bdstevel@tonic-gate#include <sys/disp.h>
8347c478bdstevel@tonic-gate#include <vm/seg_kmem.h>
8357c478bdstevel@tonic-gate#include <sys/log.h>
8367c478bdstevel@tonic-gate#include <sys/callb.h>
8377c478bdstevel@tonic-gate#include <sys/taskq.h>
8387c478bdstevel@tonic-gate#include <sys/modctl.h>
8397c478bdstevel@tonic-gate#include <sys/reboot.h>
8407c478bdstevel@tonic-gate#include <sys/id32.h>
8417c478bdstevel@tonic-gate#include <sys/zone.h>
842f4b3ec6dh#include <sys/netstack.h>
843b5fca8ftomee#ifdef	DEBUG
844b5fca8ftomee#include <sys/random.h>
845b5fca8ftomee#endif
8467c478bdstevel@tonic-gate
8477c478bdstevel@tonic-gateextern void streams_msg_init(void);
8487c478bdstevel@tonic-gateextern int segkp_fromheap;
8497c478bdstevel@tonic-gateextern void segkp_cache_free(void);
8506e00b11Peter Telfordextern int callout_init_done;
8517c478bdstevel@tonic-gate
8527c478bdstevel@tonic-gatestruct kmem_cache_kstat {
8537c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_size;
8547c478bdstevel@tonic-gate	kstat_named_t	kmc_align;
8557c478bdstevel@tonic-gate	kstat_named_t	kmc_chunk_size;
8567c478bdstevel@tonic-gate	kstat_named_t	kmc_slab_size;
8577c478bdstevel@tonic-gate	kstat_named_t	kmc_alloc;
8587c478bdstevel@tonic-gate	kstat_named_t	kmc_alloc_fail;
8597c478bdstevel@tonic-gate	kstat_named_t	kmc_free;
8607c478bdstevel@tonic-gate	kstat_named_t	kmc_depot_alloc;
8617c478bdstevel@tonic-gate	kstat_named_t	kmc_depot_free;
8627c478bdstevel@tonic-gate	kstat_named_t	kmc_depot_contention;
8637c478bdstevel@tonic-gate	kstat_named_t	kmc_slab_alloc;
8647c478bdstevel@tonic-gate	kstat_named_t	kmc_slab_free;
8657c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_constructed;
8667c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_avail;
8677c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_inuse;
8687c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_total;
8697c478bdstevel@tonic-gate	kstat_named_t	kmc_buf_max;
8707c478bdstevel@tonic-gate	kstat_named_t	kmc_slab_create;
8717c478bdstevel@tonic-gate	kstat_named_t	kmc_slab_destroy;
8727c478bdstevel@tonic-gate	kstat_named_t	kmc_vmem_source;
8737c478bdstevel@tonic-gate	kstat_named_t	kmc_hash_size;
8747c478bdstevel@tonic-gate	kstat_named_t	kmc_hash_lookup_depth;
8757c478bdstevel@tonic-gate	kstat_named_t	kmc_hash_rescale;
8767c478bdstevel@tonic-gate	kstat_named_t	kmc_full_magazines;
8777c478bdstevel@tonic-gate	kstat_named_t	kmc_empty_magazines;
8787c478bdstevel@tonic-gate	kstat_named_t	kmc_magazine_size;
879686031eTom Erickson	kstat_named_t	kmc_reap; /* number of kmem_cache_reap() calls */
880686031eTom Erickson	kstat_named_t	kmc_defrag; /* attempts to defrag all partial slabs */
881686031eTom Erickson	kstat_named_t	kmc_scan; /* attempts to defrag one partial slab */
882686031eTom Erickson	kstat_named_t	kmc_move_callbacks; /* sum of yes, no, later, dn, dk */
883b5fca8ftomee	kstat_named_t	kmc_move_yes;
884b5fca8ftomee	kstat_named_t	kmc_move_no;
885b5fca8ftomee	kstat_named_t	kmc_move_later;
886b5fca8ftomee	kstat_named_t	kmc_move_dont_need;
887686031eTom Erickson	kstat_named_t	kmc_move_dont_know; /* obj unrecognized by client ... */
888686031eTom Erickson	kstat_named_t	kmc_move_hunt_found; /* ... but found in mag layer */
889686031eTom Erickson	kstat_named_t	kmc_move_slabs_freed; /* slabs freed by consolidator */
890686031eTom Erickson	kstat_named_t	kmc_move_reclaimable; /* buffers, if consolidator ran */
8917c478bdstevel@tonic-gate} kmem_cache_kstat = {
8927c478bdstevel@tonic-gate	{ "buf_size",		KSTAT_DATA_UINT64 },
8937c478bdstevel@tonic-gate	{ "align",		KSTAT_DATA_UINT64 },
8947c478bdstevel@tonic-gate	{ "chunk_size",		KSTAT_DATA_UINT64 },
8957c478bdstevel@tonic-gate	{ "slab_size",		KSTAT_DATA_UINT64 },
8967c478bdstevel@tonic-gate	{ "alloc",		KSTAT_DATA_UINT64 },
8977c478bdstevel@tonic-gate	{ "alloc_fail",		KSTAT_DATA_UINT64 },
8987c478bdstevel@tonic-gate	{ "free",		KSTAT_DATA_UINT64 },
8997c478bdstevel@tonic-gate	{ "depot_alloc",	KSTAT_DATA_UINT64 },
9007c478bdstevel@tonic-gate	{ "depot_free",		KSTAT_DATA_UINT64 },
9017c478bdstevel@tonic-gate	{ "depot_contention",	KSTAT_DATA_UINT64 },
9027c478bdstevel@tonic-gate	{ "slab_alloc",		KSTAT_DATA_UINT64 },
9037c478bdstevel@tonic-gate	{ "slab_free",		KSTAT_DATA_UINT64 },
9047c478bdstevel@tonic-gate	{ "buf_constructed",	KSTAT_DATA_UINT64 },
9057c478bdstevel@tonic-gate	{ "buf_avail",		KSTAT_DATA_UINT64 },
9067c478bdstevel@tonic-gate	{ "buf_inuse",		KSTAT_DATA_UINT64 },
9077c478bdstevel@tonic-gate	{ "buf_total",		KSTAT_DATA_UINT64 },
9087c478bdstevel@tonic-gate	{ "buf_max",		KSTAT_DATA_UINT64 },
9097c478bdstevel@tonic-gate	{ "slab_create",	KSTAT_DATA_UINT64 },
9107c478bdstevel@tonic-gate	{ "slab_destroy",	KSTAT_DATA_UINT64 },
9117c478bdstevel@tonic-gate	{ "vmem_source",	KSTAT_DATA_UINT64 },
9127c478bdstevel@tonic-gate	{ "hash_size",		KSTAT_DATA_UINT64 },
9137c478bdstevel@tonic-gate	{ "hash_lookup_depth",	KSTAT_DATA_UINT64 },
9147c478bdstevel@tonic-gate	{ "hash_rescale",	KSTAT_DATA_UINT64 },
9157c478bdstevel@tonic-gate	{ "full_magazines",	KSTAT_DATA_UINT64 },
9167c478bdstevel@tonic-gate	{ "empty_magazines",	KSTAT_DATA_UINT64 },
9177c478bdstevel@tonic-gate	{ "magazine_size",	KSTAT_DATA_UINT64 },
918686031eTom Erickson	{ "reap",		KSTAT_DATA_UINT64 },
919686031eTom Erickson	{ "defrag",		KSTAT_DATA_UINT64 },
920686031eTom Erickson	{ "scan",		KSTAT_DATA_UINT64 },
921b5fca8ftomee	{ "move_callbacks",	KSTAT_DATA_UINT64 },
922b5fca8ftomee	{ "move_yes",		KSTAT_DATA_UINT64 },
923b5fca8ftomee	{ "move_no",		KSTAT_DATA_UINT64 },
924b5fca8ftomee	{ "move_later",		KSTAT_DATA_UINT64 },
925b5fca8ftomee	{ "move_dont_need",	KSTAT_DATA_UINT64 },
926b5fca8ftomee	{ "move_dont_know",	KSTAT_DATA_UINT64 },
927b5fca8ftomee	{ "move_hunt_found",	KSTAT_DATA_UINT64 },
928686031eTom Erickson	{ "move_slabs_freed",	KSTAT_DATA_UINT64 },
929686031eTom Erickson	{ "move_reclaimable",	KSTAT_DATA_UINT64 },
9307c478bdstevel@tonic-gate};
9317c478bdstevel@tonic-gate
9327c478bdstevel@tonic-gatestatic kmutex_t kmem_cache_kstat_lock;
9337c478bdstevel@tonic-gate
9347c478bdstevel@tonic-gate/*
9357c478bdstevel@tonic-gate * The default set of caches to back kmem_alloc().
9367c478bdstevel@tonic-gate * These sizes should be reevaluated periodically.
9377c478bdstevel@tonic-gate *
9387c478bdstevel@tonic-gate * We want allocations that are multiples of the coherency granularity
9397c478bdstevel@tonic-gate * (64 bytes) to be satisfied from a cache which is a multiple of 64
9407c478bdstevel@tonic-gate * bytes, so that it will be 64-byte aligned.  For all multiples of 64,
9417c478bdstevel@tonic-gate * the next kmem_cache_size greater than or equal to it must be a
9427c478bdstevel@tonic-gate * multiple of 64.
943dce01e3Jonathan W Adams *
944dce01e3Jonathan W Adams * We split the table into two sections:  size <= 4k and size > 4k.  This
945dce01e3Jonathan W Adams * saves a lot of space and cache footprint in our cache tables.
9467c478bdstevel@tonic-gate */
9477c478bdstevel@tonic-gatestatic const int kmem_alloc_sizes[] = {
9487c478bdstevel@tonic-gate	1 * 8,
9497c478bdstevel@tonic-gate	2 * 8,
9507c478bdstevel@tonic-gate	3 * 8,
9517c478bdstevel@tonic-gate	4 * 8,		5 * 8,		6 * 8,		7 * 8,
9527c478bdstevel@tonic-gate	4 * 16,		5 * 16,		6 * 16,		7 * 16,
9537c478bdstevel@tonic-gate	4 * 32,		5 * 32,		6 * 32,		7 * 32,
9547c478bdstevel@tonic-gate	4 * 64,		5 * 64,		6 * 64,		7 * 64,
9557c478bdstevel@tonic-gate	4 * 128,	5 * 128,	6 * 128,	7 * 128,
9567c478bdstevel@tonic-gate	P2ALIGN(8192 / 7, 64),
9577c478bdstevel@tonic-gate	P2ALIGN(8192 / 6, 64),
9587c478bdstevel@tonic-gate	P2ALIGN(8192 / 5, 64),
9597c478bdstevel@tonic-gate	P2ALIGN(8192 / 4, 64),
9607c478bdstevel@tonic-gate	P2ALIGN(8192 / 3, 64),
9617c478bdstevel@tonic-gate	P2ALIGN(8192 / 2, 64),
9627c478bdstevel@tonic-gate};
9637c478bdstevel@tonic-gate
964dce01e3Jonathan W Adamsstatic const int kmem_big_alloc_sizes[] = {
965dce01e3Jonathan W Adams	2 * 4096,	3 * 4096,
966dce01e3Jonathan W Adams	2 * 8192,	3 * 8192,
967dce01e3Jonathan W Adams	4 * 8192,	5 * 8192,	6 * 8192,	7 * 8192,
968dce01e3Jonathan W Adams	8 * 8192,	9 * 8192,	10 * 8192,	11 * 8192,
969dce01e3Jonathan W Adams	12 * 8192,	13 * 8192,	14 * 8192,	15 * 8192,
970dce01e3Jonathan W Adams	16 * 8192
971dce01e3Jonathan W Adams};
972dce01e3Jonathan W Adams
973dce01e3Jonathan W Adams#define	KMEM_MAXBUF		4096
974dce01e3Jonathan W Adams#define	KMEM_BIG_MAXBUF_32BIT	32768
975dce01e3Jonathan W Adams#define	KMEM_BIG_MAXBUF		131072
976dce01e3Jonathan W Adams
977dce01e3Jonathan W Adams#define	KMEM_BIG_MULTIPLE	4096	/* big_alloc_sizes must be a multiple */
978dce01e3Jonathan W Adams#define	KMEM_BIG_SHIFT		12	/* lg(KMEM_BIG_MULTIPLE) */
9797c478bdstevel@tonic-gate
9807c478bdstevel@tonic-gatestatic kmem_cache_t *kmem_alloc_table[KMEM_MAXBUF >> KMEM_ALIGN_SHIFT];
981dce01e3Jonathan W Adamsstatic kmem_cache_t *kmem_big_alloc_table[KMEM_BIG_MAXBUF >> KMEM_BIG_SHIFT];
982dce01e3Jonathan W Adams
983dce01e3Jonathan W Adams#define	KMEM_ALLOC_TABLE_MAX	(KMEM_MAXBUF >> KMEM_ALIGN_SHIFT)
984dce01e3Jonathan W Adamsstatic size_t kmem_big_alloc_table_max = 0;	/* # of filled elements */
9857c478bdstevel@tonic-gate
9867c478bdstevel@tonic-gatestatic kmem_magtype_t kmem_magtype[] = {
9877c478bdstevel@tonic-gate	{ 1,	8,	3200,	65536	},
9887c478bdstevel@tonic-gate	{ 3,	16,	256,	32768	},
9897c478bdstevel@tonic-gate	{ 7,	32,	64,	16384	},
9907c478bdstevel@tonic-gate	{ 15,	64,	0,	8192	},
9917c478bdstevel@tonic-gate	{ 31,	64,	0,	4096	},
9927c478bdstevel@tonic-gate	{ 47,	64,	0,	2048	},
9937c478bdstevel@tonic-gate	{ 63,	64,	0,	1024	},
9947c478bdstevel@tonic-gate	{ 95,	64,	0,	512	},
9957c478bdstevel@tonic-gate	{ 143,	64,	0,	0	},
9967c478bdstevel@tonic-gate};
9977c478bdstevel@tonic-gate
9987c478bdstevel@tonic-gatestatic uint32_t kmem_reaping;
9997c478bdstevel@tonic-gatestatic uint32_t kmem_reaping_idspace;
10007c478bdstevel@tonic-gate
10017c478bdstevel@tonic-gate/*
10027c478bdstevel@tonic-gate * kmem tunables
10037c478bdstevel@tonic-gate */
10047c478bdstevel@tonic-gateclock_t kmem_reap_interval;	/* cache reaping rate [15 * HZ ticks] */
10057c478bdstevel@tonic-gateint kmem_depot_contention = 3;	/* max failed tryenters per real interval */
10067c478bdstevel@tonic-gatepgcnt_t kmem_reapahead = 0;	/* start reaping N pages before pageout */
10077c478bdstevel@tonic-gateint kmem_panic = 1;		/* whether to panic on error */
10087c478bdstevel@tonic-gateint kmem_logging = 1;		/* kmem_log_enter() override */
10097c478bdstevel@tonic-gateuint32_t kmem_mtbf = 0;		/* mean time between failures [default: off] */
10107c478bdstevel@tonic-gatesize_t kmem_transaction_log_size; /* transaction log size [2% of memory] */
10117c478bdstevel@tonic-gatesize_t kmem_content_log_size;	/* content log size [2% of memory] */
10127c478bdstevel@tonic-gatesize_t kmem_failure_log_size;	/* failure log [4 pages per CPU] */
10137c478bdstevel@tonic-gatesize_t kmem_slab_log_size;	/* slab create log [4 pages per CPU] */
1014d158018Bryan Cantrillsize_t kmem_zerosized_log_size;	/* zero-sized log [4 pages per CPU] */
10157c478bdstevel@tonic-gatesize_t kmem_content_maxsave = 256; /* KMF_CONTENTS max bytes to log */
10167c478bdstevel@tonic-gatesize_t kmem_lite_minsize = 0;	/* minimum buffer size for KMF_LITE */
10177c478bdstevel@tonic-gatesize_t kmem_lite_maxalign = 1024; /* maximum buffer alignment for KMF_LITE */
10187c478bdstevel@tonic-gateint kmem_lite_pcs = 4;		/* number of PCs to store in KMF_LITE mode */
10197c478bdstevel@tonic-gatesize_t kmem_maxverify;		/* maximum bytes to inspect in debug routines */
10207c478bdstevel@tonic-gatesize_t kmem_minfirewall;	/* hardware-enforced redzone threshold */
10217c478bdstevel@tonic-gate
1022d158018Bryan Cantrill#ifdef DEBUG
1023d158018Bryan Cantrillint kmem_warn_zerosized = 1;	/* whether to warn on zero-sized KM_SLEEP */
1024d158018Bryan Cantrill#else
1025d158018Bryan Cantrillint kmem_warn_zerosized = 0;	/* whether to warn on zero-sized KM_SLEEP */
1026d158018Bryan Cantrill#endif
1027d158018Bryan Cantrill
1028d158018Bryan Cantrillint kmem_panic_zerosized = 0;	/* whether to panic on zero-sized KM_SLEEP */
1029d158018Bryan Cantrill
1030dce01e3Jonathan W Adams#ifdef _LP64
1031dce01e3Jonathan W Adamssize_t	kmem_max_cached = KMEM_BIG_MAXBUF;	/* maximum kmem_alloc cache */
1032dce01e3Jonathan W Adams#else
1033dce01e3Jonathan W Adamssize_t	kmem_max_cached = KMEM_BIG_MAXBUF_32BIT; /* maximum kmem_alloc cache */
1034dce01e3Jonathan W Adams#endif
1035dce01e3Jonathan W Adams
10367c478bdstevel@tonic-gate#ifdef DEBUG
10377c478bdstevel@tonic-gateint kmem_flags = KMF_AUDIT | KMF_DEADBEEF | KMF_REDZONE | KMF_CONTENTS;
10387c478bdstevel@tonic-gate#else
10397c478bdstevel@tonic-gateint kmem_flags = 0;
10407c478bdstevel@tonic-gate#endif
10417c478bdstevel@tonic-gateint kmem_ready;
10427c478bdstevel@tonic-gate
10437c478bdstevel@tonic-gatestatic kmem_cache_t	*kmem_slab_cache;
10447c478bdstevel@tonic-gatestatic kmem_cache_t	*kmem_bufctl_cache;
10457c478bdstevel@tonic-gatestatic kmem_cache_t	*kmem_bufctl_audit_cache;
10467c478bdstevel@tonic-gate
10477c478bdstevel@tonic-gatestatic kmutex_t		kmem_cache_lock;	/* inter-cache linkage only */
1048b5fca8ftomeestatic list_t		kmem_caches;
10497c478bdstevel@tonic-gate
10507c478bdstevel@tonic-gatestatic taskq_t		*kmem_taskq;
10517c478bdstevel@tonic-gatestatic kmutex_t		kmem_flags_lock;
10527c478bdstevel@tonic-gatestatic vmem_t		*kmem_metadata_arena;
10537c478bdstevel@tonic-gatestatic vmem_t		*kmem_msb_arena;	/* arena for metadata caches */
10547c478bdstevel@tonic-gatestatic vmem_t		*kmem_cache_arena;
10557c478bdstevel@tonic-gatestatic vmem_t		*kmem_hash_arena;
10567c478bdstevel@tonic-gatestatic vmem_t		*kmem_log_arena;
10577c478bdstevel@tonic-gatestatic vmem_t		*kmem_oversize_arena;
10587c478bdstevel@tonic-gatestatic vmem_t		*kmem_va_arena;
10597c478bdstevel@tonic-gatestatic vmem_t		*kmem_default_arena;
10607c478bdstevel@tonic-gatestatic vmem_t		*kmem_firewall_va_arena;
10617c478bdstevel@tonic-gatestatic vmem_t		*kmem_firewall_arena;
10627c478bdstevel@tonic-gate
1063d158018Bryan Cantrillstatic int		kmem_zerosized;		/* # of zero-sized allocs */
1064d158018Bryan Cantrill
1065b5fca8ftomee/*
1066b5fca8ftomee * kmem slab consolidator thresholds (tunables)
1067b5fca8ftomee */
1068686031eTom Ericksonsize_t kmem_frag_minslabs = 101;	/* minimum total slabs */
1069686031eTom Ericksonsize_t kmem_frag_numer = 1;		/* free buffers (numerator) */
1070686031eTom Ericksonsize_t kmem_frag_denom = KMEM_VOID_FRACTION; /* buffers (denominator) */
1071b5fca8ftomee/*
1072b5fca8ftomee * Maximum number of slabs from which to move buffers during a single
1073b5fca8ftomee * maintenance interval while the system is not low on memory.
1074b5fca8ftomee */
1075686031eTom Ericksonsize_t kmem_reclaim_max_slabs = 1;
1076b5fca8ftomee/*
1077b5fca8ftomee * Number of slabs to scan backwards from the end of the partial slab list
1078b5fca8ftomee * when searching for buffers to relocate.
1079b5fca8ftomee */
1080686031eTom Ericksonsize_t kmem_reclaim_scan_range = 12;
1081b5fca8ftomee
1082b5fca8ftomee/* consolidator knobs */
1083929d5b4Matthew Ahrensboolean_t kmem_move_noreap;
1084929d5b4Matthew Ahrensboolean_t kmem_move_blocked;
1085929d5b4Matthew Ahrensboolean_t kmem_move_fulltilt;
1086929d5b4Matthew Ahrensboolean_t kmem_move_any_partial;
1087b5fca8ftomee
1088b5fca8ftomee#ifdef	DEBUG
1089b5fca8ftomee/*
1090686031eTom Erickson * kmem consolidator debug tunables:
1091b5fca8ftomee * Ensure code coverage by occasionally running the consolidator even when the
1092b5fca8ftomee * caches are not fragmented (they may never be). These intervals are mean time
1093b5fca8ftomee * in cache maintenance intervals (kmem_cache_update).
1094b5fca8ftomee */
1095686031eTom Ericksonuint32_t kmem_mtb_move = 60;	/* defrag 1 slab (~15min) */
1096686031eTom Ericksonuint32_t kmem_mtb_reap = 1800;	/* defrag all slabs (~7.5hrs) */
1097b5fca8ftomee#endif	/* DEBUG */
1098b5fca8ftomee
1099b5fca8ftomeestatic kmem_cache_t	*kmem_defrag_cache;
1100b5fca8ftomeestatic kmem_cache_t	*kmem_move_cache;
1101b5fca8ftomeestatic taskq_t		*kmem_move_taskq;
1102b5fca8ftomee
1103b5fca8ftomeestatic void kmem_cache_scan(kmem_cache_t *);
1104b5fca8ftomeestatic void kmem_cache_defrag(kmem_cache_t *);
1105b942e89David Valinstatic void kmem_slab_prefill(kmem_cache_t *, kmem_slab_t *);
1106b5fca8ftomee
1107b5fca8ftomee
11087c478bdstevel@tonic-gatekmem_log_header_t	*kmem_transaction_log;
11097c478bdstevel@tonic-gatekmem_log_header_t	*kmem_content_log;
11107c478bdstevel@tonic-gatekmem_log_header_t	*kmem_failure_log;
11117c478bdstevel@tonic-gatekmem_log_header_t	*kmem_slab_log;
1112d158018Bryan Cantrillkmem_log_header_t	*kmem_zerosized_log;
11137c478bdstevel@tonic-gate
11147c478bdstevel@tonic-gatestatic int		kmem_lite_count; /* # of PCs in kmem_buftag_lite_t */
11157c478bdstevel@tonic-gate
11167c478bdstevel@tonic-gate#define	KMEM_BUFTAG_LITE_ENTER(bt, count, caller)			\
11177c478bdstevel@tonic-gate	if ((count) > 0) {						\
11187c478bdstevel@tonic-gate		pc_t *_s = ((kmem_buftag_lite_t *)(bt))->bt_history;	\
11197c478bdstevel@tonic-gate		pc_t *_e;						\
11207c478bdstevel@tonic-gate		/* memmove() the old entries down one notch */		\
11217c478bdstevel@tonic-gate		for (_e = &_s[(count) - 1]; _e > _s; _e--)		\
11227c478bdstevel@tonic-gate			*_e = *(_e - 1);				\
11237c478bdstevel@tonic-gate		*_s = (uintptr_t)(caller);				\
11247c478bdstevel@tonic-gate	}
11257c478bdstevel@tonic-gate
11267c478bdstevel@tonic-gate#define	KMERR_MODIFIED	0	/* buffer modified while on freelist */
11277c478bdstevel@tonic-gate#define	KMERR_REDZONE	1	/* redzone violation (write past end of buf) */
11287c478bdstevel@tonic-gate#define	KMERR_DUPFREE	2	/* freed a buffer twice */
11297c478bdstevel@tonic-gate#define	KMERR_BADADDR	3	/* freed a bad (unallocated) address */
11307c478bdstevel@tonic-gate#define	KMERR_BADBUFTAG	4	/* buftag corrupted */
11317c478bdstevel@tonic-gate#define	KMERR_BADBUFCTL	5	/* bufctl corrupted */
11327c478bdstevel@tonic-gate#define	KMERR_BADCACHE	6	/* freed a buffer to the wrong cache */
11337c478bdstevel@tonic-gate#define	KMERR_BADSIZE	7	/* alloc size != free size */
11347c478bdstevel@tonic-gate#define	KMERR_BADBASE	8	/* buffer base address wrong */
11357c478bdstevel@tonic-gate
11367c478bdstevel@tonic-gatestruct {
11377c478bdstevel@tonic-gate	hrtime_t	kmp_timestamp;	/* timestamp of panic */
11387c478bdstevel@tonic-gate	int		kmp_error;	/* type of kmem error */
11397c478bdstevel@tonic-gate	void		*kmp_buffer;	/* buffer that induced panic */
11407c478bdstevel@tonic-gate	void		*kmp_realbuf;	/* real start address for buffer */
11417c478bdstevel@tonic-gate	kmem_cache_t	*kmp_cache;	/* buffer's cache according to client */
11427c478bdstevel@tonic-gate	kmem_cache_t	*kmp_realcache;	/* actual cache containing buffer */
11437c478bdstevel@tonic-gate	kmem_slab_t	*kmp_slab;	/* slab accoring to kmem_findslab() */
11447c478bdstevel@tonic-gate	kmem_bufctl_t	*kmp_bufctl;	/* bufctl */
11457c478bdstevel@tonic-gate} kmem_panic_info;
11467c478bdstevel@tonic-gate
11477c478bdstevel@tonic-gate
11487c478bdstevel@tonic-gatestatic void
11497c478bdstevel@tonic-gatecopy_pattern(uint64_t pattern, void *buf_arg, size_t size)
11507c478bdstevel@tonic-gate{
11517c478bdstevel@tonic-gate	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
11527c478bdstevel@tonic-gate	uint64_t *buf = buf_arg;
11537c478bdstevel@tonic-gate
11547c478bdstevel@tonic-gate	while (buf < bufend)
11557c478bdstevel@tonic-gate		*buf++ = pattern;
11567c478bdstevel@tonic-gate}
11577c478bdstevel@tonic-gate
11587c478bdstevel@tonic-gatestatic void *
11597c478bdstevel@tonic-gateverify_pattern(uint64_t pattern, void *buf_arg, size_t size)
11607c478bdstevel@tonic-gate{
11617c478bdstevel@tonic-gate	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
11627c478bdstevel@tonic-gate	uint64_t *buf;
11637c478bdstevel@tonic-gate
11647c478bdstevel@tonic-gate	for (buf = buf_arg; buf < bufend; buf++)
11657c478bdstevel@tonic-gate		if (*buf != pattern)
11667c478bdstevel@tonic-gate			return (buf);
11677c478bdstevel@tonic-gate	return (NULL);
11687c478bdstevel@tonic-gate}
11697c478bdstevel@tonic-gate
11707c478bdstevel@tonic-gatestatic void *
11717c478bdstevel@tonic-gateverify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, size_t size)
11727c478bdstevel@tonic-gate{
11737c478bdstevel@tonic-gate	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
11747c478bdstevel@tonic-gate	uint64_t *buf;
11757c478bdstevel@tonic-gate
11767c478bdstevel@tonic-gate	for (buf = buf_arg; buf < bufend; buf++) {
11777c478bdstevel@tonic-gate		if (*buf != old) {
11787c478bdstevel@tonic-gate			copy_pattern(old, buf_arg,
11799f1b636tomee			    (char *)buf - (char *)buf_arg);
11807c478bdstevel@tonic-gate			return (buf);
11817c478bdstevel@tonic-gate		}
11827c478bdstevel@tonic-gate		*buf = new;
11837c478bdstevel@tonic-gate	}
11847c478bdstevel@tonic-gate
11857c478bdstevel@tonic-gate	return (NULL);
11867c478bdstevel@tonic-gate}
11877c478bdstevel@tonic-gate
11887c478bdstevel@tonic-gatestatic void
11897c478bdstevel@tonic-gatekmem_cache_applyall(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
11907c478bdstevel@tonic-gate{
11917c478bdstevel@tonic-gate	kmem_cache_t *cp;
11927c478bdstevel@tonic-gate
11937c478bdstevel@tonic-gate	mutex_enter(&kmem_cache_lock);
1194b5fca8ftomee	for (cp = list_head(&kmem_caches); cp != NULL;
1195b5fca8ftomee	    cp = list_next(&kmem_caches, cp))
11967c478bdstevel@tonic-gate		if (tq != NULL)
11977c478bdstevel@tonic-gate			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
11987c478bdstevel@tonic-gate			    tqflag);
11997c478bdstevel@tonic-gate		else
12007c478bdstevel@tonic-gate			func(cp);
12017c478bdstevel@tonic-gate	mutex_exit(&kmem_cache_lock);
12027c478bdstevel@tonic-gate}
12037c478bdstevel@tonic-gate
12047c478bdstevel@tonic-gatestatic void
12057c478bdstevel@tonic-gatekmem_cache_applyall_id(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
12067c478bdstevel@tonic-gate{
12077c478bdstevel@tonic-gate	kmem_cache_t *cp;
12087c478bdstevel@tonic-gate
12097c478bdstevel@tonic-gate	mutex_enter(&kmem_cache_lock);
1210b5fca8ftomee	for (cp = list_head(&kmem_caches); cp != NULL;
1211b5fca8ftomee	    cp = list_next(&kmem_caches, cp)) {
12127c478bdstevel@tonic-gate		if (!(cp->cache_cflags & KMC_IDENTIFIER))
12137c478bdstevel@tonic-gate			continue;
12147c478bdstevel@tonic-gate		if (tq != NULL)
12157c478bdstevel@tonic-gate			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
12167c478bdstevel@tonic-gate			    tqflag);
12177c478bdstevel@tonic-gate		else
12187c478bdstevel@tonic-gate			func(cp);
12197c478bdstevel@tonic-gate	}
12207c478bdstevel@tonic-gate	mutex_exit(&kmem_cache_lock);
12217c478bdstevel@tonic-gate}
12227c478bdstevel@tonic-gate
12237c478bdstevel@tonic-gate/*
12247c478bdstevel@tonic-gate * Debugging support.  Given a buffer address, find its slab.
12257c478bdstevel@tonic-gate */
12267c478bdstevel@tonic-gatestatic kmem_slab_t *
12277c478bdstevel@tonic-gatekmem_findslab(kmem_cache_t *cp, void *buf)
12287c478bdstevel@tonic-gate{
12297c478bdstevel@tonic-gate	kmem_slab_t *sp;
12307c478bdstevel@tonic-gate
12317c478bdstevel@tonic-gate	mutex_enter(&cp->cache_lock);
1232b5fca8ftomee	for (sp = list_head(&cp->cache_complete_slabs); sp != NULL;
1233b5fca8ftomee	    sp = list_next(&cp->cache_complete_slabs, sp)) {
1234b5fca8ftomee		if (KMEM_SLAB_MEMBER(sp, buf)) {
1235b5fca8ftomee			mutex_exit(&cp->cache_lock);
1236b5fca8ftomee			return (sp);
1237b5fca8ftomee		}
1238b5fca8ftomee	}
1239b5fca8ftomee	for (sp = avl_first(&cp->cache_partial_slabs); sp != NULL;
1240b5fca8ftomee	    sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) {
12417c478bdstevel@tonic-gate		if (KMEM_SLAB_MEMBER(sp, buf)) {
12427c478bdstevel@tonic-gate			mutex_exit(&cp->cache_lock);
12437c478bdstevel@tonic-gate			return (sp);
12447c478bdstevel@tonic-gate		}
12457c478bdstevel@tonic-gate	}
12467c478bdstevel@tonic-gate	mutex_exit(&cp->cache_lock);
12477c478bdstevel@tonic-gate
12487c478bdstevel@tonic-gate	return (NULL);
12497c478bdstevel@tonic-gate}
12507c478bdstevel@tonic-gate
12517c478bdstevel@tonic-gatestatic void
12527c478bdstevel@tonic-gatekmem_error(int error, kmem_cache_t *cparg, void *bufarg)
12537c478bdstevel@tonic-gate{
12547c478bdstevel@tonic-gate	kmem_buftag_t *btp = NULL;
12557c478bdstevel@tonic-gate	kmem_bufctl_t *bcp = NULL;
12567c478bdstevel@tonic-gate	kmem_cache_t *cp = cparg;
12577c478bdstevel@tonic-gate	kmem_slab_t *sp;
12587c478bdstevel@tonic-gate	uint64_t *off;
12597c478bdstevel@tonic-gate	void *buf = bufarg;
12607c478bdstevel@tonic-gate
12617c478bdstevel@tonic-gate	kmem_logging = 0;	/* stop logging when a bad thing happens */
12627c478bdstevel@tonic-gate
12637c478bdstevel@tonic-gate	kmem_panic_info.kmp_timestamp = gethrtime();
12647c478bdstevel@tonic-gate
12657c478bdstevel@tonic-gate	sp = kmem_findslab(cp, buf);
12667c478bdstevel@tonic-gate	if (sp == NULL) {
1267b5fca8ftomee		for (cp = list_tail(&kmem_caches); cp != NULL;
1268b5fca8ftomee		    cp = list_prev(&kmem_caches, cp)) {
12697c478bdstevel@tonic-gate			if ((sp = kmem_findslab(cp, buf)) != NULL)
12707c478bdstevel@tonic-gate				break;
12717c478bdstevel@tonic-gate		}
12727c478bdstevel@tonic-gate	}
12737c478bdstevel@tonic-gate
12747c478bdstevel@tonic-gate	if (sp == NULL) {
12757c478bdstevel@tonic-gate		cp = NULL;
12767c478bdstevel@tonic-gate		error = KMERR_BADADDR;
12777c478bdstevel@tonic-gate	} else {
12787c478bdstevel@tonic-gate		if (cp != cparg)
12797c478bdstevel@tonic-gate			error = KMERR_BADCACHE;
12807c478bdstevel@tonic-gate		else
12817c478bdstevel@tonic-gate			buf = (char *)bufarg - ((uintptr_t)bufarg -
12827c478bdstevel@tonic-gate			    (uintptr_t)sp->slab_base) % cp->cache_chunksize;
12837c478bdstevel@tonic-gate		if (buf != bufarg)
12847c478bdstevel@tonic-gate			error = KMERR_BADBASE;
12857c478bdstevel@tonic-gate		if (cp->cache_flags & KMF_BUFTAG)
12867c478bdstevel@tonic-gate			btp = KMEM_BUFTAG(cp, buf);
12877c478bdstevel@tonic-gate		if (cp->cache_flags & KMF_HASH) {
12887c478bdstevel@tonic-gate			mutex_enter(&cp->cache_lock);
12897c478bdstevel@tonic-gate			for (bcp = *KMEM_HASH(cp, buf); bcp; bcp = bcp->bc_next)
12907c478bdstevel@tonic-gate				if (bcp->bc_addr == buf)
12917c478bdstevel@tonic-gate					break;
12927c478bdstevel@tonic-gate			mutex_exit(&cp->cache_lock);
12937c478bdstevel@tonic-gate			if (bcp == NULL && btp != NULL)
12947c478bdstevel@tonic-gate				bcp = btp->bt_bufctl;
12957c478bdstevel@tonic-gate			if (kmem_findslab(cp->cache_bufctl_cache, bcp) ==
12967c478bdstevel@tonic-gate			    NULL || P2PHASE((uintptr_t)bcp, KMEM_ALIGN) ||
12977c478bdstevel@tonic-gate			    bcp->bc_addr != buf) {
12987c478bdstevel@tonic-gate				error = KMERR_BADBUFCTL;
12997c478bdstevel@tonic-gate				bcp = NULL;
13007c478bdstevel@tonic-gate			}
13017c478bdstevel@tonic-gate		}
13027c478bdstevel@tonic-gate	}
13037c478bdstevel@tonic-gate
13047c478bdstevel@tonic-gate	kmem_panic_info.kmp_error = error;
13057c478bdstevel@tonic-gate	kmem_panic_info.kmp_buffer = bufarg;
13067c478bdstevel@tonic-gate	kmem_panic_info.kmp_realbuf = buf;
13077c478bdstevel@tonic-gate	kmem_panic_info.kmp_cache = cparg;
13087c478bdstevel@tonic-gate	kmem_panic_info.kmp_realcache = cp;
13097c478bdstevel@tonic-gate	kmem_panic_info.kmp_slab = sp;
13107c478bdstevel@tonic-gate	kmem_panic_info.kmp_bufctl = bcp;
13117c478bdstevel@tonic-gate
13127c478bdstevel@tonic-gate	printf("kernel memory allocator: ");
13137c478bdstevel@tonic-gate
13147c478bdstevel@tonic-gate	switch (error) {
13157c478bdstevel@tonic-gate
13167c478bdstevel@tonic-gate	case KMERR_MODIFIED:
13177c478bdstevel@tonic-gate		printf("buffer modified after being freed\n");
13187c478bdstevel@tonic-gate		off = verify_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
13197c478bdstevel@tonic-gate		if (off == NULL)	/* shouldn't happen */
13207c478bdstevel@tonic-gate			off = buf;
13217c478bdstevel@tonic-gate		printf("modification occurred at offset 0x%lx "
13227c478bdstevel@tonic-gate		    "(0x%llx replaced by 0x%llx)\n",
13237c478bdstevel@tonic-gate		    (uintptr_t)off - (uintptr_t)buf,
13247c478bdstevel@tonic-gate		    (longlong_t)KMEM_FREE_PATTERN, (longlong_t)*off);
13257c478bdstevel@tonic-gate		break;
13267c478bdstevel@tonic-gate
13277c478bdstevel@tonic-gate	case KMERR_REDZONE:
13287c478bdstevel@tonic-gate		printf("redzone violation: write past end of buffer\n");
13297c478bdstevel@tonic-gate		break;
13307c478bdstevel@tonic-gate
13317c478bdstevel@tonic-gate	case KMERR_BADADDR:
13327c478bdstevel@tonic-gate		printf("invalid free: buffer not in cache\n");
13337c478bdstevel@tonic-gate		break;
13347c478bdstevel@tonic-gate
13357c478bdstevel@tonic-gate	case KMERR_DUPFREE:
13367c478bdstevel@tonic-gate		printf("duplicate free: buffer freed twice\n");
13377c478bdstevel@tonic-gate		break;
13387c478bdstevel@tonic-gate
13397c478bdstevel@tonic-gate	case KMERR_BADBUFTAG:
13407c478bdstevel@tonic-gate		printf("boundary tag corrupted\n");
13417c478bdstevel@tonic-gate		printf("bcp ^ bxstat = %lx, should be %lx\n",
13427c478bdstevel@tonic-gate		    (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat,
13437c478bdstevel@tonic-gate		    KMEM_BUFTAG_FREE);
13447c478bdstevel@tonic-gate		break;
13457c478bdstevel@tonic-gate
13467c478bdstevel@tonic-gate	case KMERR_BADBUFCTL:
13477c478bdstevel@tonic-gate		printf("bufctl corrupted\n");
13487c478bdstevel@tonic-gate		break;
13497c478bdstevel@tonic-gate
13507c478bdstevel@tonic-gate	case KMERR_BADCACHE:
13517c478bdstevel@tonic-gate		printf("buffer freed to wrong cache\n");
13527c478bdstevel@tonic-gate		printf("buffer was allocated from %s,\n", cp->cache_name);
13537c478bdstevel@tonic-gate		printf("caller attempting free to %s.\n", cparg->cache_name);
13547c478bdstevel@tonic-gate		break;
13557c478bdstevel@tonic-gate
13567c478bdstevel@tonic-gate	case KMERR_BADSIZE:
13577c478bdstevel@tonic-gate		printf("bad free: free size (%u) != alloc size (%u)\n",
13587c478bdstevel@tonic-gate		    KMEM_SIZE_DECODE(((uint32_t *)btp)[0]),
13597c478bdstevel@tonic-gate		    KMEM_SIZE_DECODE(((uint32_t *)btp)[1]));
13607c478bdstevel@tonic-gate		break;
13617c478bdstevel@tonic-gate
13627c478bdstevel@tonic-gate	case KMERR_BADBASE:
13637c478bdstevel@tonic-gate		printf("bad free: free address (%p) != alloc address (%p)\n",
13647c478bdstevel@tonic-gate		    bufarg, buf);
13657c478bdstevel@tonic-gate		break;
13667c478bdstevel@tonic-gate	}
13677c478bdstevel@tonic-gate
13687c478bdstevel@tonic-gate	printf("buffer=%p  bufctl=%p  cache: %s\n",
13697c478bdstevel@tonic-gate	    bufarg, (void *)bcp, cparg->cache_name);
13707c478bdstevel@tonic-gate
13717c478bdstevel@tonic-gate	if (bcp != NULL && (cp->cache_flags & KMF_AUDIT) &&
13727c478bdstevel@tonic-gate	    error != KMERR_BADBUFCTL) {
13737c478bdstevel@tonic-gate		int d;
13747c478bdstevel@tonic-gate		timestruc_t ts;
13757c478bdstevel@tonic-gate		kmem_bufctl_audit_t *bcap = (kmem_bufctl_audit_t *)bcp;
13767c478bdstevel@tonic-gate
13777c478bdstevel@tonic-gate		hrt2ts(kmem_panic_info.kmp_timestamp - bcap->bc_timestamp, &ts);
13787c478bdstevel@tonic-gate		printf("previous transaction on buffer %p:\n", buf);
13797c478bdstevel@tonic-gate		printf("thread=%p  time=T-%ld.%09ld  slab=%p  cache: %s\n",
13807c478bdstevel@tonic-gate		    (void *)bcap->bc_thread, ts.tv_sec, ts.tv_nsec,
13817c478bdstevel@tonic-gate		    (void *)sp, cp->cache_name);
13827c478bdstevel@tonic-gate		for (d = 0; d < MIN(bcap->bc_depth, KMEM_STACK_DEPTH); d++) {
13837c478bdstevel@tonic-gate			ulong_t off;
13847c478bdstevel@tonic-gate			char *sym = kobj_getsymname(bcap->bc_stack[d], &off);
13857c478bdstevel@tonic-gate			printf("%s+%lx\n", sym ? sym : "?", off);
13867c478bdstevel@tonic-gate		}
13877c478bdstevel@tonic-gate	}
13887c478bdstevel@tonic-gate	if (kmem_panic > 0)
13897c478bdstevel@tonic-gate		panic("kernel heap corruption detected");
13907c478bdstevel@tonic-gate	if (kmem_panic == 0)
13917c478bdstevel@tonic-gate		debug_enter(NULL);
13927c478bdstevel@tonic-gate	kmem_logging = 1;	/* resume logging */
13937c478bdstevel@tonic-gate}
13947c478bdstevel@tonic-gate
13957c478bdstevel@tonic-gatestatic kmem_log_header_t *
13967c478bdstevel@tonic-gatekmem_log_init(size_t logsize)
13977c478bdstevel@tonic-gate{
13987c478bdstevel@tonic-gate	kmem_log_header_t *lhp;
13997c478bdstevel@tonic-gate	int nchunks = 4 * max_ncpus;
14007c478bdstevel@tonic-gate	size_t lhsize = (size_t)&((kmem_log_header_t *)0)->lh_cpu[max_ncpus];
14017c478bdstevel@tonic-gate	int i;
14027c478bdstevel@tonic-gate
14037c478bdstevel@tonic-gate	/*
14047c478bdstevel@tonic-gate	 * Make sure that lhp->lh_cpu[] is nicely aligned
14057c478bdstevel@tonic-gate	 * to prevent false sharing of cache lines.
14067c478bdstevel@tonic-gate	 */
14077c478bdstevel@tonic-gate	lhsize = P2ROUNDUP(lhsize, KMEM_ALIGN);
14087c478bdstevel@tonic-gate	lhp = vmem_xalloc(kmem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0,
14097c478bdstevel@tonic-gate	    NULL, NULL, VM_SLEEP);
14107c478bdstevel@tonic-gate	bzero(lhp, lhsize);
14117c478bdstevel@tonic-gate
14127c478bdstevel@tonic-gate	mutex_init(&lhp->lh_lock, NULL, MUTEX_DEFAULT, NULL);
14137c478bdstevel@tonic-gate	lhp->lh_nchunks = nchunks;
14147c478bdstevel@tonic-gate	lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks + 1, PAGESIZE);
14157c478bdstevel@tonic-gate	lhp->lh_base = vmem_alloc(kmem_log_arena,
14167c478bdstevel@tonic-gate	    lhp->lh_chunksize * nchunks, VM_SLEEP);
14177c478bdstevel@tonic-gate	lhp->lh_free = vmem_alloc(kmem_log_arena,
14187c478bdstevel@tonic-gate	    nchunks * sizeof (int), VM_SLEEP);
14197c478bdstevel@tonic-gate	bzero(lhp->lh_base, lhp->lh_chunksize * nchunks);
14207c478bdstevel@tonic-gate
14217c478bdstevel@tonic-gate	for (i = 0; i < max_ncpus; i++) {
14227c478bdstevel@tonic-gate		kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[i];
14237c478bdstevel@tonic-gate		mutex_init(&clhp->clh_lock, NULL, MUTEX_DEFAULT, NULL);
14247c478bdstevel@tonic-gate		clhp->clh_chunk = i;
14257c478bdstevel@tonic-gate	}
14267c478bdstevel@tonic-gate
14277c478bdstevel@tonic-gate	for (i = max_ncpus; i < nchunks; i++)
14287c478bdstevel@tonic-gate		lhp->lh_free[i] = i;
14297c478bdstevel@tonic-gate
14307c478bdstevel@tonic-gate	lhp->lh_head = max_ncpus;
14317c478bdstevel@tonic-gate	lhp->lh_tail = 0;
14327c478bdstevel@tonic-gate
14337c478bdstevel@tonic-gate	return (lhp);
14347c478bdstevel@tonic-gate}
14357c478bdstevel@tonic-gate
14367c478bdstevel@tonic-gatestatic void *
14377c478bdstevel@tonic-gatekmem_log_enter(kmem_log_header_t *lhp, void *data, size_t size)
14387c478bdstevel@tonic-gate{
14397c478bdstevel@tonic-gate	void *logspace;
1440066570eJohn Levon	kmem_cpu_log_header_t *clhp;
14417c478bdstevel@tonic-gate
14427c478bdstevel@tonic-gate	if (lhp == NULL || kmem_logging == 0 || panicstr)
14437c478bdstevel@tonic-gate		return (NULL);
14447c478bdstevel@tonic-gate
1445066570eJohn Levon	clhp = &lhp->lh_cpu[CPU->cpu_seqid];
1446066570eJohn Levon
14477c478bdstevel@tonic-gate	mutex_enter(&clhp->clh_lock);
14487c478bdstevel@tonic-gate	clhp->clh_hits++;
14497c478bdstevel@tonic-gate	if (size > clhp->clh_avail) {
14507c478bdstevel@tonic-gate		mutex_enter(&lhp->lh_lock);
14517c478bdstevel@tonic-gate		lhp->lh_hits++;
14527c478bdstevel@tonic-gate		lhp->lh_free[lhp->lh_tail] = clhp->clh_chunk;
14537c478bdstevel@tonic-gate		lhp->lh_tail = (lhp->lh_tail + 1) % lhp->lh_nchunks;
14547c478bdstevel@tonic-gate		clhp->clh_chunk = lhp->lh_free[lhp->lh_head];
14557c478bdstevel@tonic-gate		lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks;
14567c478bdstevel@tonic-gate		clhp->clh_current = lhp->lh_base +
14579f1b636tomee		    clhp->clh_chunk * lhp->lh_chunksize;
14587c478bdstevel@tonic-gate		clhp->clh_avail = lhp->lh_chunksize;
14597c478bdstevel@tonic-gate		if (size > lhp->lh_chunksize)
14607c478bdstevel@tonic-gate			size = lhp->lh_chunksize;
14617c478bdstevel@tonic-gate		mutex_exit(&lhp->lh_lock);
14627c478bdstevel@tonic-gate	}
14637c478bdstevel@tonic-gate	logspace = clhp->clh_current;
14647c478bdstevel@tonic-gate	clhp->clh_current += size;
14657c478bdstevel@tonic-gate	clhp->clh_avail -= size;
14667c478bdstevel@tonic-gate	bcopy(data, logspace, size);
14677c478bdstevel@tonic-gate	mutex_exit(&clhp->clh_lock);
14687c478bdstevel@tonic-gate	return (logspace);
14697c478bdstevel@tonic-gate}
14707c478bdstevel@tonic-gate
14717c478bdstevel@tonic-gate#define	KMEM_AUDIT(lp, cp, bcp)						\
14727c478bdstevel@tonic-gate{									\
14737c478bdstevel@tonic-gate	kmem_bufctl_audit_t *_bcp = (kmem_bufctl_audit_t *)(bcp);	\
14747c478bdstevel@tonic-gate	_bcp->bc_timestamp = gethrtime();				\
14757c478bdstevel@tonic-gate	_bcp->bc_thread = curthread;					\
14767c478bdstevel@tonic-gate	_bcp->bc_depth = getpcstack(_bcp->bc_stack, KMEM_STACK_DEPTH);	\
14777c478bdstevel@tonic-gate	_bcp->bc_lastlog = kmem_log_enter((lp), _bcp, sizeof (*_bcp));	\
14787c478bdstevel@tonic-gate}
14797c478bdstevel@tonic-gate
14807c478bdstevel@tonic-gatestatic void
14817c478bdstevel@tonic-gatekmem_log_event(kmem_log_header_t *lp, kmem_cache_t *cp,
14821c207aeMatthew Ahrens    kmem_slab_t *sp, void *addr)
14837c478bdstevel@tonic-gate{
14847c478bdstevel@tonic-gate	kmem_bufctl_audit_t bca;
14857c478bdstevel@tonic-gate
14867c478bdstevel@tonic-gate	bzero(&bca, sizeof (kmem_bufctl_audit_t));
14877c478bdstevel@tonic-gate	bca.bc_addr = addr;
14887c478bdstevel@tonic-gate	bca.bc_slab = sp;
14897c478bdstevel@tonic-gate	bca.bc_cache = cp;
14907c478bdstevel@tonic-gate	KMEM_AUDIT(lp, cp, &bca);
14917c478bdstevel@tonic-gate}
14927c478bdstevel@tonic-gate
14937c478bdstevel@tonic-gate/*
14947c478bdstevel@tonic-gate * Create a new slab for cache cp.
14957c478bdstevel@tonic-gate */
14967c478bdstevel@tonic-gatestatic kmem_slab_t *
14977c478bdstevel@tonic-gatekmem_slab_create(kmem_cache_t *cp, int kmflag)
14987c478bdstevel@tonic-gate{
14997c478bdstevel@tonic-gate	size_t slabsize = cp->cache_slabsize;
15007c478bdstevel@tonic-gate	size_t chunksize = cp->cache_chunksize;
15017c478bdstevel@tonic-gate	int cache_flags = cp->cache_flags;
15027c478bdstevel@tonic-gate	size_t color, chunks;
15037c478bdstevel@tonic-gate	char *buf, *slab;
15047c478bdstevel@tonic-gate	kmem_slab_t *sp;
15057c478bdstevel@tonic-gate	kmem_bufctl_t *bcp;
15067c478bdstevel@tonic-gate	vmem_t *vmp = cp->cache_arena;
15077c478bdstevel@tonic-gate
1508b5fca8ftomee	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
1509b5fca8ftomee
15107c478bdstevel@tonic-gate	color = cp->cache_color + cp->cache_align;
15117c478bdstevel@tonic-gate	if (color > cp->cache_maxcolor)
15127c478bdstevel@tonic-gate		color = cp->cache_mincolor;
15137c478bdstevel@tonic-gate	cp->cache_color = color;
15147c478bdstevel@tonic-gate
15157c478bdstevel@tonic-gate	slab = vmem_alloc(vmp, slabsize, kmflag & KM_VMFLAGS);
15167c478bdstevel@tonic-gate
15177c478bdstevel@tonic-gate	if (slab == NULL)
15187c478bdstevel@tonic-gate		goto vmem_alloc_failure;
15197c478bdstevel@tonic-gate
15207c478bdstevel@tonic-gate	ASSERT(P2PHASE((uintptr_t)slab, vmp->vm_quantum) == 0);
15217c478bdstevel@tonic-gate
1522b5fca8ftomee	/*
1523b5fca8ftomee	 * Reverify what was already checked in kmem_cache_set_move(), since the
1524b5fca8ftomee	 * consolidator depends (for correctness) on slabs being initialized
1525b5fca8ftomee	 * with the 0xbaddcafe memory pattern (setting a low order bit usable by
1526b5fca8ftomee	 * clients to distinguish uninitialized memory from known objects).
1527b5fca8ftomee	 */
1528b5fca8ftomee	ASSERT((cp->cache_move == NULL) || !(cp->cache_cflags & KMC_NOTOUCH));
15297c478bdstevel@tonic-gate	if (!(cp->cache_cflags & KMC_NOTOUCH))
15307c478bdstevel@tonic-gate		copy_pattern(KMEM_UNINITIALIZED_PATTERN, slab, slabsize);
15317c478bdstevel@tonic-gate
15327c478bdstevel@tonic-gate	if (cache_flags & KMF_HASH) {
15337c478bdstevel@tonic-gate		if ((sp = kmem_cache_alloc(kmem_slab_cache, kmflag)) == NULL)
15347c478bdstevel@tonic-gate			goto slab_alloc_failure;
15357c478bdstevel@tonic-gate		chunks = (slabsize - color) / chunksize;
15367c478bdstevel@tonic-gate	} else {
15377c478bdstevel@tonic-gate		sp = KMEM_SLAB(cp, slab);
15387c478bdstevel@tonic-gate		chunks = (slabsize - sizeof (kmem_slab_t) - color) / chunksize;
15397c478bdstevel@tonic-gate	}
15407c478bdstevel@tonic-gate
15417c478bdstevel@tonic-gate	sp->slab_cache	= cp;
15427c478bdstevel@tonic-gate	sp->slab_head	= NULL;
15437c478bdstevel@tonic-gate	sp->slab_refcnt	= 0;
15447c478bdstevel@tonic-gate	sp->slab_base	= buf = slab + color;
15457c478bdstevel@tonic-gate	sp->slab_chunks	= chunks;
1546b5fca8ftomee	sp->slab_stuck_offset = (uint32_t)-1;
1547b5fca8ftomee	sp->slab_later_count = 0;
1548b5fca8ftomee	sp->slab_flags = 0;
15497c478bdstevel@tonic-gate
15507c478bdstevel@tonic-gate	ASSERT(chunks > 0);
15517c478bdstevel@tonic-gate	while (chunks-- != 0) {
15527c478bdstevel@tonic-gate		if (cache_flags & KMF_HASH) {
15537c478bdstevel@tonic-gate			bcp = kmem_cache_alloc(cp->cache_bufctl_cache, kmflag);
15547c478bdstevel@tonic-gate			if (bcp == NULL)
15557c478bdstevel@tonic-gate				goto bufctl_alloc_failure;
15567c478bdstevel@tonic-gate			if (cache_flags & KMF_AUDIT) {
15577c478bdstevel@tonic-gate				kmem_bufctl_audit_t *bcap =
15587c478bdstevel@tonic-gate				    (kmem_bufctl_audit_t *)bcp;
15597c478bdstevel@tonic-gate				bzero(bcap, sizeof (kmem_bufctl_audit_t));
15607c478bdstevel@tonic-gate				bcap->bc_cache = cp;
15617c478bdstevel@tonic-gate			}
15627c478bdstevel@tonic-gate			bcp->bc_addr = buf;
15637c478bdstevel@tonic-gate			bcp->bc_slab = sp;
15647c478bdstevel@tonic-gate		} else {
15657c478bdstevel@tonic-gate			bcp = KMEM_BUFCTL(cp, buf);
15667c478bdstevel@tonic-gate		}
15677c478bdstevel@tonic-gate		if (cache_flags & KMF_BUFTAG) {
15687c478bdstevel@tonic-gate			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
15697c478bdstevel@tonic-gate			btp->bt_redzone = KMEM_REDZONE_PATTERN;
15707c478bdstevel@tonic-gate			btp->bt_bufctl = bcp;
15717c478bdstevel@tonic-gate			btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
15727c478bdstevel@tonic-gate			if (cache_flags & KMF_DEADBEEF) {
15737c478bdstevel@tonic-gate				copy_pattern(KMEM_FREE_PATTERN, buf,
15747c478bdstevel@tonic-gate				    cp->cache_verify);
15757c478bdstevel@tonic-gate			}
15767c478bdstevel@tonic-gate		}
15777c478bdstevel@tonic-gate		bcp->bc_next = sp->slab_head;
15787c478bdstevel@tonic-gate		sp->slab_head = bcp;
15797c478bdstevel@tonic-gate		buf += chunksize;
15807c478bdstevel@tonic-gate	}
15817c478bdstevel@tonic-gate
15827c478bdstevel@tonic-gate	kmem_log_event(kmem_slab_log, cp, sp, slab);
15837c478bdstevel@tonic-gate
15847c478bdstevel@tonic-gate	return (sp);
15857c478bdstevel@tonic-gate
15867c478bdstevel@tonic-gatebufctl_alloc_failure:
15877c478bdstevel@tonic-gate
15887c478bdstevel@tonic-gate	while ((bcp = sp->slab_head) != NULL) {
15897c478bdstevel@tonic-gate		sp->slab_head = bcp->bc_next;
15907c478bdstevel@tonic-gate		kmem_cache_free(cp->cache_bufctl_cache, bcp);
15917c478bdstevel@tonic-gate	}
15927c478bdstevel@tonic-gate	kmem_cache_free(kmem_slab_cache, sp);
15937c478bdstevel@tonic-gate
15947c478bdstevel@tonic-gateslab_alloc_failure:
15957c478bdstevel@tonic-gate
15967c478bdstevel@tonic-gate	vmem_free(vmp, slab, slabsize);
15977c478bdstevel@tonic-gate
15987c478bdstevel@tonic-gatevmem_alloc_failure:
15997c478bdstevel@tonic-gate
16007c478bdstevel@tonic-gate	kmem_log_event(kmem_failure_log, cp, NULL, NULL);
16011a5e258Josef 'Jeff' Sipek	atomic_inc_64(&cp->cache_alloc_fail);
16027c478bdstevel@tonic-gate
16037c478bdstevel@tonic-gate	return (NULL);
16047c478bdstevel@tonic-gate}
16057c478bdstevel@tonic-gate
16067c478bdstevel@tonic-gate/*
16077c478bdstevel@tonic-gate * Destroy a slab.
16087c478bdstevel@tonic-gate */
16097c478bdstevel@tonic-gatestatic void
16107c478bdstevel@tonic-gatekmem_slab_destroy(kmem_cache_t *cp, kmem_slab_t *sp)
16117c478bdstevel@tonic-gate{
16127c478bdstevel@tonic-gate	vmem_t *vmp = cp->cache_arena;
16137c478bdstevel@tonic-gate	void *slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum);
16147c478bdstevel@tonic-gate
1615