xref: /illumos-gate/usr/src/uts/common/os/kmem.c (revision 4d4c4c43355e86515b3e8f1309e0d4ca76d9f40c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Kernel memory allocator, as described in the following two papers and a
28  * statement about the consolidator:
29  *
30  * Jeff Bonwick,
31  * The Slab Allocator: An Object-Caching Kernel Memory Allocator.
32  * Proceedings of the Summer 1994 Usenix Conference.
33  * Available as /shared/sac/PSARC/1994/028/materials/kmem.pdf.
34  *
35  * Jeff Bonwick and Jonathan Adams,
36  * Magazines and vmem: Extending the Slab Allocator to Many CPUs and
37  * Arbitrary Resources.
38  * Proceedings of the 2001 Usenix Conference.
39  * Available as /shared/sac/PSARC/2000/550/materials/vmem.pdf.
40  *
41  * kmem Slab Consolidator Big Theory Statement:
42  *
43  * 1. Motivation
44  *
45  * As stated in Bonwick94, slabs provide the following advantages over other
46  * allocation structures in terms of memory fragmentation:
47  *
48  *  - Internal fragmentation (per-buffer wasted space) is minimal.
49  *  - Severe external fragmentation (unused buffers on the free list) is
50  *    unlikely.
51  *
52  * Segregating objects by size eliminates one source of external fragmentation,
53  * and according to Bonwick:
54  *
55  *   The other reason that slabs reduce external fragmentation is that all
56  *   objects in a slab are of the same type, so they have the same lifetime
57  *   distribution. The resulting segregation of short-lived and long-lived
58  *   objects at slab granularity reduces the likelihood of an entire page being
59  *   held hostage due to a single long-lived allocation [Barrett93, Hanson90].
60  *
61  * While unlikely, severe external fragmentation remains possible. Clients that
62  * allocate both short- and long-lived objects from the same cache cannot
63  * anticipate the distribution of long-lived objects within the allocator's slab
64  * implementation. Even a small percentage of long-lived objects distributed
65  * randomly across many slabs can lead to a worst case scenario where the client
66  * frees the majority of its objects and the system gets back almost none of the
67  * slabs. Despite the client doing what it reasonably can to help the system
68  * reclaim memory, the allocator cannot shake free enough slabs because of
69  * lonely allocations stubbornly hanging on. Although the allocator is in a
70  * position to diagnose the fragmentation, there is nothing that the allocator
71  * by itself can do about it. It only takes a single allocated object to prevent
72  * an entire slab from being reclaimed, and any object handed out by
73  * kmem_cache_alloc() is by definition in the client's control. Conversely,
74  * although the client is in a position to move a long-lived object, it has no
75  * way of knowing if the object is causing fragmentation, and if so, where to
76  * move it. A solution necessarily requires further cooperation between the
77  * allocator and the client.
78  *
79  * 2. Move Callback
80  *
81  * The kmem slab consolidator therefore adds a move callback to the
82  * allocator/client interface, improving worst-case external fragmentation in
83  * kmem caches that supply a function to move objects from one memory location
84  * to another. In a situation of low memory kmem attempts to consolidate all of
85  * a cache's slabs at once; otherwise it works slowly to bring external
86  * fragmentation within the 1/8 limit guaranteed for internal fragmentation,
87  * thereby helping to avoid a low memory situation in the future.
88  *
89  * The callback has the following signature:
90  *
91  *   kmem_cbrc_t move(void *old, void *new, size_t size, void *user_arg)
92  *
93  * It supplies the kmem client with two addresses: the allocated object that
94  * kmem wants to move and a buffer selected by kmem for the client to use as the
95  * copy destination. The callback is kmem's way of saying "Please get off of
96  * this buffer and use this one instead." kmem knows where it wants to move the
97  * object in order to best reduce fragmentation. All the client needs to know
98  * about the second argument (void *new) is that it is an allocated, constructed
99  * object ready to take the contents of the old object. When the move function
100  * is called, the system is likely to be low on memory, and the new object
101  * spares the client from having to worry about allocating memory for the
102  * requested move. The third argument supplies the size of the object, in case a
103  * single move function handles multiple caches whose objects differ only in
104  * size (such as zio_buf_512, zio_buf_1024, etc). Finally, the same optional
105  * user argument passed to the constructor, destructor, and reclaim functions is
106  * also passed to the move callback.
107  *
108  * 2.1 Setting the Move Callback
109  *
110  * The client sets the move callback after creating the cache and before
111  * allocating from it:
112  *
113  *	object_cache = kmem_cache_create(...);
114  *      kmem_cache_set_move(object_cache, object_move);
115  *
116  * 2.2 Move Callback Return Values
117  *
118  * Only the client knows about its own data and when is a good time to move it.
119  * The client is cooperating with kmem to return unused memory to the system,
120  * and kmem respectfully accepts this help at the client's convenience. When
121  * asked to move an object, the client can respond with any of the following:
122  *
123  *   typedef enum kmem_cbrc {
124  *           KMEM_CBRC_YES,
125  *           KMEM_CBRC_NO,
126  *           KMEM_CBRC_LATER,
127  *           KMEM_CBRC_DONT_NEED,
128  *           KMEM_CBRC_DONT_KNOW
129  *   } kmem_cbrc_t;
130  *
131  * The client must not explicitly kmem_cache_free() either of the objects passed
132  * to the callback, since kmem wants to free them directly to the slab layer
133  * (bypassing the per-CPU magazine layer). The response tells kmem which of the
134  * objects to free:
135  *
136  *       YES: (Did it) The client moved the object, so kmem frees the old one.
137  *        NO: (Never) The client refused, so kmem frees the new object (the
138  *            unused copy destination). kmem also marks the slab of the old
139  *            object so as not to bother the client with further callbacks for
140  *            that object as long as the slab remains on the partial slab list.
141  *            (The system won't be getting the slab back as long as the
142  *            immovable object holds it hostage, so there's no point in moving
143  *            any of its objects.)
144  *     LATER: The client is using the object and cannot move it now, so kmem
145  *            frees the new object (the unused copy destination). kmem still
146  *            attempts to move other objects off the slab, since it expects to
147  *            succeed in clearing the slab in a later callback. The client
148  *            should use LATER instead of NO if the object is likely to become
149  *            movable very soon.
150  * DONT_NEED: The client no longer needs the object, so kmem frees the old along
151  *            with the new object (the unused copy destination). This response
152  *            is the client's opportunity to be a model citizen and give back as
153  *            much as it can.
154  * DONT_KNOW: The client does not know about the object because
155  *            a) the client has just allocated the object and not yet put it
156  *               wherever it expects to find known objects
157  *            b) the client has removed the object from wherever it expects to
158  *               find known objects and is about to free it, or
159  *            c) the client has freed the object.
160  *            In all these cases (a, b, and c) kmem frees the new object (the
161  *            unused copy destination) and searches for the old object in the
162  *            magazine layer. If found, the object is removed from the magazine
163  *            layer and freed to the slab layer so it will no longer hold the
164  *            slab hostage.
165  *
166  * 2.3 Object States
167  *
168  * Neither kmem nor the client can be assumed to know the object's whereabouts
169  * at the time of the callback. An object belonging to a kmem cache may be in
170  * any of the following states:
171  *
172  * 1. Uninitialized on the slab
173  * 2. Allocated from the slab but not constructed (still uninitialized)
174  * 3. Allocated from the slab, constructed, but not yet ready for business
175  *    (not in a valid state for the move callback)
176  * 4. In use (valid and known to the client)
177  * 5. About to be freed (no longer in a valid state for the move callback)
178  * 6. Freed to a magazine (still constructed)
179  * 7. Allocated from a magazine, not yet ready for business (not in a valid
180  *    state for the move callback), and about to return to state #4
181  * 8. Deconstructed on a magazine that is about to be freed
182  * 9. Freed to the slab
183  *
184  * Since the move callback may be called at any time while the object is in any
185  * of the above states (except state #1), the client needs a safe way to
186  * determine whether or not it knows about the object. Specifically, the client
187  * needs to know whether or not the object is in state #4, the only state in
188  * which a move is valid. If the object is in any other state, the client should
189  * immediately return KMEM_CBRC_DONT_KNOW, since it is unsafe to access any of
190  * the object's fields.
191  *
192  * Note that although an object may be in state #4 when kmem initiates the move
193  * request, the object may no longer be in that state by the time kmem actually
194  * calls the move function. Not only does the client free objects
195  * asynchronously, kmem itself puts move requests on a queue where thay are
196  * pending until kmem processes them from another context. Also, objects freed
197  * to a magazine appear allocated from the point of view of the slab layer, so
198  * kmem may even initiate requests for objects in a state other than state #4.
199  *
200  * 2.3.1 Magazine Layer
201  *
202  * An important insight revealed by the states listed above is that the magazine
203  * layer is populated only by kmem_cache_free(). Magazines of constructed
204  * objects are never populated directly from the slab layer (which contains raw,
205  * unconstructed objects). Whenever an allocation request cannot be satisfied
206  * from the magazine layer, the magazines are bypassed and the request is
207  * satisfied from the slab layer (creating a new slab if necessary). kmem calls
208  * the object constructor only when allocating from the slab layer, and only in
209  * response to kmem_cache_alloc() or to prepare the destination buffer passed in
210  * the move callback. kmem does not preconstruct objects in anticipation of
211  * kmem_cache_alloc().
212  *
213  * 2.3.2 Object Constructor and Destructor
214  *
215  * If the client supplies a destructor, it must be valid to call the destructor
216  * on a newly created object (immediately after the constructor).
217  *
218  * 2.4 Recognizing Known Objects
219  *
220  * There is a simple test to determine safely whether or not the client knows
221  * about a given object in the move callback. It relies on the fact that kmem
222  * guarantees that the object of the move callback has only been touched by the
223  * client itself or else by kmem. kmem does this by ensuring that none of the
224  * cache's slabs are freed to the virtual memory (VM) subsystem while a move
225  * callback is pending. When the last object on a slab is freed, if there is a
226  * pending move, kmem puts the slab on a per-cache dead list and defers freeing
227  * slabs on that list until all pending callbacks are completed. That way,
228  * clients can be certain that the object of a move callback is in one of the
229  * states listed above, making it possible to distinguish known objects (in
230  * state #4) using the two low order bits of any pointer member (with the
231  * exception of 'char *' or 'short *' which may not be 4-byte aligned on some
232  * platforms).
233  *
234  * The test works as long as the client always transitions objects from state #4
235  * (known, in use) to state #5 (about to be freed, invalid) by setting the low
236  * order bit of the client-designated pointer member. Since kmem only writes
237  * invalid memory patterns, such as 0xbaddcafe to uninitialized memory and
238  * 0xdeadbeef to freed memory, any scribbling on the object done by kmem is
239  * guaranteed to set at least one of the two low order bits. Therefore, given an
240  * object with a back pointer to a 'container_t *o_container', the client can
241  * test
242  *
243  *      container_t *container = object->o_container;
244  *      if ((uintptr_t)container & 0x3) {
245  *              return (KMEM_CBRC_DONT_KNOW);
246  *      }
247  *
248  * Typically, an object will have a pointer to some structure with a list or
249  * hash where objects from the cache are kept while in use. Assuming that the
250  * client has some way of knowing that the container structure is valid and will
251  * not go away during the move, and assuming that the structure includes a lock
252  * to protect whatever collection is used, then the client would continue as
253  * follows:
254  *
255  *	// Ensure that the container structure does not go away.
256  *      if (container_hold(container) == 0) {
257  *              return (KMEM_CBRC_DONT_KNOW);
258  *      }
259  *      mutex_enter(&container->c_objects_lock);
260  *      if (container != object->o_container) {
261  *              mutex_exit(&container->c_objects_lock);
262  *              container_rele(container);
263  *              return (KMEM_CBRC_DONT_KNOW);
264  *      }
265  *
266  * At this point the client knows that the object cannot be freed as long as
267  * c_objects_lock is held. Note that after acquiring the lock, the client must
268  * recheck the o_container pointer in case the object was removed just before
269  * acquiring the lock.
270  *
271  * When the client is about to free an object, it must first remove that object
272  * from the list, hash, or other structure where it is kept. At that time, to
273  * mark the object so it can be distinguished from the remaining, known objects,
274  * the client sets the designated low order bit:
275  *
276  *      mutex_enter(&container->c_objects_lock);
277  *      object->o_container = (void *)((uintptr_t)object->o_container | 0x1);
278  *      list_remove(&container->c_objects, object);
279  *      mutex_exit(&container->c_objects_lock);
280  *
281  * In the common case, the object is freed to the magazine layer, where it may
282  * be reused on a subsequent allocation without the overhead of calling the
283  * constructor. While in the magazine it appears allocated from the point of
284  * view of the slab layer, making it a candidate for the move callback. Most
285  * objects unrecognized by the client in the move callback fall into this
286  * category and are cheaply distinguished from known objects by the test
287  * described earlier. Since recognition is cheap for the client, and searching
288  * magazines is expensive for kmem, kmem defers searching until the client first
289  * returns KMEM_CBRC_DONT_KNOW. As long as the needed effort is reasonable, kmem
290  * elsewhere does what it can to avoid bothering the client unnecessarily.
291  *
292  * Invalidating the designated pointer member before freeing the object marks
293  * the object to be avoided in the callback, and conversely, assigning a valid
294  * value to the designated pointer member after allocating the object makes the
295  * object fair game for the callback:
296  *
297  *      ... allocate object ...
298  *      ... set any initial state not set by the constructor ...
299  *
300  *      mutex_enter(&container->c_objects_lock);
301  *      list_insert_tail(&container->c_objects, object);
302  *      membar_producer();
303  *      object->o_container = container;
304  *      mutex_exit(&container->c_objects_lock);
305  *
306  * Note that everything else must be valid before setting o_container makes the
307  * object fair game for the move callback. The membar_producer() call ensures
308  * that all the object's state is written to memory before setting the pointer
309  * that transitions the object from state #3 or #7 (allocated, constructed, not
310  * yet in use) to state #4 (in use, valid). That's important because the move
311  * function has to check the validity of the pointer before it can safely
312  * acquire the lock protecting the collection where it expects to find known
313  * objects.
314  *
315  * This method of distinguishing known objects observes the usual symmetry:
316  * invalidating the designated pointer is the first thing the client does before
317  * freeing the object, and setting the designated pointer is the last thing the
318  * client does after allocating the object. Of course, the client is not
319  * required to use this method. Fundamentally, how the client recognizes known
320  * objects is completely up to the client, but this method is recommended as an
321  * efficient and safe way to take advantage of the guarantees made by kmem. If
322  * the entire object is arbitrary data without any markable bits from a suitable
323  * pointer member, then the client must find some other method, such as
324  * searching a hash table of known objects.
325  *
326  * 2.5 Preventing Objects From Moving
327  *
328  * Besides a way to distinguish known objects, the other thing that the client
329  * needs is a strategy to ensure that an object will not move while the client
330  * is actively using it. The details of satisfying this requirement tend to be
331  * highly cache-specific. It might seem that the same rules that let a client
332  * remove an object safely should also decide when an object can be moved
333  * safely. However, any object state that makes a removal attempt invalid is
334  * likely to be long-lasting for objects that the client does not expect to
335  * remove. kmem knows nothing about the object state and is equally likely (from
336  * the client's point of view) to request a move for any object in the cache,
337  * whether prepared for removal or not. Even a low percentage of objects stuck
338  * in place by unremovability will defeat the consolidator if the stuck objects
339  * are the same long-lived allocations likely to hold slabs hostage.
340  * Fundamentally, the consolidator is not aimed at common cases. Severe external
341  * fragmentation is a worst case scenario manifested as sparsely allocated
342  * slabs, by definition a low percentage of the cache's objects. When deciding
343  * what makes an object movable, keep in mind the goal of the consolidator: to
344  * bring worst-case external fragmentation within the limits guaranteed for
345  * internal fragmentation. Removability is a poor criterion if it is likely to
346  * exclude more than an insignificant percentage of objects for long periods of
347  * time.
348  *
349  * A tricky general solution exists, and it has the advantage of letting you
350  * move any object at almost any moment, practically eliminating the likelihood
351  * that an object can hold a slab hostage. However, if there is a cache-specific
352  * way to ensure that an object is not actively in use in the vast majority of
353  * cases, a simpler solution that leverages this cache-specific knowledge is
354  * preferred.
355  *
356  * 2.5.1 Cache-Specific Solution
357  *
358  * As an example of a cache-specific solution, the ZFS znode cache takes
359  * advantage of the fact that the vast majority of znodes are only being
360  * referenced from the DNLC. (A typical case might be a few hundred in active
361  * use and a hundred thousand in the DNLC.) In the move callback, after the ZFS
362  * client has established that it recognizes the znode and can access its fields
363  * safely (using the method described earlier), it then tests whether the znode
364  * is referenced by anything other than the DNLC. If so, it assumes that the
365  * znode may be in active use and is unsafe to move, so it drops its locks and
366  * returns KMEM_CBRC_LATER. The advantage of this strategy is that everywhere
367  * else znodes are used, no change is needed to protect against the possibility
368  * of the znode moving. The disadvantage is that it remains possible for an
369  * application to hold a znode slab hostage with an open file descriptor.
370  * However, this case ought to be rare and the consolidator has a way to deal
371  * with it: If the client responds KMEM_CBRC_LATER repeatedly for the same
372  * object, kmem eventually stops believing it and treats the slab as if the
373  * client had responded KMEM_CBRC_NO. Having marked the hostage slab, kmem can
374  * then focus on getting it off of the partial slab list by allocating rather
375  * than freeing all of its objects. (Either way of getting a slab off the
376  * free list reduces fragmentation.)
377  *
378  * 2.5.2 General Solution
379  *
380  * The general solution, on the other hand, requires an explicit hold everywhere
381  * the object is used to prevent it from moving. To keep the client locking
382  * strategy as uncomplicated as possible, kmem guarantees the simplifying
383  * assumption that move callbacks are sequential, even across multiple caches.
384  * Internally, a global queue processed by a single thread supports all caches
385  * implementing the callback function. No matter how many caches supply a move
386  * function, the consolidator never moves more than one object at a time, so the
387  * client does not have to worry about tricky lock ordering involving several
388  * related objects from different kmem caches.
389  *
390  * The general solution implements the explicit hold as a read-write lock, which
391  * allows multiple readers to access an object from the cache simultaneously
392  * while a single writer is excluded from moving it. A single rwlock for the
393  * entire cache would lock out all threads from using any of the cache's objects
394  * even though only a single object is being moved, so to reduce contention,
395  * the client can fan out the single rwlock into an array of rwlocks hashed by
396  * the object address, making it probable that moving one object will not
397  * prevent other threads from using a different object. The rwlock cannot be a
398  * member of the object itself, because the possibility of the object moving
399  * makes it unsafe to access any of the object's fields until the lock is
400  * acquired.
401  *
402  * Assuming a small, fixed number of locks, it's possible that multiple objects
403  * will hash to the same lock. A thread that needs to use multiple objects in
404  * the same function may acquire the same lock multiple times. Since rwlocks are
405  * reentrant for readers, and since there is never more than a single writer at
406  * a time (assuming that the client acquires the lock as a writer only when
407  * moving an object inside the callback), there would seem to be no problem.
408  * However, a client locking multiple objects in the same function must handle
409  * one case of potential deadlock: Assume that thread A needs to prevent both
410  * object 1 and object 2 from moving, and thread B, the callback, meanwhile
411  * tries to move object 3. It's possible, if objects 1, 2, and 3 all hash to the
412  * same lock, that thread A will acquire the lock for object 1 as a reader
413  * before thread B sets the lock's write-wanted bit, preventing thread A from
414  * reacquiring the lock for object 2 as a reader. Unable to make forward
415  * progress, thread A will never release the lock for object 1, resulting in
416  * deadlock.
417  *
418  * There are two ways of avoiding the deadlock just described. The first is to
419  * use rw_tryenter() rather than rw_enter() in the callback function when
420  * attempting to acquire the lock as a writer. If tryenter discovers that the
421  * same object (or another object hashed to the same lock) is already in use, it
422  * aborts the callback and returns KMEM_CBRC_LATER. The second way is to use
423  * rprwlock_t (declared in common/fs/zfs/sys/rprwlock.h) instead of rwlock_t,
424  * since it allows a thread to acquire the lock as a reader in spite of a
425  * waiting writer. This second approach insists on moving the object now, no
426  * matter how many readers the move function must wait for in order to do so,
427  * and could delay the completion of the callback indefinitely (blocking
428  * callbacks to other clients). In practice, a less insistent callback using
429  * rw_tryenter() returns KMEM_CBRC_LATER infrequently enough that there seems
430  * little reason to use anything else.
431  *
432  * Avoiding deadlock is not the only problem that an implementation using an
433  * explicit hold needs to solve. Locking the object in the first place (to
434  * prevent it from moving) remains a problem, since the object could move
435  * between the time you obtain a pointer to the object and the time you acquire
436  * the rwlock hashed to that pointer value. Therefore the client needs to
437  * recheck the value of the pointer after acquiring the lock, drop the lock if
438  * the value has changed, and try again. This requires a level of indirection:
439  * something that points to the object rather than the object itself, that the
440  * client can access safely while attempting to acquire the lock. (The object
441  * itself cannot be referenced safely because it can move at any time.)
442  * The following lock-acquisition function takes whatever is safe to reference
443  * (arg), follows its pointer to the object (using function f), and tries as
444  * often as necessary to acquire the hashed lock and verify that the object
445  * still has not moved:
446  *
447  *      object_t *
448  *      object_hold(object_f f, void *arg)
449  *      {
450  *              object_t *op;
451  *
452  *              op = f(arg);
453  *              if (op == NULL) {
454  *                      return (NULL);
455  *              }
456  *
457  *              rw_enter(OBJECT_RWLOCK(op), RW_READER);
458  *              while (op != f(arg)) {
459  *                      rw_exit(OBJECT_RWLOCK(op));
460  *                      op = f(arg);
461  *                      if (op == NULL) {
462  *                              break;
463  *                      }
464  *                      rw_enter(OBJECT_RWLOCK(op), RW_READER);
465  *              }
466  *
467  *              return (op);
468  *      }
469  *
470  * The OBJECT_RWLOCK macro hashes the object address to obtain the rwlock. The
471  * lock reacquisition loop, while necessary, almost never executes. The function
472  * pointer f (used to obtain the object pointer from arg) has the following type
473  * definition:
474  *
475  *      typedef object_t *(*object_f)(void *arg);
476  *
477  * An object_f implementation is likely to be as simple as accessing a structure
478  * member:
479  *
480  *      object_t *
481  *      s_object(void *arg)
482  *      {
483  *              something_t *sp = arg;
484  *              return (sp->s_object);
485  *      }
486  *
487  * The flexibility of a function pointer allows the path to the object to be
488  * arbitrarily complex and also supports the notion that depending on where you
489  * are using the object, you may need to get it from someplace different.
490  *
491  * The function that releases the explicit hold is simpler because it does not
492  * have to worry about the object moving:
493  *
494  *      void
495  *      object_rele(object_t *op)
496  *      {
497  *              rw_exit(OBJECT_RWLOCK(op));
498  *      }
499  *
500  * The caller is spared these details so that obtaining and releasing an
501  * explicit hold feels like a simple mutex_enter()/mutex_exit() pair. The caller
502  * of object_hold() only needs to know that the returned object pointer is valid
503  * if not NULL and that the object will not move until released.
504  *
505  * Although object_hold() prevents an object from moving, it does not prevent it
506  * from being freed. The caller must take measures before calling object_hold()
507  * (afterwards is too late) to ensure that the held object cannot be freed. The
508  * caller must do so without accessing the unsafe object reference, so any lock
509  * or reference count used to ensure the continued existence of the object must
510  * live outside the object itself.
511  *
512  * Obtaining a new object is a special case where an explicit hold is impossible
513  * for the caller. Any function that returns a newly allocated object (either as
514  * a return value, or as an in-out paramter) must return it already held; after
515  * the caller gets it is too late, since the object cannot be safely accessed
516  * without the level of indirection described earlier. The following
517  * object_alloc() example uses the same code shown earlier to transition a new
518  * object into the state of being recognized (by the client) as a known object.
519  * The function must acquire the hold (rw_enter) before that state transition
520  * makes the object movable:
521  *
522  *      static object_t *
523  *      object_alloc(container_t *container)
524  *      {
525  *              object_t *object = kmem_cache_alloc(object_cache, 0);
526  *              ... set any initial state not set by the constructor ...
527  *              rw_enter(OBJECT_RWLOCK(object), RW_READER);
528  *              mutex_enter(&container->c_objects_lock);
529  *              list_insert_tail(&container->c_objects, object);
530  *              membar_producer();
531  *              object->o_container = container;
532  *              mutex_exit(&container->c_objects_lock);
533  *              return (object);
534  *      }
535  *
536  * Functions that implicitly acquire an object hold (any function that calls
537  * object_alloc() to supply an object for the caller) need to be carefully noted
538  * so that the matching object_rele() is not neglected. Otherwise, leaked holds
539  * prevent all objects hashed to the affected rwlocks from ever being moved.
540  *
541  * The pointer to a held object can be hashed to the holding rwlock even after
542  * the object has been freed. Although it is possible to release the hold
543  * after freeing the object, you may decide to release the hold implicitly in
544  * whatever function frees the object, so as to release the hold as soon as
545  * possible, and for the sake of symmetry with the function that implicitly
546  * acquires the hold when it allocates the object. Here, object_free() releases
547  * the hold acquired by object_alloc(). Its implicit object_rele() forms a
548  * matching pair with object_hold():
549  *
550  *      void
551  *      object_free(object_t *object)
552  *      {
553  *              container_t *container;
554  *
555  *              ASSERT(object_held(object));
556  *              container = object->o_container;
557  *              mutex_enter(&container->c_objects_lock);
558  *              object->o_container =
559  *                  (void *)((uintptr_t)object->o_container | 0x1);
560  *              list_remove(&container->c_objects, object);
561  *              mutex_exit(&container->c_objects_lock);
562  *              object_rele(object);
563  *              kmem_cache_free(object_cache, object);
564  *      }
565  *
566  * Note that object_free() cannot safely accept an object pointer as an argument
567  * unless the object is already held. Any function that calls object_free()
568  * needs to be carefully noted since it similarly forms a matching pair with
569  * object_hold().
570  *
571  * To complete the picture, the following callback function implements the
572  * general solution by moving objects only if they are currently unheld:
573  *
574  *      static kmem_cbrc_t
575  *      object_move(void *buf, void *newbuf, size_t size, void *arg)
576  *      {
577  *              object_t *op = buf, *np = newbuf;
578  *              container_t *container;
579  *
580  *              container = op->o_container;
581  *              if ((uintptr_t)container & 0x3) {
582  *                      return (KMEM_CBRC_DONT_KNOW);
583  *              }
584  *
585  *	        // Ensure that the container structure does not go away.
586  *              if (container_hold(container) == 0) {
587  *                      return (KMEM_CBRC_DONT_KNOW);
588  *              }
589  *
590  *              mutex_enter(&container->c_objects_lock);
591  *              if (container != op->o_container) {
592  *                      mutex_exit(&container->c_objects_lock);
593  *                      container_rele(container);
594  *                      return (KMEM_CBRC_DONT_KNOW);
595  *              }
596  *
597  *              if (rw_tryenter(OBJECT_RWLOCK(op), RW_WRITER) == 0) {
598  *                      mutex_exit(&container->c_objects_lock);
599  *                      container_rele(container);
600  *                      return (KMEM_CBRC_LATER);
601  *              }
602  *
603  *              object_move_impl(op, np); // critical section
604  *              rw_exit(OBJECT_RWLOCK(op));
605  *
606  *              op->o_container = (void *)((uintptr_t)op->o_container | 0x1);
607  *              list_link_replace(&op->o_link_node, &np->o_link_node);
608  *              mutex_exit(&container->c_objects_lock);
609  *              container_rele(container);
610  *              return (KMEM_CBRC_YES);
611  *      }
612  *
613  * Note that object_move() must invalidate the designated o_container pointer of
614  * the old object in the same way that object_free() does, since kmem will free
615  * the object in response to the KMEM_CBRC_YES return value.
616  *
617  * The lock order in object_move() differs from object_alloc(), which locks
618  * OBJECT_RWLOCK first and &container->c_objects_lock second, but as long as the
619  * callback uses rw_tryenter() (preventing the deadlock described earlier), it's
620  * not a problem. Holding the lock on the object list in the example above
621  * through the entire callback not only prevents the object from going away, it
622  * also allows you to lock the list elsewhere and know that none of its elements
623  * will move during iteration.
624  *
625  * Adding an explicit hold everywhere an object from the cache is used is tricky
626  * and involves much more change to client code than a cache-specific solution
627  * that leverages existing state to decide whether or not an object is
628  * movable. However, this approach has the advantage that no object remains
629  * immovable for any significant length of time, making it extremely unlikely
630  * that long-lived allocations can continue holding slabs hostage; and it works
631  * for any cache.
632  *
633  * 3. Consolidator Implementation
634  *
635  * Once the client supplies a move function that a) recognizes known objects and
636  * b) avoids moving objects that are actively in use, the remaining work is up
637  * to the consolidator to decide which objects to move and when to issue
638  * callbacks.
639  *
640  * The consolidator relies on the fact that a cache's slabs are ordered by
641  * usage. Each slab has a fixed number of objects. Depending on the slab's
642  * "color" (the offset of the first object from the beginning of the slab;
643  * offsets are staggered to mitigate false sharing of cache lines) it is either
644  * the maximum number of objects per slab determined at cache creation time or
645  * else the number closest to the maximum that fits within the space remaining
646  * after the initial offset. A completely allocated slab may contribute some
647  * internal fragmentation (per-slab overhead) but no external fragmentation, so
648  * it is of no interest to the consolidator. At the other extreme, slabs whose
649  * objects have all been freed to the slab are released to the virtual memory
650  * (VM) subsystem (objects freed to magazines are still allocated as far as the
651  * slab is concerned). External fragmentation exists when there are slabs
652  * somewhere between these extremes. A partial slab has at least one but not all
653  * of its objects allocated. The more partial slabs, and the fewer allocated
654  * objects on each of them, the higher the fragmentation. Hence the
655  * consolidator's overall strategy is to reduce the number of partial slabs by
656  * moving allocated objects from the least allocated slabs to the most allocated
657  * slabs.
658  *
659  * Partial slabs are kept in an AVL tree ordered by usage. Completely allocated
660  * slabs are kept separately in an unordered list. Since the majority of slabs
661  * tend to be completely allocated (a typical unfragmented cache may have
662  * thousands of complete slabs and only a single partial slab), separating
663  * complete slabs improves the efficiency of partial slab ordering, since the
664  * complete slabs do not affect the depth or balance of the AVL tree. This
665  * ordered sequence of partial slabs acts as a "free list" supplying objects for
666  * allocation requests.
667  *
668  * Objects are always allocated from the first partial slab in the free list,
669  * where the allocation is most likely to eliminate a partial slab (by
670  * completely allocating it). Conversely, when a single object from a completely
671  * allocated slab is freed to the slab, that slab is added to the front of the
672  * free list. Since most free list activity involves highly allocated slabs
673  * coming and going at the front of the list, slabs tend naturally toward the
674  * ideal order: highly allocated at the front, sparsely allocated at the back.
675  * Slabs with few allocated objects are likely to become completely free if they
676  * keep a safe distance away from the front of the free list. Slab misorders
677  * interfere with the natural tendency of slabs to become completely free or
678  * completely allocated. For example, a slab with a single allocated object
679  * needs only a single free to escape the cache; its natural desire is
680  * frustrated when it finds itself at the front of the list where a second
681  * allocation happens just before the free could have released it. Another slab
682  * with all but one object allocated might have supplied the buffer instead, so
683  * that both (as opposed to neither) of the slabs would have been taken off the
684  * free list.
685  *
686  * Although slabs tend naturally toward the ideal order, misorders allowed by a
687  * simple list implementation defeat the consolidator's strategy of merging
688  * least- and most-allocated slabs. Without an AVL tree to guarantee order, kmem
689  * needs another way to fix misorders to optimize its callback strategy. One
690  * approach is to periodically scan a limited number of slabs, advancing a
691  * marker to hold the current scan position, and to move extreme misorders to
692  * the front or back of the free list and to the front or back of the current
693  * scan range. By making consecutive scan ranges overlap by one slab, the least
694  * allocated slab in the current range can be carried along from the end of one
695  * scan to the start of the next.
696  *
697  * Maintaining partial slabs in an AVL tree relieves kmem of this additional
698  * task, however. Since most of the cache's activity is in the magazine layer,
699  * and allocations from the slab layer represent only a startup cost, the
700  * overhead of maintaining a balanced tree is not a significant concern compared
701  * to the opportunity of reducing complexity by eliminating the partial slab
702  * scanner just described. The overhead of an AVL tree is minimized by
703  * maintaining only partial slabs in the tree and keeping completely allocated
704  * slabs separately in a list. To avoid increasing the size of the slab
705  * structure the AVL linkage pointers are reused for the slab's list linkage,
706  * since the slab will always be either partial or complete, never stored both
707  * ways at the same time. To further minimize the overhead of the AVL tree the
708  * compare function that orders partial slabs by usage divides the range of
709  * allocated object counts into bins such that counts within the same bin are
710  * considered equal. Binning partial slabs makes it less likely that allocating
711  * or freeing a single object will change the slab's order, requiring a tree
712  * reinsertion (an avl_remove() followed by an avl_add(), both potentially
713  * requiring some rebalancing of the tree). Allocation counts closest to
714  * completely free and completely allocated are left unbinned (finely sorted) to
715  * better support the consolidator's strategy of merging slabs at either
716  * extreme.
717  *
718  * 3.1 Assessing Fragmentation and Selecting Candidate Slabs
719  *
720  * The consolidator piggybacks on the kmem maintenance thread and is called on
721  * the same interval as kmem_cache_update(), once per cache every fifteen
722  * seconds. kmem maintains a running count of unallocated objects in the slab
723  * layer (cache_bufslab). The consolidator checks whether that number exceeds
724  * 12.5% (1/8) of the total objects in the cache (cache_buftotal), and whether
725  * there is a significant number of slabs in the cache (arbitrarily a minimum
726  * 101 total slabs). Unused objects that have fallen out of the magazine layer's
727  * working set are included in the assessment, and magazines in the depot are
728  * reaped if those objects would lift cache_bufslab above the fragmentation
729  * threshold. Once the consolidator decides that a cache is fragmented, it looks
730  * for a candidate slab to reclaim, starting at the end of the partial slab free
731  * list and scanning backwards. At first the consolidator is choosy: only a slab
732  * with fewer than 12.5% (1/8) of its objects allocated qualifies (or else a
733  * single allocated object, regardless of percentage). If there is difficulty
734  * finding a candidate slab, kmem raises the allocation threshold incrementally,
735  * up to a maximum 87.5% (7/8), so that eventually the consolidator will reduce
736  * external fragmentation (unused objects on the free list) below 12.5% (1/8),
737  * even in the worst case of every slab in the cache being almost 7/8 allocated.
738  * The threshold can also be lowered incrementally when candidate slabs are easy
739  * to find, and the threshold is reset to the minimum 1/8 as soon as the cache
740  * is no longer fragmented.
741  *
742  * 3.2 Generating Callbacks
743  *
744  * Once an eligible slab is chosen, a callback is generated for every allocated
745  * object on the slab, in the hope that the client will move everything off the
746  * slab and make it reclaimable. Objects selected as move destinations are
747  * chosen from slabs at the front of the free list. Assuming slabs in the ideal
748  * order (most allocated at the front, least allocated at the back) and a
749  * cooperative client, the consolidator will succeed in removing slabs from both
750  * ends of the free list, completely allocating on the one hand and completely
751  * freeing on the other. Objects selected as move destinations are allocated in
752  * the kmem maintenance thread where move requests are enqueued. A separate
753  * callback thread removes pending callbacks from the queue and calls the
754  * client. The separate thread ensures that client code (the move function) does
755  * not interfere with internal kmem maintenance tasks. A map of pending
756  * callbacks keyed by object address (the object to be moved) is checked to
757  * ensure that duplicate callbacks are not generated for the same object.
758  * Allocating the move destination (the object to move to) prevents subsequent
759  * callbacks from selecting the same destination as an earlier pending callback.
760  *
761  * Move requests can also be generated by kmem_cache_reap() when the system is
762  * desperate for memory and by kmem_cache_move_notify(), called by the client to
763  * notify kmem that a move refused earlier with KMEM_CBRC_LATER is now possible.
764  * The map of pending callbacks is protected by the same lock that protects the
765  * slab layer.
766  *
767  * When the system is desperate for memory, kmem does not bother to determine
768  * whether or not the cache exceeds the fragmentation threshold, but tries to
769  * consolidate as many slabs as possible. Normally, the consolidator chews
770  * slowly, one sparsely allocated slab at a time during each maintenance
771  * interval that the cache is fragmented. When desperate, the consolidator
772  * starts at the last partial slab and enqueues callbacks for every allocated
773  * object on every partial slab, working backwards until it reaches the first
774  * partial slab. The first partial slab, meanwhile, advances in pace with the
775  * consolidator as allocations to supply move destinations for the enqueued
776  * callbacks use up the highly allocated slabs at the front of the free list.
777  * Ideally, the overgrown free list collapses like an accordion, starting at
778  * both ends and ending at the center with a single partial slab.
779  *
780  * 3.3 Client Responses
781  *
782  * When the client returns KMEM_CBRC_NO in response to the move callback, kmem
783  * marks the slab that supplied the stuck object non-reclaimable and moves it to
784  * front of the free list. The slab remains marked as long as it remains on the
785  * free list, and it appears more allocated to the partial slab compare function
786  * than any unmarked slab, no matter how many of its objects are allocated.
787  * Since even one immovable object ties up the entire slab, the goal is to
788  * completely allocate any slab that cannot be completely freed. kmem does not
789  * bother generating callbacks to move objects from a marked slab unless the
790  * system is desperate.
791  *
792  * When the client responds KMEM_CBRC_LATER, kmem increments a count for the
793  * slab. If the client responds LATER too many times, kmem disbelieves and
794  * treats the response as a NO. The count is cleared when the slab is taken off
795  * the partial slab list or when the client moves one of the slab's objects.
796  *
797  * 4. Observability
798  *
799  * A kmem cache's external fragmentation is best observed with 'mdb -k' using
800  * the ::kmem_slabs dcmd. For a complete description of the command, enter
801  * '::help kmem_slabs' at the mdb prompt.
802  */
803 
804 #include <sys/kmem_impl.h>
805 #include <sys/vmem_impl.h>
806 #include <sys/param.h>
807 #include <sys/sysmacros.h>
808 #include <sys/vm.h>
809 #include <sys/proc.h>
810 #include <sys/tuneable.h>
811 #include <sys/systm.h>
812 #include <sys/cmn_err.h>
813 #include <sys/debug.h>
814 #include <sys/sdt.h>
815 #include <sys/mutex.h>
816 #include <sys/bitmap.h>
817 #include <sys/atomic.h>
818 #include <sys/kobj.h>
819 #include <sys/disp.h>
820 #include <vm/seg_kmem.h>
821 #include <sys/log.h>
822 #include <sys/callb.h>
823 #include <sys/taskq.h>
824 #include <sys/modctl.h>
825 #include <sys/reboot.h>
826 #include <sys/id32.h>
827 #include <sys/zone.h>
828 #include <sys/netstack.h>
829 #ifdef	DEBUG
830 #include <sys/random.h>
831 #endif
832 
833 extern void streams_msg_init(void);
834 extern int segkp_fromheap;
835 extern void segkp_cache_free(void);
836 
837 struct kmem_cache_kstat {
838 	kstat_named_t	kmc_buf_size;
839 	kstat_named_t	kmc_align;
840 	kstat_named_t	kmc_chunk_size;
841 	kstat_named_t	kmc_slab_size;
842 	kstat_named_t	kmc_alloc;
843 	kstat_named_t	kmc_alloc_fail;
844 	kstat_named_t	kmc_free;
845 	kstat_named_t	kmc_depot_alloc;
846 	kstat_named_t	kmc_depot_free;
847 	kstat_named_t	kmc_depot_contention;
848 	kstat_named_t	kmc_slab_alloc;
849 	kstat_named_t	kmc_slab_free;
850 	kstat_named_t	kmc_buf_constructed;
851 	kstat_named_t	kmc_buf_avail;
852 	kstat_named_t	kmc_buf_inuse;
853 	kstat_named_t	kmc_buf_total;
854 	kstat_named_t	kmc_buf_max;
855 	kstat_named_t	kmc_slab_create;
856 	kstat_named_t	kmc_slab_destroy;
857 	kstat_named_t	kmc_vmem_source;
858 	kstat_named_t	kmc_hash_size;
859 	kstat_named_t	kmc_hash_lookup_depth;
860 	kstat_named_t	kmc_hash_rescale;
861 	kstat_named_t	kmc_full_magazines;
862 	kstat_named_t	kmc_empty_magazines;
863 	kstat_named_t	kmc_magazine_size;
864 	kstat_named_t	kmc_move_callbacks;
865 	kstat_named_t	kmc_move_yes;
866 	kstat_named_t	kmc_move_no;
867 	kstat_named_t	kmc_move_later;
868 	kstat_named_t	kmc_move_dont_need;
869 	kstat_named_t	kmc_move_dont_know;
870 	kstat_named_t	kmc_move_hunt_found;
871 } kmem_cache_kstat = {
872 	{ "buf_size",		KSTAT_DATA_UINT64 },
873 	{ "align",		KSTAT_DATA_UINT64 },
874 	{ "chunk_size",		KSTAT_DATA_UINT64 },
875 	{ "slab_size",		KSTAT_DATA_UINT64 },
876 	{ "alloc",		KSTAT_DATA_UINT64 },
877 	{ "alloc_fail",		KSTAT_DATA_UINT64 },
878 	{ "free",		KSTAT_DATA_UINT64 },
879 	{ "depot_alloc",	KSTAT_DATA_UINT64 },
880 	{ "depot_free",		KSTAT_DATA_UINT64 },
881 	{ "depot_contention",	KSTAT_DATA_UINT64 },
882 	{ "slab_alloc",		KSTAT_DATA_UINT64 },
883 	{ "slab_free",		KSTAT_DATA_UINT64 },
884 	{ "buf_constructed",	KSTAT_DATA_UINT64 },
885 	{ "buf_avail",		KSTAT_DATA_UINT64 },
886 	{ "buf_inuse",		KSTAT_DATA_UINT64 },
887 	{ "buf_total",		KSTAT_DATA_UINT64 },
888 	{ "buf_max",		KSTAT_DATA_UINT64 },
889 	{ "slab_create",	KSTAT_DATA_UINT64 },
890 	{ "slab_destroy",	KSTAT_DATA_UINT64 },
891 	{ "vmem_source",	KSTAT_DATA_UINT64 },
892 	{ "hash_size",		KSTAT_DATA_UINT64 },
893 	{ "hash_lookup_depth",	KSTAT_DATA_UINT64 },
894 	{ "hash_rescale",	KSTAT_DATA_UINT64 },
895 	{ "full_magazines",	KSTAT_DATA_UINT64 },
896 	{ "empty_magazines",	KSTAT_DATA_UINT64 },
897 	{ "magazine_size",	KSTAT_DATA_UINT64 },
898 	{ "move_callbacks",	KSTAT_DATA_UINT64 },
899 	{ "move_yes",		KSTAT_DATA_UINT64 },
900 	{ "move_no",		KSTAT_DATA_UINT64 },
901 	{ "move_later",		KSTAT_DATA_UINT64 },
902 	{ "move_dont_need",	KSTAT_DATA_UINT64 },
903 	{ "move_dont_know",	KSTAT_DATA_UINT64 },
904 	{ "move_hunt_found",	KSTAT_DATA_UINT64 },
905 };
906 
907 static kmutex_t kmem_cache_kstat_lock;
908 
909 /*
910  * The default set of caches to back kmem_alloc().
911  * These sizes should be reevaluated periodically.
912  *
913  * We want allocations that are multiples of the coherency granularity
914  * (64 bytes) to be satisfied from a cache which is a multiple of 64
915  * bytes, so that it will be 64-byte aligned.  For all multiples of 64,
916  * the next kmem_cache_size greater than or equal to it must be a
917  * multiple of 64.
918  */
919 static const int kmem_alloc_sizes[] = {
920 	1 * 8,
921 	2 * 8,
922 	3 * 8,
923 	4 * 8,		5 * 8,		6 * 8,		7 * 8,
924 	4 * 16,		5 * 16,		6 * 16,		7 * 16,
925 	4 * 32,		5 * 32,		6 * 32,		7 * 32,
926 	4 * 64,		5 * 64,		6 * 64,		7 * 64,
927 	4 * 128,	5 * 128,	6 * 128,	7 * 128,
928 	P2ALIGN(8192 / 7, 64),
929 	P2ALIGN(8192 / 6, 64),
930 	P2ALIGN(8192 / 5, 64),
931 	P2ALIGN(8192 / 4, 64),
932 	P2ALIGN(8192 / 3, 64),
933 	P2ALIGN(8192 / 2, 64),
934 	P2ALIGN(8192 / 1, 64),
935 	4096 * 3,
936 	8192 * 2,
937 	8192 * 3,
938 	8192 * 4,
939 };
940 
941 #define	KMEM_MAXBUF	32768
942 
943 static kmem_cache_t *kmem_alloc_table[KMEM_MAXBUF >> KMEM_ALIGN_SHIFT];
944 
945 static kmem_magtype_t kmem_magtype[] = {
946 	{ 1,	8,	3200,	65536	},
947 	{ 3,	16,	256,	32768	},
948 	{ 7,	32,	64,	16384	},
949 	{ 15,	64,	0,	8192	},
950 	{ 31,	64,	0,	4096	},
951 	{ 47,	64,	0,	2048	},
952 	{ 63,	64,	0,	1024	},
953 	{ 95,	64,	0,	512	},
954 	{ 143,	64,	0,	0	},
955 };
956 
957 static uint32_t kmem_reaping;
958 static uint32_t kmem_reaping_idspace;
959 
960 /*
961  * kmem tunables
962  */
963 clock_t kmem_reap_interval;	/* cache reaping rate [15 * HZ ticks] */
964 int kmem_depot_contention = 3;	/* max failed tryenters per real interval */
965 pgcnt_t kmem_reapahead = 0;	/* start reaping N pages before pageout */
966 int kmem_panic = 1;		/* whether to panic on error */
967 int kmem_logging = 1;		/* kmem_log_enter() override */
968 uint32_t kmem_mtbf = 0;		/* mean time between failures [default: off] */
969 size_t kmem_transaction_log_size; /* transaction log size [2% of memory] */
970 size_t kmem_content_log_size;	/* content log size [2% of memory] */
971 size_t kmem_failure_log_size;	/* failure log [4 pages per CPU] */
972 size_t kmem_slab_log_size;	/* slab create log [4 pages per CPU] */
973 size_t kmem_content_maxsave = 256; /* KMF_CONTENTS max bytes to log */
974 size_t kmem_lite_minsize = 0;	/* minimum buffer size for KMF_LITE */
975 size_t kmem_lite_maxalign = 1024; /* maximum buffer alignment for KMF_LITE */
976 int kmem_lite_pcs = 4;		/* number of PCs to store in KMF_LITE mode */
977 size_t kmem_maxverify;		/* maximum bytes to inspect in debug routines */
978 size_t kmem_minfirewall;	/* hardware-enforced redzone threshold */
979 
980 #ifdef DEBUG
981 int kmem_flags = KMF_AUDIT | KMF_DEADBEEF | KMF_REDZONE | KMF_CONTENTS;
982 #else
983 int kmem_flags = 0;
984 #endif
985 int kmem_ready;
986 
987 static kmem_cache_t	*kmem_slab_cache;
988 static kmem_cache_t	*kmem_bufctl_cache;
989 static kmem_cache_t	*kmem_bufctl_audit_cache;
990 
991 static kmutex_t		kmem_cache_lock;	/* inter-cache linkage only */
992 static list_t		kmem_caches;
993 
994 static taskq_t		*kmem_taskq;
995 static kmutex_t		kmem_flags_lock;
996 static vmem_t		*kmem_metadata_arena;
997 static vmem_t		*kmem_msb_arena;	/* arena for metadata caches */
998 static vmem_t		*kmem_cache_arena;
999 static vmem_t		*kmem_hash_arena;
1000 static vmem_t		*kmem_log_arena;
1001 static vmem_t		*kmem_oversize_arena;
1002 static vmem_t		*kmem_va_arena;
1003 static vmem_t		*kmem_default_arena;
1004 static vmem_t		*kmem_firewall_va_arena;
1005 static vmem_t		*kmem_firewall_arena;
1006 
1007 /*
1008  * Define KMEM_STATS to turn on statistic gathering. By default, it is only
1009  * turned on when DEBUG is also defined.
1010  */
1011 #ifdef	DEBUG
1012 #define	KMEM_STATS
1013 #endif	/* DEBUG */
1014 
1015 #ifdef	KMEM_STATS
1016 #define	KMEM_STAT_ADD(stat)			((stat)++)
1017 #define	KMEM_STAT_COND_ADD(cond, stat)		((void) (!(cond) || (stat)++))
1018 #else
1019 #define	KMEM_STAT_ADD(stat)			/* nothing */
1020 #define	KMEM_STAT_COND_ADD(cond, stat)		/* nothing */
1021 #endif	/* KMEM_STATS */
1022 
1023 /*
1024  * kmem slab consolidator thresholds (tunables)
1025  */
1026 static size_t kmem_frag_minslabs = 101;	/* minimum total slabs */
1027 static size_t kmem_frag_numer = 1;	/* free buffers (numerator) */
1028 static size_t kmem_frag_denom = KMEM_VOID_FRACTION; /* buffers (denominator) */
1029 /*
1030  * Maximum number of slabs from which to move buffers during a single
1031  * maintenance interval while the system is not low on memory.
1032  */
1033 static size_t kmem_reclaim_max_slabs = 1;
1034 /*
1035  * Number of slabs to scan backwards from the end of the partial slab list
1036  * when searching for buffers to relocate.
1037  */
1038 static size_t kmem_reclaim_scan_range = 12;
1039 
1040 #ifdef	KMEM_STATS
1041 static struct {
1042 	uint64_t kms_callbacks;
1043 	uint64_t kms_yes;
1044 	uint64_t kms_no;
1045 	uint64_t kms_later;
1046 	uint64_t kms_dont_need;
1047 	uint64_t kms_dont_know;
1048 	uint64_t kms_hunt_found_slab;
1049 	uint64_t kms_hunt_found_mag;
1050 	uint64_t kms_hunt_alloc_fail;
1051 	uint64_t kms_hunt_lucky;
1052 	uint64_t kms_notify;
1053 	uint64_t kms_notify_callbacks;
1054 	uint64_t kms_disbelief;
1055 	uint64_t kms_already_pending;
1056 	uint64_t kms_callback_alloc_fail;
1057 	uint64_t kms_callback_taskq_fail;
1058 	uint64_t kms_endscan_slab_destroyed;
1059 	uint64_t kms_endscan_nomem;
1060 	uint64_t kms_endscan_slab_all_used;
1061 	uint64_t kms_endscan_refcnt_changed;
1062 	uint64_t kms_endscan_nomove_changed;
1063 	uint64_t kms_endscan_freelist;
1064 	uint64_t kms_avl_update;
1065 	uint64_t kms_avl_noupdate;
1066 	uint64_t kms_no_longer_reclaimable;
1067 	uint64_t kms_notify_no_longer_reclaimable;
1068 	uint64_t kms_alloc_fail;
1069 	uint64_t kms_constructor_fail;
1070 	uint64_t kms_dead_slabs_freed;
1071 	uint64_t kms_defrags;
1072 	uint64_t kms_scan_depot_ws_reaps;
1073 	uint64_t kms_debug_reaps;
1074 	uint64_t kms_debug_move_scans;
1075 } kmem_move_stats;
1076 #endif	/* KMEM_STATS */
1077 
1078 /* consolidator knobs */
1079 static boolean_t kmem_move_noreap;
1080 static boolean_t kmem_move_blocked;
1081 static boolean_t kmem_move_fulltilt;
1082 static boolean_t kmem_move_any_partial;
1083 
1084 #ifdef	DEBUG
1085 /*
1086  * Ensure code coverage by occasionally running the consolidator even when the
1087  * caches are not fragmented (they may never be). These intervals are mean time
1088  * in cache maintenance intervals (kmem_cache_update).
1089  */
1090 static int kmem_mtb_move = 60;		/* defrag 1 slab (~15min) */
1091 static int kmem_mtb_reap = 1800;	/* defrag all slabs (~7.5hrs) */
1092 #endif	/* DEBUG */
1093 
1094 static kmem_cache_t	*kmem_defrag_cache;
1095 static kmem_cache_t	*kmem_move_cache;
1096 static taskq_t		*kmem_move_taskq;
1097 
1098 static void kmem_cache_scan(kmem_cache_t *);
1099 static void kmem_cache_defrag(kmem_cache_t *);
1100 
1101 
1102 kmem_log_header_t	*kmem_transaction_log;
1103 kmem_log_header_t	*kmem_content_log;
1104 kmem_log_header_t	*kmem_failure_log;
1105 kmem_log_header_t	*kmem_slab_log;
1106 
1107 static int		kmem_lite_count; /* # of PCs in kmem_buftag_lite_t */
1108 
1109 #define	KMEM_BUFTAG_LITE_ENTER(bt, count, caller)			\
1110 	if ((count) > 0) {						\
1111 		pc_t *_s = ((kmem_buftag_lite_t *)(bt))->bt_history;	\
1112 		pc_t *_e;						\
1113 		/* memmove() the old entries down one notch */		\
1114 		for (_e = &_s[(count) - 1]; _e > _s; _e--)		\
1115 			*_e = *(_e - 1);				\
1116 		*_s = (uintptr_t)(caller);				\
1117 	}
1118 
1119 #define	KMERR_MODIFIED	0	/* buffer modified while on freelist */
1120 #define	KMERR_REDZONE	1	/* redzone violation (write past end of buf) */
1121 #define	KMERR_DUPFREE	2	/* freed a buffer twice */
1122 #define	KMERR_BADADDR	3	/* freed a bad (unallocated) address */
1123 #define	KMERR_BADBUFTAG	4	/* buftag corrupted */
1124 #define	KMERR_BADBUFCTL	5	/* bufctl corrupted */
1125 #define	KMERR_BADCACHE	6	/* freed a buffer to the wrong cache */
1126 #define	KMERR_BADSIZE	7	/* alloc size != free size */
1127 #define	KMERR_BADBASE	8	/* buffer base address wrong */
1128 
1129 struct {
1130 	hrtime_t	kmp_timestamp;	/* timestamp of panic */
1131 	int		kmp_error;	/* type of kmem error */
1132 	void		*kmp_buffer;	/* buffer that induced panic */
1133 	void		*kmp_realbuf;	/* real start address for buffer */
1134 	kmem_cache_t	*kmp_cache;	/* buffer's cache according to client */
1135 	kmem_cache_t	*kmp_realcache;	/* actual cache containing buffer */
1136 	kmem_slab_t	*kmp_slab;	/* slab accoring to kmem_findslab() */
1137 	kmem_bufctl_t	*kmp_bufctl;	/* bufctl */
1138 } kmem_panic_info;
1139 
1140 
1141 static void
1142 copy_pattern(uint64_t pattern, void *buf_arg, size_t size)
1143 {
1144 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1145 	uint64_t *buf = buf_arg;
1146 
1147 	while (buf < bufend)
1148 		*buf++ = pattern;
1149 }
1150 
1151 static void *
1152 verify_pattern(uint64_t pattern, void *buf_arg, size_t size)
1153 {
1154 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1155 	uint64_t *buf;
1156 
1157 	for (buf = buf_arg; buf < bufend; buf++)
1158 		if (*buf != pattern)
1159 			return (buf);
1160 	return (NULL);
1161 }
1162 
1163 static void *
1164 verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, size_t size)
1165 {
1166 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1167 	uint64_t *buf;
1168 
1169 	for (buf = buf_arg; buf < bufend; buf++) {
1170 		if (*buf != old) {
1171 			copy_pattern(old, buf_arg,
1172 			    (char *)buf - (char *)buf_arg);
1173 			return (buf);
1174 		}
1175 		*buf = new;
1176 	}
1177 
1178 	return (NULL);
1179 }
1180 
1181 static void
1182 kmem_cache_applyall(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
1183 {
1184 	kmem_cache_t *cp;
1185 
1186 	mutex_enter(&kmem_cache_lock);
1187 	for (cp = list_head(&kmem_caches); cp != NULL;
1188 	    cp = list_next(&kmem_caches, cp))
1189 		if (tq != NULL)
1190 			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
1191 			    tqflag);
1192 		else
1193 			func(cp);
1194 	mutex_exit(&kmem_cache_lock);
1195 }
1196 
1197 static void
1198 kmem_cache_applyall_id(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
1199 {
1200 	kmem_cache_t *cp;
1201 
1202 	mutex_enter(&kmem_cache_lock);
1203 	for (cp = list_head(&kmem_caches); cp != NULL;
1204 	    cp = list_next(&kmem_caches, cp)) {
1205 		if (!(cp->cache_cflags & KMC_IDENTIFIER))
1206 			continue;
1207 		if (tq != NULL)
1208 			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
1209 			    tqflag);
1210 		else
1211 			func(cp);
1212 	}
1213 	mutex_exit(&kmem_cache_lock);
1214 }
1215 
1216 /*
1217  * Debugging support.  Given a buffer address, find its slab.
1218  */
1219 static kmem_slab_t *
1220 kmem_findslab(kmem_cache_t *cp, void *buf)
1221 {
1222 	kmem_slab_t *sp;
1223 
1224 	mutex_enter(&cp->cache_lock);
1225 	for (sp = list_head(&cp->cache_complete_slabs); sp != NULL;
1226 	    sp = list_next(&cp->cache_complete_slabs, sp)) {
1227 		if (KMEM_SLAB_MEMBER(sp, buf)) {
1228 			mutex_exit(&cp->cache_lock);
1229 			return (sp);
1230 		}
1231 	}
1232 	for (sp = avl_first(&cp->cache_partial_slabs); sp != NULL;
1233 	    sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) {
1234 		if (KMEM_SLAB_MEMBER(sp, buf)) {
1235 			mutex_exit(&cp->cache_lock);
1236 			return (sp);
1237 		}
1238 	}
1239 	mutex_exit(&cp->cache_lock);
1240 
1241 	return (NULL);
1242 }
1243 
1244 static void
1245 kmem_error(int error, kmem_cache_t *cparg, void *bufarg)
1246 {
1247 	kmem_buftag_t *btp = NULL;
1248 	kmem_bufctl_t *bcp = NULL;
1249 	kmem_cache_t *cp = cparg;
1250 	kmem_slab_t *sp;
1251 	uint64_t *off;
1252 	void *buf = bufarg;
1253 
1254 	kmem_logging = 0;	/* stop logging when a bad thing happens */
1255 
1256 	kmem_panic_info.kmp_timestamp = gethrtime();
1257 
1258 	sp = kmem_findslab(cp, buf);
1259 	if (sp == NULL) {
1260 		for (cp = list_tail(&kmem_caches); cp != NULL;
1261 		    cp = list_prev(&kmem_caches, cp)) {
1262 			if ((sp = kmem_findslab(cp, buf)) != NULL)
1263 				break;
1264 		}
1265 	}
1266 
1267 	if (sp == NULL) {
1268 		cp = NULL;
1269 		error = KMERR_BADADDR;
1270 	} else {
1271 		if (cp != cparg)
1272 			error = KMERR_BADCACHE;
1273 		else
1274 			buf = (char *)bufarg - ((uintptr_t)bufarg -
1275 			    (uintptr_t)sp->slab_base) % cp->cache_chunksize;
1276 		if (buf != bufarg)
1277 			error = KMERR_BADBASE;
1278 		if (cp->cache_flags & KMF_BUFTAG)
1279 			btp = KMEM_BUFTAG(cp, buf);
1280 		if (cp->cache_flags & KMF_HASH) {
1281 			mutex_enter(&cp->cache_lock);
1282 			for (bcp = *KMEM_HASH(cp, buf); bcp; bcp = bcp->bc_next)
1283 				if (bcp->bc_addr == buf)
1284 					break;
1285 			mutex_exit(&cp->cache_lock);
1286 			if (bcp == NULL && btp != NULL)
1287 				bcp = btp->bt_bufctl;
1288 			if (kmem_findslab(cp->cache_bufctl_cache, bcp) ==
1289 			    NULL || P2PHASE((uintptr_t)bcp, KMEM_ALIGN) ||
1290 			    bcp->bc_addr != buf) {
1291 				error = KMERR_BADBUFCTL;
1292 				bcp = NULL;
1293 			}
1294 		}
1295 	}
1296 
1297 	kmem_panic_info.kmp_error = error;
1298 	kmem_panic_info.kmp_buffer = bufarg;
1299 	kmem_panic_info.kmp_realbuf = buf;
1300 	kmem_panic_info.kmp_cache = cparg;
1301 	kmem_panic_info.kmp_realcache = cp;
1302 	kmem_panic_info.kmp_slab = sp;
1303 	kmem_panic_info.kmp_bufctl = bcp;
1304 
1305 	printf("kernel memory allocator: ");
1306 
1307 	switch (error) {
1308 
1309 	case KMERR_MODIFIED:
1310 		printf("buffer modified after being freed\n");
1311 		off = verify_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1312 		if (off == NULL)	/* shouldn't happen */
1313 			off = buf;
1314 		printf("modification occurred at offset 0x%lx "
1315 		    "(0x%llx replaced by 0x%llx)\n",
1316 		    (uintptr_t)off - (uintptr_t)buf,
1317 		    (longlong_t)KMEM_FREE_PATTERN, (longlong_t)*off);
1318 		break;
1319 
1320 	case KMERR_REDZONE:
1321 		printf("redzone violation: write past end of buffer\n");
1322 		break;
1323 
1324 	case KMERR_BADADDR:
1325 		printf("invalid free: buffer not in cache\n");
1326 		break;
1327 
1328 	case KMERR_DUPFREE:
1329 		printf("duplicate free: buffer freed twice\n");
1330 		break;
1331 
1332 	case KMERR_BADBUFTAG:
1333 		printf("boundary tag corrupted\n");
1334 		printf("bcp ^ bxstat = %lx, should be %lx\n",
1335 		    (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat,
1336 		    KMEM_BUFTAG_FREE);
1337 		break;
1338 
1339 	case KMERR_BADBUFCTL:
1340 		printf("bufctl corrupted\n");
1341 		break;
1342 
1343 	case KMERR_BADCACHE:
1344 		printf("buffer freed to wrong cache\n");
1345 		printf("buffer was allocated from %s,\n", cp->cache_name);
1346 		printf("caller attempting free to %s.\n", cparg->cache_name);
1347 		break;
1348 
1349 	case KMERR_BADSIZE:
1350 		printf("bad free: free size (%u) != alloc size (%u)\n",
1351 		    KMEM_SIZE_DECODE(((uint32_t *)btp)[0]),
1352 		    KMEM_SIZE_DECODE(((uint32_t *)btp)[1]));
1353 		break;
1354 
1355 	case KMERR_BADBASE:
1356 		printf("bad free: free address (%p) != alloc address (%p)\n",
1357 		    bufarg, buf);
1358 		break;
1359 	}
1360 
1361 	printf("buffer=%p  bufctl=%p  cache: %s\n",
1362 	    bufarg, (void *)bcp, cparg->cache_name);
1363 
1364 	if (bcp != NULL && (cp->cache_flags & KMF_AUDIT) &&
1365 	    error != KMERR_BADBUFCTL) {
1366 		int d;
1367 		timestruc_t ts;
1368 		kmem_bufctl_audit_t *bcap = (kmem_bufctl_audit_t *)bcp;
1369 
1370 		hrt2ts(kmem_panic_info.kmp_timestamp - bcap->bc_timestamp, &ts);
1371 		printf("previous transaction on buffer %p:\n", buf);
1372 		printf("thread=%p  time=T-%ld.%09ld  slab=%p  cache: %s\n",
1373 		    (void *)bcap->bc_thread, ts.tv_sec, ts.tv_nsec,
1374 		    (void *)sp, cp->cache_name);
1375 		for (d = 0; d < MIN(bcap->bc_depth, KMEM_STACK_DEPTH); d++) {
1376 			ulong_t off;
1377 			char *sym = kobj_getsymname(bcap->bc_stack[d], &off);
1378 			printf("%s+%lx\n", sym ? sym : "?", off);
1379 		}
1380 	}
1381 	if (kmem_panic > 0)
1382 		panic("kernel heap corruption detected");
1383 	if (kmem_panic == 0)
1384 		debug_enter(NULL);
1385 	kmem_logging = 1;	/* resume logging */
1386 }
1387 
1388 static kmem_log_header_t *
1389 kmem_log_init(size_t logsize)
1390 {
1391 	kmem_log_header_t *lhp;
1392 	int nchunks = 4 * max_ncpus;
1393 	size_t lhsize = (size_t)&((kmem_log_header_t *)0)->lh_cpu[max_ncpus];
1394 	int i;
1395 
1396 	/*
1397 	 * Make sure that lhp->lh_cpu[] is nicely aligned
1398 	 * to prevent false sharing of cache lines.
1399 	 */
1400 	lhsize = P2ROUNDUP(lhsize, KMEM_ALIGN);
1401 	lhp = vmem_xalloc(kmem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0,
1402 	    NULL, NULL, VM_SLEEP);
1403 	bzero(lhp, lhsize);
1404 
1405 	mutex_init(&lhp->lh_lock, NULL, MUTEX_DEFAULT, NULL);
1406 	lhp->lh_nchunks = nchunks;
1407 	lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks + 1, PAGESIZE);
1408 	lhp->lh_base = vmem_alloc(kmem_log_arena,
1409 	    lhp->lh_chunksize * nchunks, VM_SLEEP);
1410 	lhp->lh_free = vmem_alloc(kmem_log_arena,
1411 	    nchunks * sizeof (int), VM_SLEEP);
1412 	bzero(lhp->lh_base, lhp->lh_chunksize * nchunks);
1413 
1414 	for (i = 0; i < max_ncpus; i++) {
1415 		kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[i];
1416 		mutex_init(&clhp->clh_lock, NULL, MUTEX_DEFAULT, NULL);
1417 		clhp->clh_chunk = i;
1418 	}
1419 
1420 	for (i = max_ncpus; i < nchunks; i++)
1421 		lhp->lh_free[i] = i;
1422 
1423 	lhp->lh_head = max_ncpus;
1424 	lhp->lh_tail = 0;
1425 
1426 	return (lhp);
1427 }
1428 
1429 static void *
1430 kmem_log_enter(kmem_log_header_t *lhp, void *data, size_t size)
1431 {
1432 	void *logspace;
1433 	kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[CPU->cpu_seqid];
1434 
1435 	if (lhp == NULL || kmem_logging == 0 || panicstr)
1436 		return (NULL);
1437 
1438 	mutex_enter(&clhp->clh_lock);
1439 	clhp->clh_hits++;
1440 	if (size > clhp->clh_avail) {
1441 		mutex_enter(&lhp->lh_lock);
1442 		lhp->lh_hits++;
1443 		lhp->lh_free[lhp->lh_tail] = clhp->clh_chunk;
1444 		lhp->lh_tail = (lhp->lh_tail + 1) % lhp->lh_nchunks;
1445 		clhp->clh_chunk = lhp->lh_free[lhp->lh_head];
1446 		lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks;
1447 		clhp->clh_current = lhp->lh_base +
1448 		    clhp->clh_chunk * lhp->lh_chunksize;
1449 		clhp->clh_avail = lhp->lh_chunksize;
1450 		if (size > lhp->lh_chunksize)
1451 			size = lhp->lh_chunksize;
1452 		mutex_exit(&lhp->lh_lock);
1453 	}
1454 	logspace = clhp->clh_current;
1455 	clhp->clh_current += size;
1456 	clhp->clh_avail -= size;
1457 	bcopy(data, logspace, size);
1458 	mutex_exit(&clhp->clh_lock);
1459 	return (logspace);
1460 }
1461 
1462 #define	KMEM_AUDIT(lp, cp, bcp)						\
1463 {									\
1464 	kmem_bufctl_audit_t *_bcp = (kmem_bufctl_audit_t *)(bcp);	\
1465 	_bcp->bc_timestamp = gethrtime();				\
1466 	_bcp->bc_thread = curthread;					\
1467 	_bcp->bc_depth = getpcstack(_bcp->bc_stack, KMEM_STACK_DEPTH);	\
1468 	_bcp->bc_lastlog = kmem_log_enter((lp), _bcp, sizeof (*_bcp));	\
1469 }
1470 
1471 static void
1472 kmem_log_event(kmem_log_header_t *lp, kmem_cache_t *cp,
1473 	kmem_slab_t *sp, void *addr)
1474 {
1475 	kmem_bufctl_audit_t bca;
1476 
1477 	bzero(&bca, sizeof (kmem_bufctl_audit_t));
1478 	bca.bc_addr = addr;
1479 	bca.bc_slab = sp;
1480 	bca.bc_cache = cp;
1481 	KMEM_AUDIT(lp, cp, &bca);
1482 }
1483 
1484 /*
1485  * Create a new slab for cache cp.
1486  */
1487 static kmem_slab_t *
1488 kmem_slab_create(kmem_cache_t *cp, int kmflag)
1489 {
1490 	size_t slabsize = cp->cache_slabsize;
1491 	size_t chunksize = cp->cache_chunksize;
1492 	int cache_flags = cp->cache_flags;
1493 	size_t color, chunks;
1494 	char *buf, *slab;
1495 	kmem_slab_t *sp;
1496 	kmem_bufctl_t *bcp;
1497 	vmem_t *vmp = cp->cache_arena;
1498 
1499 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
1500 
1501 	color = cp->cache_color + cp->cache_align;
1502 	if (color > cp->cache_maxcolor)
1503 		color = cp->cache_mincolor;
1504 	cp->cache_color = color;
1505 
1506 	slab = vmem_alloc(vmp, slabsize, kmflag & KM_VMFLAGS);
1507 
1508 	if (slab == NULL)
1509 		goto vmem_alloc_failure;
1510 
1511 	ASSERT(P2PHASE((uintptr_t)slab, vmp->vm_quantum) == 0);
1512 
1513 	/*
1514 	 * Reverify what was already checked in kmem_cache_set_move(), since the
1515 	 * consolidator depends (for correctness) on slabs being initialized
1516 	 * with the 0xbaddcafe memory pattern (setting a low order bit usable by
1517 	 * clients to distinguish uninitialized memory from known objects).
1518 	 */
1519 	ASSERT((cp->cache_move == NULL) || !(cp->cache_cflags & KMC_NOTOUCH));
1520 	if (!(cp->cache_cflags & KMC_NOTOUCH))
1521 		copy_pattern(KMEM_UNINITIALIZED_PATTERN, slab, slabsize);
1522 
1523 	if (cache_flags & KMF_HASH) {
1524 		if ((sp = kmem_cache_alloc(kmem_slab_cache, kmflag)) == NULL)
1525 			goto slab_alloc_failure;
1526 		chunks = (slabsize - color) / chunksize;
1527 	} else {
1528 		sp = KMEM_SLAB(cp, slab);
1529 		chunks = (slabsize - sizeof (kmem_slab_t) - color) / chunksize;
1530 	}
1531 
1532 	sp->slab_cache	= cp;
1533 	sp->slab_head	= NULL;
1534 	sp->slab_refcnt	= 0;
1535 	sp->slab_base	= buf = slab + color;
1536 	sp->slab_chunks	= chunks;
1537 	sp->slab_stuck_offset = (uint32_t)-1;
1538 	sp->slab_later_count = 0;
1539 	sp->slab_flags = 0;
1540 
1541 	ASSERT(chunks > 0);
1542 	while (chunks-- != 0) {
1543 		if (cache_flags & KMF_HASH) {
1544 			bcp = kmem_cache_alloc(cp->cache_bufctl_cache, kmflag);
1545 			if (bcp == NULL)
1546 				goto bufctl_alloc_failure;
1547 			if (cache_flags & KMF_AUDIT) {
1548 				kmem_bufctl_audit_t *bcap =
1549 				    (kmem_bufctl_audit_t *)bcp;
1550 				bzero(bcap, sizeof (kmem_bufctl_audit_t));
1551 				bcap->bc_cache = cp;
1552 			}
1553 			bcp->bc_addr = buf;
1554 			bcp->bc_slab = sp;
1555 		} else {
1556 			bcp = KMEM_BUFCTL(cp, buf);
1557 		}
1558 		if (cache_flags & KMF_BUFTAG) {
1559 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1560 			btp->bt_redzone = KMEM_REDZONE_PATTERN;
1561 			btp->bt_bufctl = bcp;
1562 			btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1563 			if (cache_flags & KMF_DEADBEEF) {
1564 				copy_pattern(KMEM_FREE_PATTERN, buf,
1565 				    cp->cache_verify);
1566 			}
1567 		}
1568 		bcp->bc_next = sp->slab_head;
1569 		sp->slab_head = bcp;
1570 		buf += chunksize;
1571 	}
1572 
1573 	kmem_log_event(kmem_slab_log, cp, sp, slab);
1574 
1575 	return (sp);
1576 
1577 bufctl_alloc_failure:
1578 
1579 	while ((bcp = sp->slab_head) != NULL) {
1580 		sp->slab_head = bcp->bc_next;
1581 		kmem_cache_free(cp->cache_bufctl_cache, bcp);
1582 	}
1583 	kmem_cache_free(kmem_slab_cache, sp);
1584 
1585 slab_alloc_failure:
1586 
1587 	vmem_free(vmp, slab, slabsize);
1588 
1589 vmem_alloc_failure:
1590 
1591 	kmem_log_event(kmem_failure_log, cp, NULL, NULL);
1592 	atomic_add_64(&cp->cache_alloc_fail, 1);
1593 
1594 	return (NULL);
1595 }
1596 
1597 /*
1598  * Destroy a slab.
1599  */
1600 static void
1601 kmem_slab_destroy(kmem_cache_t *cp, kmem_slab_t *sp)
1602 {
1603 	vmem_t *vmp = cp->cache_arena;
1604 	void *slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum);
1605 
1606 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
1607 	ASSERT(sp->slab_refcnt == 0);
1608 
1609 	if (cp->cache_flags & KMF_HASH) {
1610 		kmem_bufctl_t *bcp;
1611 		while ((bcp = sp->slab_head) != NULL) {
1612 			sp->slab_head = bcp->bc_next;
1613 			kmem_cache_free(cp->cache_bufctl_cache, bcp);
1614 		}
1615 		kmem_cache_free(kmem_slab_cache, sp);
1616 	}
1617 	vmem_free(vmp, slab, cp->cache_slabsize);
1618 }
1619 
1620 static void *
1621 kmem_slab_alloc_impl(kmem_cache_t *cp, kmem_slab_t *sp)
1622 {
1623 	kmem_bufctl_t *bcp, **hash_bucket;
1624 	void *buf;
1625 
1626 	ASSERT(MUTEX_HELD(&cp->cache_lock));
1627 	/*
1628 	 * kmem_slab_alloc() drops cache_lock when it creates a new slab, so we
1629 	 * can't ASSERT(avl_is_empty(&cp->cache_partial_slabs)) here when the
1630 	 * slab is newly created (sp->slab_refcnt == 0).
1631 	 */
1632 	ASSERT((sp->slab_refcnt == 0) || (KMEM_SLAB_IS_PARTIAL(sp) &&
1633 	    (sp == avl_first(&cp->cache_partial_slabs))));
1634 	ASSERT(sp->slab_cache == cp);
1635 
1636 	cp->cache_slab_alloc++;
1637 	cp->cache_bufslab--;
1638 	sp->slab_refcnt++;
1639 
1640 	bcp = sp->slab_head;
1641 	if ((sp->slab_head = bcp->bc_next) == NULL) {
1642 		ASSERT(KMEM_SLAB_IS_ALL_USED(sp));
1643 		if (sp->slab_refcnt == 1) {
1644 			ASSERT(sp->slab_chunks == 1);
1645 		} else {
1646 			ASSERT(sp->slab_chunks > 1); /* the slab was partial */
1647 			avl_remove(&cp->cache_partial_slabs, sp);
1648 			sp->slab_later_count = 0; /* clear history */
1649 			sp->slab_flags &= ~KMEM_SLAB_NOMOVE;
1650 			sp->slab_stuck_offset = (uint32_t)-1;
1651 		}
1652 		list_insert_head(&cp->cache_complete_slabs, sp);
1653 		cp->cache_complete_slab_count++;
1654 	} else {
1655 		ASSERT(KMEM_SLAB_IS_PARTIAL(sp));
1656 		if (sp->slab_refcnt == 1) {
1657 			avl_add(&cp->cache_partial_slabs, sp);
1658 		} else {
1659 			/*
1660 			 * The slab is now more allocated than it was, so the
1661 			 * order remains unchanged.
1662 			 */
1663 			ASSERT(!avl_update(&cp->cache_partial_slabs, sp));
1664 		}
1665 	}
1666 
1667 	if (cp->cache_flags & KMF_HASH) {
1668 		/*
1669 		 * Add buffer to allocated-address hash table.
1670 		 */
1671 		buf = bcp->bc_addr;
1672 		hash_bucket = KMEM_HASH(cp, buf);
1673 		bcp->bc_next = *hash_bucket;
1674 		*hash_bucket = bcp;
1675 		if ((cp->cache_flags & (KMF_AUDIT | KMF_BUFTAG)) == KMF_AUDIT) {
1676 			KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1677 		}
1678 	} else {
1679 		buf = KMEM_BUF(cp, bcp);
1680 	}
1681 
1682 	ASSERT(KMEM_SLAB_MEMBER(sp, buf));
1683 	return (buf);
1684 }
1685 
1686 /*
1687  * Allocate a raw (unconstructed) buffer from cp's slab layer.
1688  */
1689 static void *
1690 kmem_slab_alloc(kmem_cache_t *cp, int kmflag)
1691 {
1692 	kmem_slab_t *sp;
1693 	void *buf;
1694 	boolean_t test_destructor;
1695 
1696 	mutex_enter(&cp->cache_lock);
1697 	test_destructor = (cp->cache_slab_alloc == 0);
1698 	sp = avl_first(&cp->cache_partial_slabs);
1699 	if (sp == NULL) {
1700 		ASSERT(cp->cache_bufslab == 0);
1701 
1702 		/*
1703 		 * The freelist is empty.  Create a new slab.
1704 		 */
1705 		mutex_exit(&cp->cache_lock);
1706 		if ((sp = kmem_slab_create(cp, kmflag)) == NULL) {
1707 			return (NULL);
1708 		}
1709 		mutex_enter(&cp->cache_lock);
1710 		cp->cache_slab_create++;
1711 		if ((cp->cache_buftotal += sp->slab_chunks) > cp->cache_bufmax)
1712 			cp->cache_bufmax = cp->cache_buftotal;
1713 		cp->cache_bufslab += sp->slab_chunks;
1714 	}
1715 
1716 	buf = kmem_slab_alloc_impl(cp, sp);
1717 	ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) ==
1718 	    (cp->cache_complete_slab_count +
1719 	    avl_numnodes(&cp->cache_partial_slabs) +
1720 	    (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount)));
1721 	mutex_exit(&cp->cache_lock);
1722 
1723 	if (test_destructor && cp->cache_destructor != NULL) {
1724 		/*
1725 		 * On the first kmem_slab_alloc(), assert that it is valid to
1726 		 * call the destructor on a newly constructed object without any
1727 		 * client involvement.
1728 		 */
1729 		if ((cp->cache_constructor == NULL) ||
1730 		    cp->cache_constructor(buf, cp->cache_private,
1731 		    kmflag) == 0) {
1732 			cp->cache_destructor(buf, cp->cache_private);
1733 		}
1734 		copy_pattern(KMEM_UNINITIALIZED_PATTERN, buf,
1735 		    cp->cache_bufsize);
1736 		if (cp->cache_flags & KMF_DEADBEEF) {
1737 			copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1738 		}
1739 	}
1740 
1741 	return (buf);
1742 }
1743 
1744 static void kmem_slab_move_yes(kmem_cache_t *, kmem_slab_t *, void *);
1745 
1746 /*
1747  * Free a raw (unconstructed) buffer to cp's slab layer.
1748  */
1749 static void
1750 kmem_slab_free(kmem_cache_t *cp, void *buf)
1751 {
1752 	kmem_slab_t *sp;
1753 	kmem_bufctl_t *bcp, **prev_bcpp;
1754 
1755 	ASSERT(buf != NULL);
1756 
1757 	mutex_enter(&cp->cache_lock);
1758 	cp->cache_slab_free++;
1759 
1760 	if (cp->cache_flags & KMF_HASH) {
1761 		/*
1762 		 * Look up buffer in allocated-address hash table.
1763 		 */
1764 		prev_bcpp = KMEM_HASH(cp, buf);
1765 		while ((bcp = *prev_bcpp) != NULL) {
1766 			if (bcp->bc_addr == buf) {
1767 				*prev_bcpp = bcp->bc_next;
1768 				sp = bcp->bc_slab;
1769 				break;
1770 			}
1771 			cp->cache_lookup_depth++;
1772 			prev_bcpp = &bcp->bc_next;
1773 		}
1774 	} else {
1775 		bcp = KMEM_BUFCTL(cp, buf);
1776 		sp = KMEM_SLAB(cp, buf);
1777 	}
1778 
1779 	if (bcp == NULL || sp->slab_cache != cp || !KMEM_SLAB_MEMBER(sp, buf)) {
1780 		mutex_exit(&cp->cache_lock);
1781 		kmem_error(KMERR_BADADDR, cp, buf);
1782 		return;
1783 	}
1784 
1785 	if (KMEM_SLAB_OFFSET(sp, buf) == sp->slab_stuck_offset) {
1786 		/*
1787 		 * If this is the buffer that prevented the consolidator from
1788 		 * clearing the slab, we can reset the slab flags now that the
1789 		 * buffer is freed. (It makes sense to do this in
1790 		 * kmem_cache_free(), where the client gives up ownership of the
1791 		 * buffer, but on the hot path the test is too expensive.)
1792 		 */
1793 		kmem_slab_move_yes(cp, sp, buf);
1794 	}
1795 
1796 	if ((cp->cache_flags & (KMF_AUDIT | KMF_BUFTAG)) == KMF_AUDIT) {
1797 		if (cp->cache_flags & KMF_CONTENTS)
1798 			((kmem_bufctl_audit_t *)bcp)->bc_contents =
1799 			    kmem_log_enter(kmem_content_log, buf,
1800 			    cp->cache_contents);
1801 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1802 	}
1803 
1804 	bcp->bc_next = sp->slab_head;
1805 	sp->slab_head = bcp;
1806 
1807 	cp->cache_bufslab++;
1808 	ASSERT(sp->slab_refcnt >= 1);
1809 
1810 	if (--sp->slab_refcnt == 0) {
1811 		/*
1812 		 * There are no outstanding allocations from this slab,
1813 		 * so we can reclaim the memory.
1814 		 */
1815 		if (sp->slab_chunks == 1) {
1816 			list_remove(&cp->cache_complete_slabs, sp);
1817 			cp->cache_complete_slab_count--;
1818 		} else {
1819 			avl_remove(&cp->cache_partial_slabs, sp);
1820 		}
1821 
1822 		cp->cache_buftotal -= sp->slab_chunks;
1823 		cp->cache_bufslab -= sp->slab_chunks;
1824 		/*
1825 		 * Defer releasing the slab to the virtual memory subsystem
1826 		 * while there is a pending move callback, since we guarantee
1827 		 * that buffers passed to the move callback have only been
1828 		 * touched by kmem or by the client itself. Since the memory
1829 		 * patterns baddcafe (uninitialized) and deadbeef (freed) both
1830 		 * set at least one of the two lowest order bits, the client can
1831 		 * test those bits in the move callback to determine whether or
1832 		 * not it knows about the buffer (assuming that the client also
1833 		 * sets one of those low order bits whenever it frees a buffer).
1834 		 */
1835 		if (cp->cache_defrag == NULL ||
1836 		    (avl_is_empty(&cp->cache_defrag->kmd_moves_pending) &&
1837 		    !(sp->slab_flags & KMEM_SLAB_MOVE_PENDING))) {
1838 			cp->cache_slab_destroy++;
1839 			mutex_exit(&cp->cache_lock);
1840 			kmem_slab_destroy(cp, sp);
1841 		} else {
1842 			list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
1843 			/*
1844 			 * Slabs are inserted at both ends of the deadlist to
1845 			 * distinguish between slabs freed while move callbacks
1846 			 * are pending (list head) and a slab freed while the
1847 			 * lock is dropped in kmem_move_buffers() (list tail) so
1848 			 * that in both cases slab_destroy() is called from the
1849 			 * right context.
1850 			 */
1851 			if (sp->slab_flags & KMEM_SLAB_MOVE_PENDING) {
1852 				list_insert_tail(deadlist, sp);
1853 			} else {
1854 				list_insert_head(deadlist, sp);
1855 			}
1856 			cp->cache_defrag->kmd_deadcount++;
1857 			mutex_exit(&cp->cache_lock);
1858 		}
1859 		return;
1860 	}
1861 
1862 	if (bcp->bc_next == NULL) {
1863 		/* Transition the slab from completely allocated to partial. */
1864 		ASSERT(sp->slab_refcnt == (sp->slab_chunks - 1));
1865 		ASSERT(sp->slab_chunks > 1);
1866 		list_remove(&cp->cache_complete_slabs, sp);
1867 		cp->cache_complete_slab_count--;
1868 		avl_add(&cp->cache_partial_slabs, sp);
1869 	} else {
1870 #ifdef	DEBUG
1871 		if (avl_update_gt(&cp->cache_partial_slabs, sp)) {
1872 			KMEM_STAT_ADD(kmem_move_stats.kms_avl_update);
1873 		} else {
1874 			KMEM_STAT_ADD(kmem_move_stats.kms_avl_noupdate);
1875 		}
1876 #else
1877 		(void) avl_update_gt(&cp->cache_partial_slabs, sp);
1878 #endif
1879 	}
1880 
1881 	ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) ==
1882 	    (cp->cache_complete_slab_count +
1883 	    avl_numnodes(&cp->cache_partial_slabs) +
1884 	    (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount)));
1885 	mutex_exit(&cp->cache_lock);
1886 }
1887 
1888 /*
1889  * Return -1 if kmem_error, 1 if constructor fails, 0 if successful.
1890  */
1891 static int
1892 kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct,
1893     caddr_t caller)
1894 {
1895 	kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1896 	kmem_bufctl_audit_t *bcp = (kmem_bufctl_audit_t *)btp->bt_bufctl;
1897 	uint32_t mtbf;
1898 
1899 	if (btp->bt_bxstat != ((intptr_t)bcp ^ KMEM_BUFTAG_FREE)) {
1900 		kmem_error(KMERR_BADBUFTAG, cp, buf);
1901 		return (-1);
1902 	}
1903 
1904 	btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_ALLOC;
1905 
1906 	if ((cp->cache_flags & KMF_HASH) && bcp->bc_addr != buf) {
1907 		kmem_error(KMERR_BADBUFCTL, cp, buf);
1908 		return (-1);
1909 	}
1910 
1911 	if (cp->cache_flags & KMF_DEADBEEF) {
1912 		if (!construct && (cp->cache_flags & KMF_LITE)) {
1913 			if (*(uint64_t *)buf != KMEM_FREE_PATTERN) {
1914 				kmem_error(KMERR_MODIFIED, cp, buf);
1915 				return (-1);
1916 			}
1917 			if (cp->cache_constructor != NULL)
1918 				*(uint64_t *)buf = btp->bt_redzone;
1919 			else
1920 				*(uint64_t *)buf = KMEM_UNINITIALIZED_PATTERN;
1921 		} else {
1922 			construct = 1;
1923 			if (verify_and_copy_pattern(KMEM_FREE_PATTERN,
1924 			    KMEM_UNINITIALIZED_PATTERN, buf,
1925 			    cp->cache_verify)) {
1926 				kmem_error(KMERR_MODIFIED, cp, buf);
1927 				return (-1);
1928 			}
1929 		}
1930 	}
1931 	btp->bt_redzone = KMEM_REDZONE_PATTERN;
1932 
1933 	if ((mtbf = kmem_mtbf | cp->cache_mtbf) != 0 &&
1934 	    gethrtime() % mtbf == 0 &&
1935 	    (kmflag & (KM_NOSLEEP | KM_PANIC)) == KM_NOSLEEP) {
1936 		kmem_log_event(kmem_failure_log, cp, NULL, NULL);
1937 		if (!construct && cp->cache_destructor != NULL)
1938 			cp->cache_destructor(buf, cp->cache_private);
1939 	} else {
1940 		mtbf = 0;
1941 	}
1942 
1943 	if (mtbf || (construct && cp->cache_constructor != NULL &&
1944 	    cp->cache_constructor(buf, cp->cache_private, kmflag) != 0)) {
1945 		atomic_add_64(&cp->cache_alloc_fail, 1);
1946 		btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1947 		if (cp->cache_flags & KMF_DEADBEEF)
1948 			copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1949 		kmem_slab_free(cp, buf);
1950 		return (1);
1951 	}
1952 
1953 	if (cp->cache_flags & KMF_AUDIT) {
1954 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1955 	}
1956 
1957 	if ((cp->cache_flags & KMF_LITE) &&
1958 	    !(cp->cache_cflags & KMC_KMEM_ALLOC)) {
1959 		KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller);
1960 	}
1961 
1962 	return (0);
1963 }
1964 
1965 static int
1966 kmem_cache_free_debug(kmem_cache_t *cp, void *buf, caddr_t caller)
1967 {
1968 	kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1969 	kmem_bufctl_audit_t *bcp = (kmem_bufctl_audit_t *)btp->bt_bufctl;
1970 	kmem_slab_t *sp;
1971 
1972 	if (btp->bt_bxstat != ((intptr_t)bcp ^ KMEM_BUFTAG_ALLOC)) {
1973 		if (btp->bt_bxstat == ((intptr_t)bcp ^ KMEM_BUFTAG_FREE)) {
1974 			kmem_error(KMERR_DUPFREE, cp, buf);
1975 			return (-1);
1976 		}
1977 		sp = kmem_findslab(cp, buf);
1978 		if (sp == NULL || sp->slab_cache != cp)
1979 			kmem_error(KMERR_BADADDR, cp, buf);
1980 		else
1981 			kmem_error(KMERR_REDZONE, cp, buf);
1982 		return (-1);
1983 	}
1984 
1985 	btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1986 
1987 	if ((cp->cache_flags & KMF_HASH) && bcp->bc_addr != buf) {
1988 		kmem_error(KMERR_BADBUFCTL, cp, buf);
1989 		return (-1);
1990 	}
1991 
1992 	if (btp->bt_redzone != KMEM_REDZONE_PATTERN) {
1993 		kmem_error(KMERR_REDZONE, cp, buf);
1994 		return (-1);
1995 	}
1996 
1997 	if (cp->cache_flags & KMF_AUDIT) {
1998 		if (cp->cache_flags & KMF_CONTENTS)
1999 			bcp->bc_contents = kmem_log_enter(kmem_content_log,
2000 			    buf, cp->cache_contents);
2001 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
2002 	}
2003 
2004 	if ((cp->cache_flags & KMF_LITE) &&
2005 	    !(cp->cache_cflags & KMC_KMEM_ALLOC)) {
2006 		KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller);
2007 	}
2008 
2009 	if (cp->cache_flags & KMF_DEADBEEF) {
2010 		if (cp->cache_flags & KMF_LITE)
2011 			btp->bt_redzone = *(uint64_t *)buf;
2012 		else if (cp->cache_destructor != NULL)
2013 			cp->cache_destructor(buf, cp->cache_private);
2014 
2015 		copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
2016 	}
2017 
2018 	return (0);
2019 }
2020 
2021 /*
2022  * Free each object in magazine mp to cp's slab layer, and free mp itself.
2023  */
2024 static void
2025 kmem_magazine_destroy(kmem_cache_t *cp, kmem_magazine_t *mp, int nrounds)
2026 {
2027 	int round;
2028 
2029 	ASSERT(!list_link_active(&cp->cache_link) ||
2030 	    taskq_member(kmem_taskq, curthread));
2031 
2032 	for (round = 0; round < nrounds; round++) {
2033 		void *buf = mp->mag_round[round];
2034 
2035 		if (cp->cache_flags & KMF_DEADBEEF) {
2036 			if (verify_pattern(KMEM_FREE_PATTERN, buf,
2037 			    cp->cache_verify) != NULL) {
2038 				kmem_error(KMERR_MODIFIED, cp, buf);
2039 				continue;
2040 			}
2041 			if ((cp->cache_flags & KMF_LITE) &&
2042 			    cp->cache_destructor != NULL) {
2043 				kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2044 				*(uint64_t *)buf = btp->bt_redzone;
2045 				cp->cache_destructor(buf, cp->cache_private);
2046 				*(uint64_t *)buf = KMEM_FREE_PATTERN;
2047 			}
2048 		} else if (cp->cache_destructor != NULL) {
2049 			cp->cache_destructor(buf, cp->cache_private);
2050 		}
2051 
2052 		kmem_slab_free(cp, buf);
2053 	}
2054 	ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2055 	kmem_cache_free(cp->cache_magtype->mt_cache, mp);
2056 }
2057 
2058 /*
2059  * Allocate a magazine from the depot.
2060  */
2061 static kmem_magazine_t *
2062 kmem_depot_alloc(kmem_cache_t *cp, kmem_maglist_t *mlp)
2063 {
2064 	kmem_magazine_t *mp;
2065 
2066 	/*
2067 	 * If we can't get the depot lock without contention,
2068 	 * update our contention count.  We use the depot
2069 	 * contention rate to determine whether we need to
2070 	 * increase the magazine size for better scalability.
2071 	 */
2072 	if (!mutex_tryenter(&cp->cache_depot_lock)) {
2073 		mutex_enter(&cp->cache_depot_lock);
2074 		cp->cache_depot_contention++;
2075 	}
2076 
2077 	if ((mp = mlp->ml_list) != NULL) {
2078 		ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2079 		mlp->ml_list = mp->mag_next;
2080 		if (--mlp->ml_total < mlp->ml_min)
2081 			mlp->ml_min = mlp->ml_total;
2082 		mlp->ml_alloc++;
2083 	}
2084 
2085 	mutex_exit(&cp->cache_depot_lock);
2086 
2087 	return (mp);
2088 }
2089 
2090 /*
2091  * Free a magazine to the depot.
2092  */
2093 static void
2094 kmem_depot_free(kmem_cache_t *cp, kmem_maglist_t *mlp, kmem_magazine_t *mp)
2095 {
2096 	mutex_enter(&cp->cache_depot_lock);
2097 	ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2098 	mp->mag_next = mlp->ml_list;
2099 	mlp->ml_list = mp;
2100 	mlp->ml_total++;
2101 	mutex_exit(&cp->cache_depot_lock);
2102 }
2103 
2104 /*
2105  * Update the working set statistics for cp's depot.
2106  */
2107 static void
2108 kmem_depot_ws_update(kmem_cache_t *cp)
2109 {
2110 	mutex_enter(&cp->cache_depot_lock);
2111 	cp->cache_full.ml_reaplimit = cp->cache_full.ml_min;
2112 	cp->cache_full.ml_min = cp->cache_full.ml_total;
2113 	cp->cache_empty.ml_reaplimit = cp->cache_empty.ml_min;
2114 	cp->cache_empty.ml_min = cp->cache_empty.ml_total;
2115 	mutex_exit(&cp->cache_depot_lock);
2116 }
2117 
2118 /*
2119  * Reap all magazines that have fallen out of the depot's working set.
2120  */
2121 static void
2122 kmem_depot_ws_reap(kmem_cache_t *cp)
2123 {
2124 	long reap;
2125 	kmem_magazine_t *mp;
2126 
2127 	ASSERT(!list_link_active(&cp->cache_link) ||
2128 	    taskq_member(kmem_taskq, curthread));
2129 
2130 	reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
2131 	while (reap-- && (mp = kmem_depot_alloc(cp, &cp->cache_full)) != NULL)
2132 		kmem_magazine_destroy(cp, mp, cp->cache_magtype->mt_magsize);
2133 
2134 	reap = MIN(cp->cache_empty.ml_reaplimit, cp->cache_empty.ml_min);
2135 	while (reap-- && (mp = kmem_depot_alloc(cp, &cp->cache_empty)) != NULL)
2136 		kmem_magazine_destroy(cp, mp, 0);
2137 }
2138 
2139 static void
2140 kmem_cpu_reload(kmem_cpu_cache_t *ccp, kmem_magazine_t *mp, int rounds)
2141 {
2142 	ASSERT((ccp->cc_loaded == NULL && ccp->cc_rounds == -1) ||
2143 	    (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize));
2144 	ASSERT(ccp->cc_magsize > 0);
2145 
2146 	ccp->cc_ploaded = ccp->cc_loaded;
2147 	ccp->cc_prounds = ccp->cc_rounds;
2148 	ccp->cc_loaded = mp;
2149 	ccp->cc_rounds = rounds;
2150 }
2151 
2152 /*
2153  * Allocate a constructed object from cache cp.
2154  */
2155 void *
2156 kmem_cache_alloc(kmem_cache_t *cp, int kmflag)
2157 {
2158 	kmem_cpu_cache_t *ccp = KMEM_CPU_CACHE(cp);
2159 	kmem_magazine_t *fmp;
2160 	void *buf;
2161 
2162 	mutex_enter(&ccp->cc_lock);
2163 	for (;;) {
2164 		/*
2165 		 * If there's an object available in the current CPU's
2166 		 * loaded magazine, just take it and return.
2167 		 */
2168 		if (ccp->cc_rounds > 0) {
2169 			buf = ccp->cc_loaded->mag_round[--ccp->cc_rounds];
2170 			ccp->cc_alloc++;
2171 			mutex_exit(&ccp->cc_lock);
2172 			if ((ccp->cc_flags & KMF_BUFTAG) &&
2173 			    kmem_cache_alloc_debug(cp, buf, kmflag, 0,
2174 			    caller()) != 0) {
2175 				if (kmflag & KM_NOSLEEP)
2176 					return (NULL);
2177 				mutex_enter(&ccp->cc_lock);
2178 				continue;
2179 			}
2180 			return (buf);
2181 		}
2182 
2183 		/*
2184 		 * The loaded magazine is empty.  If the previously loaded
2185 		 * magazine was full, exchange them and try again.
2186 		 */
2187 		if (ccp->cc_prounds > 0) {
2188 			kmem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
2189 			continue;
2190 		}
2191 
2192 		/*
2193 		 * If the magazine layer is disabled, break out now.
2194 		 */
2195 		if (ccp->cc_magsize == 0)
2196 			break;
2197 
2198 		/*
2199 		 * Try to get a full magazine from the depot.
2200 		 */
2201 		fmp = kmem_depot_alloc(cp, &cp->cache_full);
2202 		if (fmp != NULL) {
2203 			if (ccp->cc_ploaded != NULL)
2204 				kmem_depot_free(cp, &cp->cache_empty,
2205 				    ccp->cc_ploaded);
2206 			kmem_cpu_reload(ccp, fmp, ccp->cc_magsize);
2207 			continue;
2208 		}
2209 
2210 		/*
2211 		 * There are no full magazines in the depot,
2212 		 * so fall through to the slab layer.
2213 		 */
2214 		break;
2215 	}
2216 	mutex_exit(&ccp->cc_lock);
2217 
2218 	/*
2219 	 * We couldn't allocate a constructed object from the magazine layer,
2220 	 * so get a raw buffer from the slab layer and apply its constructor.
2221 	 */
2222 	buf = kmem_slab_alloc(cp, kmflag);
2223 
2224 	if (buf == NULL)
2225 		return (NULL);
2226 
2227 	if (cp->cache_flags & KMF_BUFTAG) {
2228 		/*
2229 		 * Make kmem_cache_alloc_debug() apply the constructor for us.
2230 		 */
2231 		int rc = kmem_cache_alloc_debug(cp, buf, kmflag, 1, caller());
2232 		if (rc != 0) {
2233 			if (kmflag & KM_NOSLEEP)
2234 				return (NULL);
2235 			/*
2236 			 * kmem_cache_alloc_debug() detected corruption
2237 			 * but didn't panic (kmem_panic <= 0). We should not be
2238 			 * here because the constructor failed (indicated by a
2239 			 * return code of 1). Try again.
2240 			 */
2241 			ASSERT(rc == -1);
2242 			return (kmem_cache_alloc(cp, kmflag));
2243 		}
2244 		return (buf);
2245 	}
2246 
2247 	if (cp->cache_constructor != NULL &&
2248 	    cp->cache_constructor(buf, cp->cache_private, kmflag) != 0) {
2249 		atomic_add_64(&cp->cache_alloc_fail, 1);
2250 		kmem_slab_free(cp, buf);
2251 		return (NULL);
2252 	}
2253 
2254 	return (buf);
2255 }
2256 
2257 /*
2258  * The freed argument tells whether or not kmem_cache_free_debug() has already
2259  * been called so that we can avoid the duplicate free error. For example, a
2260  * buffer on a magazine has already been freed by the client but is still
2261  * constructed.
2262  */
2263 static void
2264 kmem_slab_free_constructed(kmem_cache_t *cp, void *buf, boolean_t freed)
2265 {
2266 	if (!freed && (cp->cache_flags & KMF_BUFTAG))
2267 		if (kmem_cache_free_debug(cp, buf, caller()) == -1)
2268 			return;
2269 
2270 	/*
2271 	 * Note that if KMF_DEADBEEF is in effect and KMF_LITE is not,
2272 	 * kmem_cache_free_debug() will have already applied the destructor.
2273 	 */
2274 	if ((cp->cache_flags & (KMF_DEADBEEF | KMF_LITE)) != KMF_DEADBEEF &&
2275 	    cp->cache_destructor != NULL) {
2276 		if (cp->cache_flags & KMF_DEADBEEF) {	/* KMF_LITE implied */
2277 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2278 			*(uint64_t *)buf = btp->bt_redzone;
2279 			cp->cache_destructor(buf, cp->cache_private);
2280 			*(uint64_t *)buf = KMEM_FREE_PATTERN;
2281 		} else {
2282 			cp->cache_destructor(buf, cp->cache_private);
2283 		}
2284 	}
2285 
2286 	kmem_slab_free(cp, buf);
2287 }
2288 
2289 /*
2290  * Free a constructed object to cache cp.
2291  */
2292 void
2293 kmem_cache_free(kmem_cache_t *cp, void *buf)
2294 {
2295 	kmem_cpu_cache_t *ccp = KMEM_CPU_CACHE(cp);
2296 	kmem_magazine_t *emp;
2297 	kmem_magtype_t *mtp;
2298 
2299 	/*
2300 	 * The client must not free either of the buffers passed to the move
2301 	 * callback function.
2302 	 */
2303 	ASSERT(cp->cache_defrag == NULL ||
2304 	    cp->cache_defrag->kmd_thread != curthread ||
2305 	    (buf != cp->cache_defrag->kmd_from_buf &&
2306 	    buf != cp->cache_defrag->kmd_to_buf));
2307 
2308 	if (ccp->cc_flags & KMF_BUFTAG)
2309 		if (kmem_cache_free_debug(cp, buf, caller()) == -1)
2310 			return;
2311 
2312 	mutex_enter(&ccp->cc_lock);
2313 	for (;;) {
2314 		/*
2315 		 * If there's a slot available in the current CPU's
2316 		 * loaded magazine, just put the object there and return.
2317 		 */
2318 		if ((uint_t)ccp->cc_rounds < ccp->cc_magsize) {
2319 			ccp->cc_loaded->mag_round[ccp->cc_rounds++] = buf;
2320 			ccp->cc_free++;
2321 			mutex_exit(&ccp->cc_lock);
2322 			return;
2323 		}
2324 
2325 		/*
2326 		 * The loaded magazine is full.  If the previously loaded
2327 		 * magazine was empty, exchange them and try again.
2328 		 */
2329 		if (ccp->cc_prounds == 0) {
2330 			kmem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
2331 			continue;
2332 		}
2333 
2334 		/*
2335 		 * If the magazine layer is disabled, break out now.
2336 		 */
2337 		if (ccp->cc_magsize == 0)
2338 			break;
2339 
2340 		/*
2341 		 * Try to get an empty magazine from the depot.
2342 		 */
2343 		emp = kmem_depot_alloc(cp, &cp->cache_empty);
2344 		if (emp != NULL) {
2345 			if (ccp->cc_ploaded != NULL)
2346 				kmem_depot_free(cp, &cp->cache_full,
2347 				    ccp->cc_ploaded);
2348 			kmem_cpu_reload(ccp, emp, 0);
2349 			continue;
2350 		}
2351 
2352 		/*
2353 		 * There are no empty magazines in the depot,
2354 		 * so try to allocate a new one.  We must drop all locks
2355 		 * across kmem_cache_alloc() because lower layers may
2356 		 * attempt to allocate from this cache.
2357 		 */
2358 		mtp = cp->cache_magtype;
2359 		mutex_exit(&ccp->cc_lock);
2360 		emp = kmem_cache_alloc(mtp->mt_cache, KM_NOSLEEP);
2361 		mutex_enter(&ccp->cc_lock);
2362 
2363 		if (emp != NULL) {
2364 			/*
2365 			 * We successfully allocated an empty magazine.
2366 			 * However, we had to drop ccp->cc_lock to do it,
2367 			 * so the cache's magazine size may have changed.
2368 			 * If so, free the magazine and try again.
2369 			 */
2370 			if (ccp->cc_magsize != mtp->mt_magsize) {
2371 				mutex_exit(&ccp->cc_lock);
2372 				kmem_cache_free(mtp->mt_cache, emp);
2373 				mutex_enter(&ccp->cc_lock);
2374 				continue;
2375 			}
2376 
2377 			/*
2378 			 * We got a magazine of the right size.  Add it to
2379 			 * the depot and try the whole dance again.
2380 			 */
2381 			kmem_depot_free(cp, &cp->cache_empty, emp);
2382 			continue;
2383 		}
2384 
2385 		/*
2386 		 * We couldn't allocate an empty magazine,
2387 		 * so fall through to the slab layer.
2388 		 */
2389 		break;
2390 	}
2391 	mutex_exit(&ccp->cc_lock);
2392 
2393 	/*
2394 	 * We couldn't free our constructed object to the magazine layer,
2395 	 * so apply its destructor and free it to the slab layer.
2396 	 */
2397 	kmem_slab_free_constructed(cp, buf, B_TRUE);
2398 }
2399 
2400 void *
2401 kmem_zalloc(size_t size, int kmflag)
2402 {
2403 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2404 	void *buf;
2405 
2406 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2407 		kmem_cache_t *cp = kmem_alloc_table[index];
2408 		buf = kmem_cache_alloc(cp, kmflag);
2409 		if (buf != NULL) {
2410 			if (cp->cache_flags & KMF_BUFTAG) {
2411 				kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2412 				((uint8_t *)buf)[size] = KMEM_REDZONE_BYTE;
2413 				((uint32_t *)btp)[1] = KMEM_SIZE_ENCODE(size);
2414 
2415 				if (cp->cache_flags & KMF_LITE) {
2416 					KMEM_BUFTAG_LITE_ENTER(btp,
2417 					    kmem_lite_count, caller());
2418 				}
2419 			}
2420 			bzero(buf, size);
2421 		}
2422 	} else {
2423 		buf = kmem_alloc(size, kmflag);
2424 		if (buf != NULL)
2425 			bzero(buf, size);
2426 	}
2427 	return (buf);
2428 }
2429 
2430 void *
2431 kmem_alloc(size_t size, int kmflag)
2432 {
2433 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2434 	void *buf;
2435 
2436 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2437 		kmem_cache_t *cp = kmem_alloc_table[index];
2438 		buf = kmem_cache_alloc(cp, kmflag);
2439 		if ((cp->cache_flags & KMF_BUFTAG) && buf != NULL) {
2440 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2441 			((uint8_t *)buf)[size] = KMEM_REDZONE_BYTE;
2442 			((uint32_t *)btp)[1] = KMEM_SIZE_ENCODE(size);
2443 
2444 			if (cp->cache_flags & KMF_LITE) {
2445 				KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count,
2446 				    caller());
2447 			}
2448 		}
2449 		return (buf);
2450 	}
2451 	if (size == 0)
2452 		return (NULL);
2453 	buf = vmem_alloc(kmem_oversize_arena, size, kmflag & KM_VMFLAGS);
2454 	if (buf == NULL)
2455 		kmem_log_event(kmem_failure_log, NULL, NULL, (void *)size);
2456 	return (buf);
2457 }
2458 
2459 void
2460 kmem_free(void *buf, size_t size)
2461 {
2462 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2463 
2464 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2465 		kmem_cache_t *cp = kmem_alloc_table[index];
2466 		if (cp->cache_flags & KMF_BUFTAG) {
2467 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2468 			uint32_t *ip = (uint32_t *)btp;
2469 			if (ip[1] != KMEM_SIZE_ENCODE(size)) {
2470 				if (*(uint64_t *)buf == KMEM_FREE_PATTERN) {
2471 					kmem_error(KMERR_DUPFREE, cp, buf);
2472 					return;
2473 				}
2474 				if (KMEM_SIZE_VALID(ip[1])) {
2475 					ip[0] = KMEM_SIZE_ENCODE(size);
2476 					kmem_error(KMERR_BADSIZE, cp, buf);
2477 				} else {
2478 					kmem_error(KMERR_REDZONE, cp, buf);
2479 				}
2480 				return;
2481 			}
2482 			if (((uint8_t *)buf)[size] != KMEM_REDZONE_BYTE) {
2483 				kmem_error(KMERR_REDZONE, cp, buf);
2484 				return;
2485 			}
2486 			btp->bt_redzone = KMEM_REDZONE_PATTERN;
2487 			if (cp->cache_flags & KMF_LITE) {
2488 				KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count,
2489 				    caller());
2490 			}
2491 		}
2492 		kmem_cache_free(cp, buf);
2493 	} else {
2494 		if (buf == NULL && size == 0)
2495 			return;
2496 		vmem_free(kmem_oversize_arena, buf, size);
2497 	}
2498 }
2499 
2500 void *
2501 kmem_firewall_va_alloc(vmem_t *vmp, size_t size, int vmflag)
2502 {
2503 	size_t realsize = size + vmp->vm_quantum;
2504 	void *addr;
2505 
2506 	/*
2507 	 * Annoying edge case: if 'size' is just shy of ULONG_MAX, adding
2508 	 * vm_quantum will cause integer wraparound.  Check for this, and
2509 	 * blow off the firewall page in this case.  Note that such a
2510 	 * giant allocation (the entire kernel address space) can never
2511 	 * be satisfied, so it will either fail immediately (VM_NOSLEEP)
2512 	 * or sleep forever (VM_SLEEP).  Thus, there is no need for a
2513 	 * corresponding check in kmem_firewall_va_free().
2514 	 */
2515 	if (realsize < size)
2516 		realsize = size;
2517 
2518 	/*
2519 	 * While boot still owns resource management, make sure that this
2520 	 * redzone virtual address allocation is properly accounted for in
2521 	 * OBPs "virtual-memory" "available" lists because we're
2522 	 * effectively claiming them for a red zone.  If we don't do this,
2523 	 * the available lists become too fragmented and too large for the
2524 	 * current boot/kernel memory list interface.
2525 	 */
2526 	addr = vmem_alloc(vmp, realsize, vmflag | VM_NEXTFIT);
2527 
2528 	if (addr != NULL && kvseg.s_base == NULL && realsize != size)
2529 		(void) boot_virt_alloc((char *)addr + size, vmp->vm_quantum);
2530 
2531 	return (addr);
2532 }
2533 
2534 void
2535 kmem_firewall_va_free(vmem_t *vmp, void *addr, size_t size)
2536 {
2537 	ASSERT((kvseg.s_base == NULL ?
2538 	    va_to_pfn((char *)addr + size) :
2539 	    hat_getpfnum(kas.a_hat, (caddr_t)addr + size)) == PFN_INVALID);
2540 
2541 	vmem_free(vmp, addr, size + vmp->vm_quantum);
2542 }
2543 
2544 /*
2545  * Try to allocate at least `size' bytes of memory without sleeping or
2546  * panicking. Return actual allocated size in `asize'. If allocation failed,
2547  * try final allocation with sleep or panic allowed.
2548  */
2549 void *
2550 kmem_alloc_tryhard(size_t size, size_t *asize, int kmflag)
2551 {
2552 	void *p;
2553 
2554 	*asize = P2ROUNDUP(size, KMEM_ALIGN);
2555 	do {
2556 		p = kmem_alloc(*asize, (kmflag | KM_NOSLEEP) & ~KM_PANIC);
2557 		if (p != NULL)
2558 			return (p);
2559 		*asize += KMEM_ALIGN;
2560 	} while (*asize <= PAGESIZE);
2561 
2562 	*asize = P2ROUNDUP(size, KMEM_ALIGN);
2563 	return (kmem_alloc(*asize, kmflag));
2564 }
2565 
2566 /*
2567  * Reclaim all unused memory from a cache.
2568  */
2569 static void
2570 kmem_cache_reap(kmem_cache_t *cp)
2571 {
2572 	ASSERT(taskq_member(kmem_taskq, curthread));
2573 
2574 	/*
2575 	 * Ask the cache's owner to free some memory if possible.
2576 	 * The idea is to handle things like the inode cache, which
2577 	 * typically sits on a bunch of memory that it doesn't truly
2578 	 * *need*.  Reclaim policy is entirely up to the owner; this
2579 	 * callback is just an advisory plea for help.
2580 	 */
2581 	if (cp->cache_reclaim != NULL) {
2582 		long delta;
2583 
2584 		/*
2585 		 * Reclaimed memory should be reapable (not included in the
2586 		 * depot's working set).
2587 		 */
2588 		delta = cp->cache_full.ml_total;
2589 		cp->cache_reclaim(cp->cache_private);
2590 		delta = cp->cache_full.ml_total - delta;
2591 		if (delta > 0) {
2592 			mutex_enter(&cp->cache_depot_lock);
2593 			cp->cache_full.ml_reaplimit += delta;
2594 			cp->cache_full.ml_min += delta;
2595 			mutex_exit(&cp->cache_depot_lock);
2596 		}
2597 	}
2598 
2599 	kmem_depot_ws_reap(cp);
2600 
2601 	if (cp->cache_defrag != NULL && !kmem_move_noreap) {
2602 		kmem_cache_defrag(cp);
2603 	}
2604 }
2605 
2606 static void
2607 kmem_reap_timeout(void *flag_arg)
2608 {
2609 	uint32_t *flag = (uint32_t *)flag_arg;
2610 
2611 	ASSERT(flag == &kmem_reaping || flag == &kmem_reaping_idspace);
2612 	*flag = 0;
2613 }
2614 
2615 static void
2616 kmem_reap_done(void *flag)
2617 {
2618 	(void) timeout(kmem_reap_timeout, flag, kmem_reap_interval);
2619 }
2620 
2621 static void
2622 kmem_reap_start(void *flag)
2623 {
2624 	ASSERT(flag == &kmem_reaping || flag == &kmem_reaping_idspace);
2625 
2626 	if (flag == &kmem_reaping) {
2627 		kmem_cache_applyall(kmem_cache_reap, kmem_taskq, TQ_NOSLEEP);
2628 		/*
2629 		 * if we have segkp under heap, reap segkp cache.
2630 		 */
2631 		if (segkp_fromheap)
2632 			segkp_cache_free();
2633 	}
2634 	else
2635 		kmem_cache_applyall_id(kmem_cache_reap, kmem_taskq, TQ_NOSLEEP);
2636 
2637 	/*
2638 	 * We use taskq_dispatch() to schedule a timeout to clear
2639 	 * the flag so that kmem_reap() becomes self-throttling:
2640 	 * we won't reap again until the current reap completes *and*
2641 	 * at least kmem_reap_interval ticks have elapsed.
2642 	 */
2643 	if (!taskq_dispatch(kmem_taskq, kmem_reap_done, flag, TQ_NOSLEEP))
2644 		kmem_reap_done(flag);
2645 }
2646 
2647 static void
2648 kmem_reap_common(void *flag_arg)
2649 {
2650 	uint32_t *flag = (uint32_t *)flag_arg;
2651 
2652 	if (MUTEX_HELD(&kmem_cache_lock) || kmem_taskq == NULL ||
2653 	    cas32(flag, 0, 1) != 0)
2654 		return;
2655 
2656 	/*
2657 	 * It may not be kosher to do memory allocation when a reap is called
2658 	 * is called (for example, if vmem_populate() is in the call chain).
2659 	 * So we start the reap going with a TQ_NOALLOC dispatch.  If the
2660 	 * dispatch fails, we reset the flag, and the next reap will try again.
2661 	 */
2662 	if (!taskq_dispatch(kmem_taskq, kmem_reap_start, flag, TQ_NOALLOC))
2663 		*flag = 0;
2664 }
2665 
2666 /*
2667  * Reclaim all unused memory from all caches.  Called from the VM system
2668  * when memory gets tight.
2669  */
2670 void
2671 kmem_reap(void)
2672 {
2673 	kmem_reap_common(&kmem_reaping);
2674 }
2675 
2676 /*
2677  * Reclaim all unused memory from identifier arenas, called when a vmem
2678  * arena not back by memory is exhausted.  Since reaping memory-backed caches
2679  * cannot help with identifier exhaustion, we avoid both a large amount of
2680  * work and unwanted side-effects from reclaim callbacks.
2681  */
2682 void
2683 kmem_reap_idspace(void)
2684 {
2685 	kmem_reap_common(&kmem_reaping_idspace);
2686 }
2687 
2688 /*
2689  * Purge all magazines from a cache and set its magazine limit to zero.
2690  * All calls are serialized by the kmem_taskq lock, except for the final
2691  * call from kmem_cache_destroy().
2692  */
2693 static void
2694 kmem_cache_magazine_purge(kmem_cache_t *cp)
2695 {
2696 	kmem_cpu_cache_t *ccp;
2697 	kmem_magazine_t *mp, *pmp;
2698 	int rounds, prounds, cpu_seqid;
2699 
2700 	ASSERT(!list_link_active(&cp->cache_link) ||
2701 	    taskq_member(kmem_taskq, curthread));
2702 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
2703 
2704 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2705 		ccp = &cp->cache_cpu[cpu_seqid];
2706 
2707 		mutex_enter(&ccp->cc_lock);
2708 		mp = ccp->cc_loaded;
2709 		pmp = ccp->cc_ploaded;
2710 		rounds = ccp->cc_rounds;
2711 		prounds = ccp->cc_prounds;
2712 		ccp->cc_loaded = NULL;
2713 		ccp->cc_ploaded = NULL;
2714 		ccp->cc_rounds = -1;
2715 		ccp->cc_prounds = -1;
2716 		ccp->cc_magsize = 0;
2717 		mutex_exit(&ccp->cc_lock);
2718 
2719 		if (mp)
2720 			kmem_magazine_destroy(cp, mp, rounds);
2721 		if (pmp)
2722 			kmem_magazine_destroy(cp, pmp, prounds);
2723 	}
2724 
2725 	/*
2726 	 * Updating the working set statistics twice in a row has the
2727 	 * effect of setting the working set size to zero, so everything
2728 	 * is eligible for reaping.
2729 	 */
2730 	kmem_depot_ws_update(cp);
2731 	kmem_depot_ws_update(cp);
2732 
2733 	kmem_depot_ws_reap(cp);
2734 }
2735 
2736 /*
2737  * Enable per-cpu magazines on a cache.
2738  */
2739 static void
2740 kmem_cache_magazine_enable(kmem_cache_t *cp)
2741 {
2742 	int cpu_seqid;
2743 
2744 	if (cp->cache_flags & KMF_NOMAGAZINE)
2745 		return;
2746 
2747 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2748 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2749 		mutex_enter(&ccp->cc_lock);
2750 		ccp->cc_magsize = cp->cache_magtype->mt_magsize;
2751 		mutex_exit(&ccp->cc_lock);
2752 	}
2753 
2754 }
2755 
2756 /*
2757  * Reap (almost) everything right now.  See kmem_cache_magazine_purge()
2758  * for explanation of the back-to-back kmem_depot_ws_update() calls.
2759  */
2760 void
2761 kmem_cache_reap_now(kmem_cache_t *cp)
2762 {
2763 	ASSERT(list_link_active(&cp->cache_link));
2764 
2765 	kmem_depot_ws_update(cp);
2766 	kmem_depot_ws_update(cp);
2767 
2768 	(void) taskq_dispatch(kmem_taskq,
2769 	    (task_func_t *)kmem_depot_ws_reap, cp, TQ_SLEEP);
2770 	taskq_wait(kmem_taskq);
2771 }
2772 
2773 /*
2774  * Recompute a cache's magazine size.  The trade-off is that larger magazines
2775  * provide a higher transfer rate with the depot, while smaller magazines
2776  * reduce memory consumption.  Magazine resizing is an expensive operation;
2777  * it should not be done frequently.
2778  *
2779  * Changes to the magazine size are serialized by the kmem_taskq lock.
2780  *
2781  * Note: at present this only grows the magazine size.  It might be useful
2782  * to allow shrinkage too.
2783  */
2784 static void
2785 kmem_cache_magazine_resize(kmem_cache_t *cp)
2786 {
2787 	kmem_magtype_t *mtp = cp->cache_magtype;
2788 
2789 	ASSERT(taskq_member(kmem_taskq, curthread));
2790 
2791 	if (cp->cache_chunksize < mtp->mt_maxbuf) {
2792 		kmem_cache_magazine_purge(cp);
2793 		mutex_enter(&cp->cache_depot_lock);
2794 		cp->cache_magtype = ++mtp;
2795 		cp->cache_depot_contention_prev =
2796 		    cp->cache_depot_contention + INT_MAX;
2797 		mutex_exit(&cp->cache_depot_lock);
2798 		kmem_cache_magazine_enable(cp);
2799 	}
2800 }
2801 
2802 /*
2803  * Rescale a cache's hash table, so that the table size is roughly the
2804  * cache size.  We want the average lookup time to be extremely small.
2805  */
2806 static void
2807 kmem_hash_rescale(kmem_cache_t *cp)
2808 {
2809 	kmem_bufctl_t **old_table, **new_table, *bcp;
2810 	size_t old_size, new_size, h;
2811 
2812 	ASSERT(taskq_member(kmem_taskq, curthread));
2813 
2814 	new_size = MAX(KMEM_HASH_INITIAL,
2815 	    1 << (highbit(3 * cp->cache_buftotal + 4) - 2));
2816 	old_size = cp->cache_hash_mask + 1;
2817 
2818 	if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
2819 		return;
2820 
2821 	new_table = vmem_alloc(kmem_hash_arena, new_size * sizeof (void *),
2822 	    VM_NOSLEEP);
2823 	if (new_table == NULL)
2824 		return;
2825 	bzero(new_table, new_size * sizeof (void *));
2826 
2827 	mutex_enter(&cp->cache_lock);
2828 
2829 	old_size = cp->cache_hash_mask + 1;
2830 	old_table = cp->cache_hash_table;
2831 
2832 	cp->cache_hash_mask = new_size - 1;
2833 	cp->cache_hash_table = new_table;
2834 	cp->cache_rescale++;
2835 
2836 	for (h = 0; h < old_size; h++) {
2837 		bcp = old_table[h];
2838 		while (bcp != NULL) {
2839 			void *addr = bcp->bc_addr;
2840 			kmem_bufctl_t *next_bcp = bcp->bc_next;
2841 			kmem_bufctl_t **hash_bucket = KMEM_HASH(cp, addr);
2842 			bcp->bc_next = *hash_bucket;
2843 			*hash_bucket = bcp;
2844 			bcp = next_bcp;
2845 		}
2846 	}
2847 
2848 	mutex_exit(&cp->cache_lock);
2849 
2850 	vmem_free(kmem_hash_arena, old_table, old_size * sizeof (void *));
2851 }
2852 
2853 /*
2854  * Perform periodic maintenance on a cache: hash rescaling, depot working-set
2855  * update, magazine resizing, and slab consolidation.
2856  */
2857 static void
2858 kmem_cache_update(kmem_cache_t *cp)
2859 {
2860 	int need_hash_rescale = 0;
2861 	int need_magazine_resize = 0;
2862 
2863 	ASSERT(MUTEX_HELD(&kmem_cache_lock));
2864 
2865 	/*
2866 	 * If the cache has become much larger or smaller than its hash table,
2867 	 * fire off a request to rescale the hash table.
2868 	 */
2869 	mutex_enter(&cp->cache_lock);
2870 
2871 	if ((cp->cache_flags & KMF_HASH) &&
2872 	    (cp->cache_buftotal > (cp->cache_hash_mask << 1) ||
2873 	    (cp->cache_buftotal < (cp->cache_hash_mask >> 1) &&
2874 	    cp->cache_hash_mask > KMEM_HASH_INITIAL)))
2875 		need_hash_rescale = 1;
2876 
2877 	mutex_exit(&cp->cache_lock);
2878 
2879 	/*
2880 	 * Update the depot working set statistics.
2881 	 */
2882 	kmem_depot_ws_update(cp);
2883 
2884 	/*
2885 	 * If there's a lot of contention in the depot,
2886 	 * increase the magazine size.
2887 	 */
2888 	mutex_enter(&cp->cache_depot_lock);
2889 
2890 	if (cp->cache_chunksize < cp->cache_magtype->mt_maxbuf &&
2891 	    (int)(cp->cache_depot_contention -
2892 	    cp->cache_depot_contention_prev) > kmem_depot_contention)
2893 		need_magazine_resize = 1;
2894 
2895 	cp->cache_depot_contention_prev = cp->cache_depot_contention;
2896 
2897 	mutex_exit(&cp->cache_depot_lock);
2898 
2899 	if (need_hash_rescale)
2900 		(void) taskq_dispatch(kmem_taskq,
2901 		    (task_func_t *)kmem_hash_rescale, cp, TQ_NOSLEEP);
2902 
2903 	if (need_magazine_resize)
2904 		(void) taskq_dispatch(kmem_taskq,
2905 		    (task_func_t *)kmem_cache_magazine_resize, cp, TQ_NOSLEEP);
2906 
2907 	if (cp->cache_defrag != NULL)
2908 		(void) taskq_dispatch(kmem_taskq,
2909 		    (task_func_t *)kmem_cache_scan, cp, TQ_NOSLEEP);
2910 }
2911 
2912 static void
2913 kmem_update_timeout(void *dummy)
2914 {
2915 	static void kmem_update(void *);
2916 
2917 	(void) timeout(kmem_update, dummy, kmem_reap_interval);
2918 }
2919 
2920 static void
2921 kmem_update(void *dummy)
2922 {
2923 	kmem_cache_applyall(kmem_cache_update, NULL, TQ_NOSLEEP);
2924 
2925 	/*
2926 	 * We use taskq_dispatch() to reschedule the timeout so that
2927 	 * kmem_update() becomes self-throttling: it won't schedule
2928 	 * new tasks until all previous tasks have completed.
2929 	 */
2930 	if (!taskq_dispatch(kmem_taskq, kmem_update_timeout, dummy, TQ_NOSLEEP))
2931 		kmem_update_timeout(NULL);
2932 }
2933 
2934 static int
2935 kmem_cache_kstat_update(kstat_t *ksp, int rw)
2936 {
2937 	struct kmem_cache_kstat *kmcp = &kmem_cache_kstat;
2938 	kmem_cache_t *cp = ksp->ks_private;
2939 	uint64_t cpu_buf_avail;
2940 	uint64_t buf_avail = 0;
2941 	int cpu_seqid;
2942 
2943 	ASSERT(MUTEX_HELD(&kmem_cache_kstat_lock));
2944 
2945 	if (rw == KSTAT_WRITE)
2946 		return (EACCES);
2947 
2948 	mutex_enter(&cp->cache_lock);
2949 
2950 	kmcp->kmc_alloc_fail.value.ui64		= cp->cache_alloc_fail;
2951 	kmcp->kmc_alloc.value.ui64		= cp->cache_slab_alloc;
2952 	kmcp->kmc_free.value.ui64		= cp->cache_slab_free;
2953 	kmcp->kmc_slab_alloc.value.ui64		= cp->cache_slab_alloc;
2954 	kmcp->kmc_slab_free.value.ui64		= cp->cache_slab_free;
2955 
2956 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2957 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2958 
2959 		mutex_enter(&ccp->cc_lock);
2960 
2961 		cpu_buf_avail = 0;
2962 		if (ccp->cc_rounds > 0)
2963 			cpu_buf_avail += ccp->cc_rounds;
2964 		if (ccp->cc_prounds > 0)
2965 			cpu_buf_avail += ccp->cc_prounds;
2966 
2967 		kmcp->kmc_alloc.value.ui64	+= ccp->cc_alloc;
2968 		kmcp->kmc_free.value.ui64	+= ccp->cc_free;
2969 		buf_avail			+= cpu_buf_avail;
2970 
2971 		mutex_exit(&ccp->cc_lock);
2972 	}
2973 
2974 	mutex_enter(&cp->cache_depot_lock);
2975 
2976 	kmcp->kmc_depot_alloc.value.ui64	= cp->cache_full.ml_alloc;
2977 	kmcp->kmc_depot_free.value.ui64		= cp->cache_empty.ml_alloc;
2978 	kmcp->kmc_depot_contention.value.ui64	= cp->cache_depot_contention;
2979 	kmcp->kmc_full_magazines.value.ui64	= cp->cache_full.ml_total;
2980 	kmcp->kmc_empty_magazines.value.ui64	= cp->cache_empty.ml_total;
2981 	kmcp->kmc_magazine_size.value.ui64	=
2982 	    (cp->cache_flags & KMF_NOMAGAZINE) ?
2983 	    0 : cp->cache_magtype->mt_magsize;
2984 
2985 	kmcp->kmc_alloc.value.ui64		+= cp->cache_full.ml_alloc;
2986 	kmcp->kmc_free.value.ui64		+= cp->cache_empty.ml_alloc;
2987 	buf_avail += cp->cache_full.ml_total * cp->cache_magtype->mt_magsize;
2988 
2989 	mutex_exit(&cp->cache_depot_lock);
2990 
2991 	kmcp->kmc_buf_size.value.ui64	= cp->cache_bufsize;
2992 	kmcp->kmc_align.value.ui64	= cp->cache_align;
2993 	kmcp->kmc_chunk_size.value.ui64	= cp->cache_chunksize;
2994 	kmcp->kmc_slab_size.value.ui64	= cp->cache_slabsize;
2995 	kmcp->kmc_buf_constructed.value.ui64 = buf_avail;
2996 	buf_avail += cp->cache_bufslab;
2997 	kmcp->kmc_buf_avail.value.ui64	= buf_avail;
2998 	kmcp->kmc_buf_inuse.value.ui64	= cp->cache_buftotal - buf_avail;
2999 	kmcp->kmc_buf_total.value.ui64	= cp->cache_buftotal;
3000 	kmcp->kmc_buf_max.value.ui64	= cp->cache_bufmax;
3001 	kmcp->kmc_slab_create.value.ui64	= cp->cache_slab_create;
3002 	kmcp->kmc_slab_destroy.value.ui64	= cp->cache_slab_destroy;
3003 	kmcp->kmc_hash_size.value.ui64	= (cp->cache_flags & KMF_HASH) ?
3004 	    cp->cache_hash_mask + 1 : 0;
3005 	kmcp->kmc_hash_lookup_depth.value.ui64	= cp->cache_lookup_depth;
3006 	kmcp->kmc_hash_rescale.value.ui64	= cp->cache_rescale;
3007 	kmcp->kmc_vmem_source.value.ui64	= cp->cache_arena->vm_id;
3008 
3009 	if (cp->cache_defrag == NULL) {
3010 		kmcp->kmc_move_callbacks.value.ui64	= 0;
3011 		kmcp->kmc_move_yes.value.ui64		= 0;
3012 		kmcp->kmc_move_no.value.ui64		= 0;
3013 		kmcp->kmc_move_later.value.ui64		= 0;
3014 		kmcp->kmc_move_dont_need.value.ui64	= 0;
3015 		kmcp->kmc_move_dont_know.value.ui64	= 0;
3016 		kmcp->kmc_move_hunt_found.value.ui64	= 0;
3017 	} else {
3018 		kmem_defrag_t *kd = cp->cache_defrag;
3019 		kmcp->kmc_move_callbacks.value.ui64	= kd->kmd_callbacks;
3020 		kmcp->kmc_move_yes.value.ui64		= kd->kmd_yes;
3021 		kmcp->kmc_move_no.value.ui64		= kd->kmd_no;
3022 		kmcp->kmc_move_later.value.ui64		= kd->kmd_later;
3023 		kmcp->kmc_move_dont_need.value.ui64	= kd->kmd_dont_need;
3024 		kmcp->kmc_move_dont_know.value.ui64	= kd->kmd_dont_know;
3025 		kmcp->kmc_move_hunt_found.value.ui64	= kd->kmd_hunt_found;
3026 	}
3027 
3028 	mutex_exit(&cp->cache_lock);
3029 	return (0);
3030 }
3031 
3032 /*
3033  * Return a named statistic about a particular cache.
3034  * This shouldn't be called very often, so it's currently designed for
3035  * simplicity (leverages existing kstat support) rather than efficiency.
3036  */
3037 uint64_t
3038 kmem_cache_stat(kmem_cache_t *cp, char *name)
3039 {
3040 	int i;
3041 	kstat_t *ksp = cp->cache_kstat;
3042 	kstat_named_t *knp = (kstat_named_t *)&kmem_cache_kstat;
3043 	uint64_t value = 0;
3044 
3045 	if (ksp != NULL) {
3046 		mutex_enter(&kmem_cache_kstat_lock);
3047 		(void) kmem_cache_kstat_update(ksp, KSTAT_READ);
3048 		for (i = 0; i < ksp->ks_ndata; i++) {
3049 			if (strcmp(knp[i].name, name) == 0) {
3050 				value = knp[i].value.ui64;
3051 				break;
3052 			}
3053 		}
3054 		mutex_exit(&kmem_cache_kstat_lock);
3055 	}
3056 	return (value);
3057 }
3058 
3059 /*
3060  * Return an estimate of currently available kernel heap memory.
3061  * On 32-bit systems, physical memory may exceed virtual memory,
3062  * we just truncate the result at 1GB.
3063  */
3064 size_t
3065 kmem_avail(void)
3066 {
3067 	spgcnt_t rmem = availrmem - tune.t_minarmem;
3068 	spgcnt_t fmem = freemem - minfree;
3069 
3070 	return ((size_t)ptob(MIN(MAX(MIN(rmem, fmem), 0),
3071 	    1 << (30 - PAGESHIFT))));
3072 }
3073 
3074 /*
3075  * Return the maximum amount of memory that is (in theory) allocatable
3076  * from the heap. This may be used as an estimate only since there
3077  * is no guarentee this space will still be available when an allocation
3078  * request is made, nor that the space may be allocated in one big request
3079  * due to kernel heap fragmentation.
3080  */
3081 size_t
3082 kmem_maxavail(void)
3083 {
3084 	spgcnt_t pmem = availrmem - tune.t_minarmem;
3085 	spgcnt_t vmem = btop(vmem_size(heap_arena, VMEM_FREE));
3086 
3087 	return ((size_t)ptob(MAX(MIN(pmem, vmem), 0)));
3088 }
3089 
3090 /*
3091  * Indicate whether memory-intensive kmem debugging is enabled.
3092  */
3093 int
3094 kmem_debugging(void)
3095 {
3096 	return (kmem_flags & (KMF_AUDIT | KMF_REDZONE));
3097 }
3098 
3099 /* binning function, sorts finely at the two extremes */
3100 #define	KMEM_PARTIAL_SLAB_WEIGHT(sp, binshift)				\
3101 	((((sp)->slab_refcnt <= (binshift)) ||				\
3102 	    (((sp)->slab_chunks - (sp)->slab_refcnt) <= (binshift)))	\
3103 	    ? -(sp)->slab_refcnt					\
3104 	    : -((binshift) + ((sp)->slab_refcnt >> (binshift))))
3105 
3106 /*
3107  * Minimizing the number of partial slabs on the freelist minimizes
3108  * fragmentation (the ratio of unused buffers held by the slab layer). There are
3109  * two ways to get a slab off of the freelist: 1) free all the buffers on the
3110  * slab, and 2) allocate all the buffers on the slab. It follows that we want
3111  * the most-used slabs at the front of the list where they have the best chance
3112  * of being completely allocated, and the least-used slabs at a safe distance
3113  * from the front to improve the odds that the few remaining buffers will all be
3114  * freed before another allocation can tie up the slab. For that reason a slab
3115  * with a higher slab_refcnt sorts less than than a slab with a lower
3116  * slab_refcnt.
3117  *
3118  * However, if a slab has at least one buffer that is deemed unfreeable, we
3119  * would rather have that slab at the front of the list regardless of
3120  * slab_refcnt, since even one unfreeable buffer makes the entire slab
3121  * unfreeable. If the client returns KMEM_CBRC_NO in response to a cache_move()
3122  * callback, the slab is marked unfreeable for as long as it remains on the
3123  * freelist.
3124  */
3125 static int
3126 kmem_partial_slab_cmp(const void *p0, const void *p1)
3127 {
3128 	const kmem_cache_t *cp;
3129 	const kmem_slab_t *s0 = p0;
3130 	const kmem_slab_t *s1 = p1;
3131 	int w0, w1;
3132 	size_t binshift;
3133 
3134 	ASSERT(KMEM_SLAB_IS_PARTIAL(s0));
3135 	ASSERT(KMEM_SLAB_IS_PARTIAL(s1));
3136 	ASSERT(s0->slab_cache == s1->slab_cache);
3137 	cp = s1->slab_cache;
3138 	ASSERT(MUTEX_HELD(&cp->cache_lock));
3139 	binshift = cp->cache_partial_binshift;
3140 
3141 	/* weight of first slab */
3142 	w0 = KMEM_PARTIAL_SLAB_WEIGHT(s0, binshift);
3143 	if (s0->slab_flags & KMEM_SLAB_NOMOVE) {
3144 		w0 -= cp->cache_maxchunks;
3145 	}
3146 
3147 	/* weight of second slab */
3148 	w1 = KMEM_PARTIAL_SLAB_WEIGHT(s1, binshift);
3149 	if (s1->slab_flags & KMEM_SLAB_NOMOVE) {
3150 		w1 -= cp->cache_maxchunks;
3151 	}
3152 
3153 	if (w0 < w1)
3154 		return (-1);
3155 	if (w0 > w1)
3156 		return (1);
3157 
3158 	/* compare pointer values */
3159 	if ((uintptr_t)s0 < (uintptr_t)s1)
3160 		return (-1);
3161 	if ((uintptr_t)s0 > (uintptr_t)s1)
3162 		return (1);
3163 
3164 	return (0);
3165 }
3166 
3167 /*
3168  * It must be valid to call the destructor (if any) on a newly created object.
3169  * That is, the constructor (if any) must leave the object in a valid state for
3170  * the destructor.
3171  */
3172 kmem_cache_t *
3173 kmem_cache_create(
3174 	char *name,		/* descriptive name for this cache */
3175 	size_t bufsize,		/* size of the objects it manages */
3176 	size_t align,		/* required object alignment */
3177 	int (*constructor)(void *, void *, int), /* object constructor */
3178 	void (*destructor)(void *, void *),	/* object destructor */
3179 	void (*reclaim)(void *), /* memory reclaim callback */
3180 	void *private,		/* pass-thru arg for constr/destr/reclaim */
3181 	vmem_t *vmp,		/* vmem source for slab allocation */
3182 	int cflags)		/* cache creation flags */
3183 {
3184 	int cpu_seqid;
3185 	size_t chunksize;
3186 	kmem_cache_t *cp;
3187 	kmem_magtype_t *mtp;
3188 	size_t csize = KMEM_CACHE_SIZE(max_ncpus);
3189 
3190 #ifdef	DEBUG
3191 	/*
3192 	 * Cache names should conform to the rules for valid C identifiers
3193 	 */
3194 	if (!strident_valid(name)) {
3195 		cmn_err(CE_CONT,
3196 		    "kmem_cache_create: '%s' is an invalid cache name\n"
3197 		    "cache names must conform to the rules for "
3198 		    "C identifiers\n", name);
3199 	}
3200 #endif	/* DEBUG */
3201 
3202 	if (vmp == NULL)
3203 		vmp = kmem_default_arena;
3204 
3205 	/*
3206 	 * If this kmem cache has an identifier vmem arena as its source, mark
3207 	 * it such to allow kmem_reap_idspace().
3208 	 */
3209 	ASSERT(!(cflags & KMC_IDENTIFIER));   /* consumer should not set this */
3210 	if (vmp->vm_cflags & VMC_IDENTIFIER)
3211 		cflags |= KMC_IDENTIFIER;
3212 
3213 	/*
3214 	 * Get a kmem_cache structure.  We arrange that cp->cache_cpu[]
3215 	 * is aligned on a KMEM_CPU_CACHE_SIZE boundary to prevent
3216 	 * false sharing of per-CPU data.
3217 	 */
3218 	cp = vmem_xalloc(kmem_cache_arena, csize, KMEM_CPU_CACHE_SIZE,
3219 	    P2NPHASE(csize, KMEM_CPU_CACHE_SIZE), 0, NULL, NULL, VM_SLEEP);
3220 	bzero(cp, csize);
3221 	list_link_init(&cp->cache_link);
3222 
3223 	if (align == 0)
3224 		align = KMEM_ALIGN;
3225 
3226 	/*
3227 	 * If we're not at least KMEM_ALIGN aligned, we can't use free
3228 	 * memory to hold bufctl information (because we can't safely
3229 	 * perform word loads and stores on it).
3230 	 */
3231 	if (align < KMEM_ALIGN)
3232 		cflags |= KMC_NOTOUCH;
3233 
3234 	if ((align & (align - 1)) != 0 || align > vmp->vm_quantum)
3235 		panic("kmem_cache_create: bad alignment %lu", align);
3236 
3237 	mutex_enter(&kmem_flags_lock);
3238 	if (kmem_flags & KMF_RANDOMIZE)
3239 		kmem_flags = (((kmem_flags | ~KMF_RANDOM) + 1) & KMF_RANDOM) |
3240 		    KMF_RANDOMIZE;
3241 	cp->cache_flags = (kmem_flags | cflags) & KMF_DEBUG;
3242 	mutex_exit(&kmem_flags_lock);
3243 
3244 	/*
3245 	 * Make sure all the various flags are reasonable.
3246 	 */
3247 	ASSERT(!(cflags & KMC_NOHASH) || !(cflags & KMC_NOTOUCH));
3248 
3249 	if (cp->cache_flags & KMF_LITE) {
3250 		if (bufsize >= kmem_lite_minsize &&
3251 		    align <= kmem_lite_maxalign &&
3252 		    P2PHASE(bufsize, kmem_lite_maxalign) != 0) {
3253 			cp->cache_flags |= KMF_BUFTAG;
3254 			cp->cache_flags &= ~(KMF_AUDIT | KMF_FIREWALL);
3255 		} else {
3256 			cp->cache_flags &= ~KMF_DEBUG;
3257 		}
3258 	}
3259 
3260 	if (cp->cache_flags & KMF_DEADBEEF)
3261 		cp->cache_flags |= KMF_REDZONE;
3262 
3263 	if ((cflags & KMC_QCACHE) && (cp->cache_flags & KMF_AUDIT))
3264 		cp->cache_flags |= KMF_NOMAGAZINE;
3265 
3266 	if (cflags & KMC_NODEBUG)
3267 		cp->cache_flags &= ~KMF_DEBUG;
3268 
3269 	if (cflags & KMC_NOTOUCH)
3270 		cp->cache_flags &= ~KMF_TOUCH;
3271 
3272 	if (cflags & KMC_NOHASH)
3273 		cp->cache_flags &= ~(KMF_AUDIT | KMF_FIREWALL);
3274 
3275 	if (cflags & KMC_NOMAGAZINE)
3276 		cp->cache_flags |= KMF_NOMAGAZINE;
3277 
3278 	if ((cp->cache_flags & KMF_AUDIT) && !(cflags & KMC_NOTOUCH))
3279 		cp->cache_flags |= KMF_REDZONE;
3280 
3281 	if (!(cp->cache_flags & KMF_AUDIT))
3282 		cp->cache_flags &= ~KMF_CONTENTS;
3283 
3284 	if ((cp->cache_flags & KMF_BUFTAG) && bufsize >= kmem_minfirewall &&
3285 	    !(cp->cache_flags & KMF_LITE) && !(cflags & KMC_NOHASH))
3286 		cp->cache_flags |= KMF_FIREWALL;
3287 
3288 	if (vmp != kmem_default_arena || kmem_firewall_arena == NULL)
3289 		cp->cache_flags &= ~KMF_FIREWALL;
3290 
3291 	if (cp->cache_flags & KMF_FIREWALL) {
3292 		cp->cache_flags &= ~KMF_BUFTAG;
3293 		cp->cache_flags |= KMF_NOMAGAZINE;
3294 		ASSERT(vmp == kmem_default_arena);
3295 		vmp = kmem_firewall_arena;
3296 	}
3297 
3298 	/*
3299 	 * Set cache properties.
3300 	 */
3301 	(void) strncpy(cp->cache_name, name, KMEM_CACHE_NAMELEN);
3302 	strident_canon(cp->cache_name, KMEM_CACHE_NAMELEN + 1);
3303 	cp->cache_bufsize = bufsize;
3304 	cp->cache_align = align;
3305 	cp->cache_constructor = constructor;
3306 	cp->cache_destructor = destructor;
3307 	cp->cache_reclaim = reclaim;
3308 	cp->cache_private = private;
3309 	cp->cache_arena = vmp;
3310 	cp->cache_cflags = cflags;
3311 
3312 	/*
3313 	 * Determine the chunk size.
3314 	 */
3315 	chunksize = bufsize;
3316 
3317 	if (align >= KMEM_ALIGN) {
3318 		chunksize = P2ROUNDUP(chunksize, KMEM_ALIGN);
3319 		cp->cache_bufctl = chunksize - KMEM_ALIGN;
3320 	}
3321 
3322 	if (cp->cache_flags & KMF_BUFTAG) {
3323 		cp->cache_bufctl = chunksize;
3324 		cp->cache_buftag = chunksize;
3325 		if (cp->cache_flags & KMF_LITE)
3326 			chunksize += KMEM_BUFTAG_LITE_SIZE(kmem_lite_count);
3327 		else
3328 			chunksize += sizeof (kmem_buftag_t);
3329 	}
3330 
3331 	if (cp->cache_flags & KMF_DEADBEEF) {
3332 		cp->cache_verify = MIN(cp->cache_buftag, kmem_maxverify);
3333 		if (cp->cache_flags & KMF_LITE)
3334 			cp->cache_verify = sizeof (uint64_t);
3335 	}
3336 
3337 	cp->cache_contents = MIN(cp->cache_bufctl, kmem_content_maxsave);
3338 
3339 	cp->cache_chunksize = chunksize = P2ROUNDUP(chunksize, align);
3340 
3341 	/*
3342 	 * Now that we know the chunk size, determine the optimal slab size.
3343 	 */
3344 	if (vmp == kmem_firewall_arena) {
3345 		cp->cache_slabsize = P2ROUNDUP(chunksize, vmp->vm_quantum);
3346 		cp->cache_mincolor = cp->cache_slabsize - chunksize;
3347 		cp->cache_maxcolor = cp->cache_mincolor;
3348 		cp->cache_flags |= KMF_HASH;
3349 		ASSERT(!(cp->cache_flags & KMF_BUFTAG));
3350 	} else if ((cflags & KMC_NOHASH) || (!(cflags & KMC_NOTOUCH) &&
3351 	    !(cp->cache_flags & KMF_AUDIT) &&
3352 	    chunksize < vmp->vm_quantum / KMEM_VOID_FRACTION)) {
3353 		cp->cache_slabsize = vmp->vm_quantum;
3354 		cp->cache_mincolor = 0;
3355 		cp->cache_maxcolor =
3356 		    (cp->cache_slabsize - sizeof (kmem_slab_t)) % chunksize;
3357 		ASSERT(chunksize + sizeof (kmem_slab_t) <= cp->cache_slabsize);
3358 		ASSERT(!(cp->cache_flags & KMF_AUDIT));
3359 	} else {
3360 		size_t chunks, bestfit, waste, slabsize;
3361 		size_t minwaste = LONG_MAX;
3362 
3363 		for (chunks = 1; chunks <= KMEM_VOID_FRACTION; chunks++) {
3364 			slabsize = P2ROUNDUP(chunksize * chunks,
3365 			    vmp->vm_quantum);
3366 			chunks = slabsize / chunksize;
3367 			waste = (slabsize % chunksize) / chunks;
3368 			if (waste < minwaste) {
3369 				minwaste = waste;
3370 				bestfit = slabsize;
3371 			}
3372 		}
3373 		if (cflags & KMC_QCACHE)
3374 			bestfit = VMEM_QCACHE_SLABSIZE(vmp->vm_qcache_max);
3375 		cp->cache_slabsize = bestfit;
3376 		cp->cache_mincolor = 0;
3377 		cp->cache_maxcolor = bestfit % chunksize;
3378 		cp->cache_flags |= KMF_HASH;
3379 	}
3380 
3381 	cp->cache_maxchunks = (cp->cache_slabsize / cp->cache_chunksize);
3382 	cp->cache_partial_binshift = highbit(cp->cache_maxchunks / 16) + 1;
3383 
3384 	if (cp->cache_flags & KMF_HASH) {
3385 		ASSERT(!(cflags & KMC_NOHASH));
3386 		cp->cache_bufctl_cache = (cp->cache_flags & KMF_AUDIT) ?
3387 		    kmem_bufctl_audit_cache : kmem_bufctl_cache;
3388 	}
3389 
3390 	if (cp->cache_maxcolor >= vmp->vm_quantum)
3391 		cp->cache_maxcolor = vmp->vm_quantum - 1;
3392 
3393 	cp->cache_color = cp->cache_mincolor;
3394 
3395 	/*
3396 	 * Initialize the rest of the slab layer.
3397 	 */
3398 	mutex_init(&cp->cache_lock, NULL, MUTEX_DEFAULT, NULL);
3399 
3400 	avl_create(&cp->cache_partial_slabs, kmem_partial_slab_cmp,
3401 	    sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link));
3402 	/* LINTED: E_TRUE_LOGICAL_EXPR */
3403 	ASSERT(sizeof (list_node_t) <= sizeof (avl_node_t));
3404 	/* reuse partial slab AVL linkage for complete slab list linkage */
3405 	list_create(&cp->cache_complete_slabs,
3406 	    sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link));
3407 
3408 	if (cp->cache_flags & KMF_HASH) {
3409 		cp->cache_hash_table = vmem_alloc(kmem_hash_arena,
3410 		    KMEM_HASH_INITIAL * sizeof (void *), VM_SLEEP);
3411 		bzero(cp->cache_hash_table,
3412 		    KMEM_HASH_INITIAL * sizeof (void *));
3413 		cp->cache_hash_mask = KMEM_HASH_INITIAL - 1;
3414 		cp->cache_hash_shift = highbit((ulong_t)chunksize) - 1;
3415 	}
3416 
3417 	/*
3418 	 * Initialize the depot.
3419 	 */
3420 	mutex_init(&cp->cache_depot_lock, NULL, MUTEX_DEFAULT, NULL);
3421 
3422 	for (mtp = kmem_magtype; chunksize <= mtp->mt_minbuf; mtp++)
3423 		continue;
3424 
3425 	cp->cache_magtype = mtp;
3426 
3427 	/*
3428 	 * Initialize the CPU layer.
3429 	 */
3430 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
3431 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
3432 		mutex_init(&ccp->cc_lock, NULL, MUTEX_DEFAULT, NULL);
3433 		ccp->cc_flags = cp->cache_flags;
3434 		ccp->cc_rounds = -1;
3435 		ccp->cc_prounds = -1;
3436 	}
3437 
3438 	/*
3439 	 * Create the cache's kstats.
3440 	 */
3441 	if ((cp->cache_kstat = kstat_create("unix", 0, cp->cache_name,
3442 	    "kmem_cache", KSTAT_TYPE_NAMED,
3443 	    sizeof (kmem_cache_kstat) / sizeof (kstat_named_t),
3444 	    KSTAT_FLAG_VIRTUAL)) != NULL) {
3445 		cp->cache_kstat->ks_data = &kmem_cache_kstat;
3446 		cp->cache_kstat->ks_update = kmem_cache_kstat_update;
3447 		cp->cache_kstat->ks_private = cp;
3448 		cp->cache_kstat->ks_lock = &kmem_cache_kstat_lock;
3449 		kstat_install(cp->cache_kstat);
3450 	}
3451 
3452 	/*
3453 	 * Add the cache to the global list.  This makes it visible
3454 	 * to kmem_update(), so the cache must be ready for business.
3455 	 */
3456 	mutex_enter(&kmem_cache_lock);
3457 	list_insert_tail(&kmem_caches, cp);
3458 	mutex_exit(&kmem_cache_lock);
3459 
3460 	if (kmem_ready)
3461 		kmem_cache_magazine_enable(cp);
3462 
3463 	return (cp);
3464 }
3465 
3466 static int
3467 kmem_move_cmp(const void *buf, const void *p)
3468 {
3469 	const kmem_move_t *kmm = p;
3470 	uintptr_t v1 = (uintptr_t)buf;
3471 	uintptr_t v2 = (uintptr_t)kmm->kmm_from_buf;
3472 	return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0));
3473 }
3474 
3475 static void
3476 kmem_reset_reclaim_threshold(kmem_defrag_t *kmd)
3477 {
3478 	kmd->kmd_reclaim_numer = 1;
3479 }
3480 
3481 /*
3482  * Initially, when choosing candidate slabs for buffers to move, we want to be
3483  * very selective and take only slabs that are less than
3484  * (1 / KMEM_VOID_FRACTION) allocated. If we have difficulty finding candidate
3485  * slabs, then we raise the allocation ceiling incrementally. The reclaim
3486  * threshold is reset to (1 / KMEM_VOID_FRACTION) as soon as the cache is no
3487  * longer fragmented.
3488  */
3489 static void
3490 kmem_adjust_reclaim_threshold(kmem_defrag_t *kmd, int direction)
3491 {
3492 	if (direction > 0) {
3493 		/* make it easier to find a candidate slab */
3494 		if (kmd->kmd_reclaim_numer < (KMEM_VOID_FRACTION - 1)) {
3495 			kmd->kmd_reclaim_numer++;
3496 		}
3497 	} else {
3498 		/* be more selective */
3499 		if (kmd->kmd_reclaim_numer > 1) {
3500 			kmd->kmd_reclaim_numer--;
3501 		}
3502 	}
3503 }
3504 
3505 void
3506 kmem_cache_set_move(kmem_cache_t *cp,
3507     kmem_cbrc_t (*move)(void *, void *, size_t, void *))
3508 {
3509 	kmem_defrag_t *defrag;
3510 
3511 	ASSERT(move != NULL);
3512 	/*
3513 	 * The consolidator does not support NOTOUCH caches because kmem cannot
3514 	 * initialize their slabs with the 0xbaddcafe memory pattern, which sets
3515 	 * a low order bit usable by clients to distinguish uninitialized memory
3516 	 * from known objects (see kmem_slab_create).
3517 	 */
3518 	ASSERT(!(cp->cache_cflags & KMC_NOTOUCH));
3519 	ASSERT(!(cp->cache_cflags & KMC_IDENTIFIER));
3520 
3521 	/*
3522 	 * We should not be holding anyone's cache lock when calling
3523 	 * kmem_cache_alloc(), so allocate in all cases before acquiring the
3524 	 * lock.
3525 	 */
3526 	defrag = kmem_cache_alloc(kmem_defrag_cache, KM_SLEEP);
3527 
3528 	mutex_enter(&cp->cache_lock);
3529 
3530 	if (KMEM_IS_MOVABLE(cp)) {
3531 		if (cp->cache_move == NULL) {
3532 			ASSERT(cp->cache_slab_alloc == 0);
3533 
3534 			cp->cache_defrag = defrag;
3535 			defrag = NULL; /* nothing to free */
3536 			bzero(cp->cache_defrag, sizeof (kmem_defrag_t));
3537 			avl_create(&cp->cache_defrag->kmd_moves_pending,
3538 			    kmem_move_cmp, sizeof (kmem_move_t),
3539 			    offsetof(kmem_move_t, kmm_entry));
3540 			/* LINTED: E_TRUE_LOGICAL_EXPR */
3541 			ASSERT(sizeof (list_node_t) <= sizeof (avl_node_t));
3542 			/* reuse the slab's AVL linkage for deadlist linkage */
3543 			list_create(&cp->cache_defrag->kmd_deadlist,
3544 			    sizeof (kmem_slab_t),
3545 			    offsetof(kmem_slab_t, slab_link));
3546 			kmem_reset_reclaim_threshold(cp->cache_defrag);
3547 		}
3548 		cp->cache_move = move;
3549 	}
3550 
3551 	mutex_exit(&cp->cache_lock);
3552 
3553 	if (defrag != NULL) {
3554 		kmem_cache_free(kmem_defrag_cache, defrag); /* unused */
3555 	}
3556 }
3557 
3558 void
3559 kmem_cache_destroy(kmem_cache_t *cp)
3560 {
3561 	int cpu_seqid;
3562 
3563 	/*
3564 	 * Remove the cache from the global cache list so that no one else
3565 	 * can schedule tasks on its behalf, wait for any pending tasks to
3566 	 * complete, purge the cache, and then destroy it.
3567 	 */
3568 	mutex_enter(&kmem_cache_lock);
3569 	list_remove(&kmem_caches, cp);
3570 	mutex_exit(&kmem_cache_lock);
3571 
3572 	if (kmem_taskq != NULL)
3573 		taskq_wait(kmem_taskq);
3574 	if (kmem_move_taskq != NULL)
3575 		taskq_wait(kmem_move_taskq);
3576 
3577 	kmem_cache_magazine_purge(cp);
3578 
3579 	mutex_enter(&cp->cache_lock);
3580 	if (cp->cache_buftotal != 0)
3581 		cmn_err(CE_WARN, "kmem_cache_destroy: '%s' (%p) not empty",
3582 		    cp->cache_name, (void *)cp);
3583 	if (cp->cache_defrag != NULL) {
3584 		avl_destroy(&cp->cache_defrag->kmd_moves_pending);
3585 		list_destroy(&cp->cache_defrag->kmd_deadlist);
3586 		kmem_cache_free(kmem_defrag_cache, cp->cache_defrag);
3587 		cp->cache_defrag = NULL;
3588 	}
3589 	/*
3590 	 * The cache is now dead.  There should be no further activity.  We
3591 	 * enforce this by setting land mines in the constructor, destructor,
3592 	 * reclaim, and move routines that induce a kernel text fault if
3593 	 * invoked.
3594 	 */
3595 	cp->cache_constructor = (int (*)(void *, void *, int))1;
3596 	cp->cache_destructor = (void (*)(void *, void *))2;
3597 	cp->cache_reclaim = (void (*)(void *))3;
3598 	cp->cache_move = (kmem_cbrc_t (*)(void *, void *, size_t, void *))4;
3599 	mutex_exit(&cp->cache_lock);
3600 
3601 	kstat_delete(cp->cache_kstat);
3602 
3603 	if (cp->cache_hash_table != NULL)
3604 		vmem_free(kmem_hash_arena, cp->cache_hash_table,
3605 		    (cp->cache_hash_mask + 1) * sizeof (void *));
3606 
3607 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++)
3608 		mutex_destroy(&cp->cache_cpu[cpu_seqid].cc_lock);
3609 
3610 	mutex_destroy(&cp->cache_depot_lock);
3611 	mutex_destroy(&cp->cache_lock);
3612 
3613 	vmem_free(kmem_cache_arena, cp, KMEM_CACHE_SIZE(max_ncpus));
3614 }
3615 
3616 /*ARGSUSED*/
3617 static int
3618 kmem_cpu_setup(cpu_setup_t what, int id, void *arg)
3619 {
3620 	ASSERT(MUTEX_HELD(&cpu_lock));
3621 	if (what == CPU_UNCONFIG) {
3622 		kmem_cache_applyall(kmem_cache_magazine_purge,
3623 		    kmem_taskq, TQ_SLEEP);
3624 		kmem_cache_applyall(kmem_cache_magazine_enable,
3625 		    kmem_taskq, TQ_SLEEP);
3626 	}
3627 	return (0);
3628 }
3629 
3630 static void
3631 kmem_cache_init(int pass, int use_large_pages)
3632 {
3633 	int i;
3634 	size_t size;
3635 	kmem_cache_t *cp;
3636 	kmem_magtype_t *mtp;
3637 	char name[KMEM_CACHE_NAMELEN + 1];
3638 
3639 	for (i = 0; i < sizeof (kmem_magtype) / sizeof (*mtp); i++) {
3640 		mtp = &kmem_magtype[i];
3641 		(void) sprintf(name, "kmem_magazine_%d", mtp->mt_magsize);
3642 		mtp->mt_cache = kmem_cache_create(name,
3643 		    (mtp->mt_magsize + 1) * sizeof (void *),
3644 		    mtp->mt_align, NULL, NULL, NULL, NULL,
3645 		    kmem_msb_arena, KMC_NOHASH);
3646 	}
3647 
3648 	kmem_slab_cache = kmem_cache_create("kmem_slab_cache",
3649 	    sizeof (kmem_slab_t), 0, NULL, NULL, NULL, NULL,
3650 	    kmem_msb_arena, KMC_NOHASH);
3651 
3652 	kmem_bufctl_cache = kmem_cache_create("kmem_bufctl_cache",
3653 	    sizeof (kmem_bufctl_t), 0, NULL, NULL, NULL, NULL,
3654 	    kmem_msb_arena, KMC_NOHASH);
3655 
3656 	kmem_bufctl_audit_cache = kmem_cache_create("kmem_bufctl_audit_cache",
3657 	    sizeof (kmem_bufctl_audit_t), 0, NULL, NULL, NULL, NULL,
3658 	    kmem_msb_arena, KMC_NOHASH);
3659 
3660 	if (pass == 2) {
3661 		kmem_va_arena = vmem_create("kmem_va",
3662 		    NULL, 0, PAGESIZE,
3663 		    vmem_alloc, vmem_free, heap_arena,
3664 		    8 * PAGESIZE, VM_SLEEP);
3665 
3666 		if (use_large_pages) {
3667 			kmem_default_arena = vmem_xcreate("kmem_default",
3668 			    NULL, 0, PAGESIZE,
3669 			    segkmem_alloc_lp, segkmem_free_lp, kmem_va_arena,
3670 			    0, VM_SLEEP);
3671 		} else {
3672 			kmem_default_arena = vmem_create("kmem_default",
3673 			    NULL, 0, PAGESIZE,
3674 			    segkmem_alloc, segkmem_free, kmem_va_arena,
3675 			    0, VM_SLEEP);
3676 		}
3677 	} else {
3678 		/*
3679 		 * During the first pass, the kmem_alloc_* caches
3680 		 * are treated as metadata.
3681 		 */
3682 		kmem_default_arena = kmem_msb_arena;
3683 	}
3684 
3685 	/*
3686 	 * Set up the default caches to back kmem_alloc()
3687 	 */
3688 	size = KMEM_ALIGN;
3689 	for (i = 0; i < sizeof (kmem_alloc_sizes) / sizeof (int); i++) {
3690 		size_t align = KMEM_ALIGN;
3691 		size_t cache_size = kmem_alloc_sizes[i];
3692 		/*
3693 		 * If they allocate a multiple of the coherency granularity,
3694 		 * they get a coherency-granularity-aligned address.
3695 		 */
3696 		if (IS_P2ALIGNED(cache_size, 64))
3697 			align = 64;
3698 		if (IS_P2ALIGNED(cache_size, PAGESIZE))
3699 			align = PAGESIZE;
3700 		(void) sprintf(name, "kmem_alloc_%lu", cache_size);
3701 		cp = kmem_cache_create(name, cache_size, align,
3702 		    NULL, NULL, NULL, NULL, NULL, KMC_KMEM_ALLOC);
3703 		while (size <= cache_size) {
3704 			kmem_alloc_table[(size - 1) >> KMEM_ALIGN_SHIFT] = cp;
3705 			size += KMEM_ALIGN;
3706 		}
3707 	}
3708 }
3709 
3710 void
3711 kmem_init(void)
3712 {
3713 	kmem_cache_t *cp;
3714 	int old_kmem_flags = kmem_flags;
3715 	int use_large_pages = 0;
3716 	size_t maxverify, minfirewall;
3717 
3718 	kstat_init();
3719 
3720 	/*
3721 	 * Small-memory systems (< 24 MB) can't handle kmem_flags overhead.
3722 	 */
3723 	if (physmem < btop(24 << 20) && !(old_kmem_flags & KMF_STICKY))
3724 		kmem_flags = 0;
3725 
3726 	/*
3727 	 * Don't do firewalled allocations if the heap is less than 1TB
3728 	 * (i.e. on a 32-bit kernel)
3729 	 * The resulting VM_NEXTFIT allocations would create too much
3730 	 * fragmentation in a small heap.
3731 	 */
3732 #if defined(_LP64)
3733 	maxverify = minfirewall = PAGESIZE / 2;
3734 #else
3735 	maxverify = minfirewall = ULONG_MAX;
3736 #endif
3737 
3738 	/* LINTED */
3739 	ASSERT(sizeof (kmem_cpu_cache_t) == KMEM_CPU_CACHE_SIZE);
3740 
3741 	list_create(&kmem_caches, sizeof (kmem_cache_t),
3742 	    offsetof(kmem_cache_t, cache_link));
3743 
3744 	kmem_metadata_arena = vmem_create("kmem_metadata", NULL, 0, PAGESIZE,
3745 	    vmem_alloc, vmem_free, heap_arena, 8 * PAGESIZE,
3746 	    VM_SLEEP | VMC_NO_QCACHE);
3747 
3748 	kmem_msb_arena = vmem_create("kmem_msb", NULL, 0,
3749 	    PAGESIZE, segkmem_alloc, segkmem_free, kmem_metadata_arena, 0,
3750 	    VM_SLEEP);
3751 
3752 	kmem_cache_arena = vmem_create("kmem_cache", NULL, 0, KMEM_ALIGN,
3753 	    segkmem_alloc, segkmem_free, kmem_metadata_arena, 0, VM_SLEEP);
3754 
3755 	kmem_hash_arena = vmem_create("kmem_hash", NULL, 0, KMEM_ALIGN,
3756 	    segkmem_alloc, segkmem_free, kmem_metadata_arena, 0, VM_SLEEP);
3757 
3758 	kmem_log_arena = vmem_create("kmem_log", NULL, 0, KMEM_ALIGN,
3759 	    segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP);
3760 
3761 	kmem_firewall_va_arena = vmem_create("kmem_firewall_va",
3762 	    NULL, 0, PAGESIZE,
3763 	    kmem_firewall_va_alloc, kmem_firewall_va_free, heap_arena,
3764 	    0, VM_SLEEP);
3765 
3766 	kmem_firewall_arena = vmem_create("kmem_firewall", NULL, 0, PAGESIZE,
3767 	    segkmem_alloc, segkmem_free, kmem_firewall_va_arena, 0, VM_SLEEP);
3768 
3769 	/* temporary oversize arena for mod_read_system_file */
3770 	kmem_oversize_arena = vmem_create("kmem_oversize", NULL, 0, PAGESIZE,
3771 	    segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP);
3772 
3773 	kmem_reap_interval = 15 * hz;
3774 
3775 	/*
3776 	 * Read /etc/system.  This is a chicken-and-egg problem because
3777 	 * kmem_flags may be set in /etc/system, but mod_read_system_file()
3778 	 * needs to use the allocator.  The simplest solution is to create
3779 	 * all the standard kmem caches, read /etc/system, destroy all the
3780 	 * caches we just created, and then create them all again in light
3781 	 * of the (possibly) new kmem_flags and other kmem tunables.
3782 	 */
3783 	kmem_cache_init(1, 0);
3784 
3785 	mod_read_system_file(boothowto & RB_ASKNAME);
3786 
3787 	while ((cp = list_tail(&kmem_caches)) != NULL)
3788 		kmem_cache_destroy(cp);
3789 
3790 	vmem_destroy(kmem_oversize_arena);
3791 
3792 	if (old_kmem_flags & KMF_STICKY)
3793 		kmem_flags = old_kmem_flags;
3794 
3795 	if (!(kmem_flags & KMF_AUDIT))
3796 		vmem_seg_size = offsetof(vmem_seg_t, vs_thread);
3797 
3798 	if (kmem_maxverify == 0)
3799 		kmem_maxverify = maxverify;
3800 
3801 	if (kmem_minfirewall == 0)
3802 		kmem_minfirewall = minfirewall;
3803 
3804 	/*
3805 	 * give segkmem a chance to figure out if we are using large pages
3806 	 * for the kernel heap
3807 	 */
3808 	use_large_pages = segkmem_lpsetup();
3809 
3810 	/*
3811 	 * To protect against corruption, we keep the actual number of callers
3812 	 * KMF_LITE records seperate from the tunable.  We arbitrarily clamp
3813 	 * to 16, since the overhead for small buffers quickly gets out of
3814 	 * hand.
3815 	 *
3816 	 * The real limit would depend on the needs of the largest KMC_NOHASH
3817 	 * cache.
3818 	 */
3819 	kmem_lite_count = MIN(MAX(0, kmem_lite_pcs), 16);
3820 	kmem_lite_pcs = kmem_lite_count;
3821 
3822 	/*
3823 	 * Normally, we firewall oversized allocations when possible, but
3824 	 * if we are using large pages for kernel memory, and we don't have
3825 	 * any non-LITE debugging flags set, we want to allocate oversized
3826 	 * buffers from large pages, and so skip the firewalling.
3827 	 */
3828 	if (use_large_pages &&
3829 	    ((kmem_flags & KMF_LITE) || !(kmem_flags & KMF_DEBUG))) {
3830 		kmem_oversize_arena = vmem_xcreate("kmem_oversize", NULL, 0,
3831 		    PAGESIZE, segkmem_alloc_lp, segkmem_free_lp, heap_arena,
3832 		    0, VM_SLEEP);
3833 	} else {
3834 		kmem_oversize_arena = vmem_create("kmem_oversize",
3835 		    NULL, 0, PAGESIZE,
3836 		    segkmem_alloc, segkmem_free, kmem_minfirewall < ULONG_MAX?
3837 		    kmem_firewall_va_arena : heap_arena, 0, VM_SLEEP);
3838 	}
3839 
3840 	kmem_cache_init(2, use_large_pages);
3841 
3842 	if (kmem_flags & (KMF_AUDIT | KMF_RANDOMIZE)) {
3843 		if (kmem_transaction_log_size == 0)
3844 			kmem_transaction_log_size = kmem_maxavail() / 50;
3845 		kmem_transaction_log = kmem_log_init(kmem_transaction_log_size);
3846 	}
3847 
3848 	if (kmem_flags & (KMF_CONTENTS | KMF_RANDOMIZE)) {
3849 		if (kmem_content_log_size == 0)
3850 			kmem_content_log_size = kmem_maxavail() / 50;
3851 		kmem_content_log = kmem_log_init(kmem_content_log_size);
3852 	}
3853 
3854 	kmem_failure_log = kmem_log_init(kmem_failure_log_size);
3855 
3856 	kmem_slab_log = kmem_log_init(kmem_slab_log_size);
3857 
3858 	/*
3859 	 * Initialize STREAMS message caches so allocb() is available.
3860 	 * This allows us to initialize the logging framework (cmn_err(9F),
3861 	 * strlog(9F), etc) so we can start recording messages.
3862 	 */
3863 	streams_msg_init();
3864 
3865 	/*
3866 	 * Initialize the ZSD framework in Zones so modules loaded henceforth
3867 	 * can register their callbacks.
3868 	 */
3869 	zone_zsd_init();
3870 
3871 	log_init();
3872 	taskq_init();
3873 
3874 	/*
3875 	 * Warn about invalid or dangerous values of kmem_flags.
3876 	 * Always warn about unsupported values.
3877 	 */
3878 	if (((kmem_flags & ~(KMF_AUDIT | KMF_DEADBEEF | KMF_REDZONE |
3879 	    KMF_CONTENTS | KMF_LITE)) != 0) ||
3880 	    ((kmem_flags & KMF_LITE) && kmem_flags != KMF_LITE))
3881 		cmn_err(CE_WARN, "kmem_flags set to unsupported value 0x%x. "
3882 		    "See the Solaris Tunable Parameters Reference Manual.",
3883 		    kmem_flags);
3884 
3885 #ifdef DEBUG
3886 	if ((kmem_flags & KMF_DEBUG) == 0)
3887 		cmn_err(CE_NOTE, "kmem debugging disabled.");
3888 #else
3889 	/*
3890 	 * For non-debug kernels, the only "normal" flags are 0, KMF_LITE,
3891 	 * KMF_REDZONE, and KMF_CONTENTS (the last because it is only enabled
3892 	 * if KMF_AUDIT is set). We should warn the user about the performance
3893 	 * penalty of KMF_AUDIT or KMF_DEADBEEF if they are set and KMF_LITE
3894 	 * isn't set (since that disables AUDIT).
3895 	 */
3896 	if (!(kmem_flags & KMF_LITE) &&
3897 	    (kmem_flags & (KMF_AUDIT | KMF_DEADBEEF)) != 0)
3898 		cmn_err(CE_WARN, "High-overhead kmem debugging features "
3899 		    "enabled (kmem_flags = 0x%x).  Performance degradation "
3900 		    "and large memory overhead possible. See the Solaris "
3901 		    "Tunable Parameters Reference Manual.", kmem_flags);
3902 #endif /* not DEBUG */
3903 
3904 	kmem_cache_applyall(kmem_cache_magazine_enable, NULL, TQ_SLEEP);
3905 
3906 	kmem_ready = 1;
3907 
3908 	/*
3909 	 * Initialize the platform-specific aligned/DMA memory allocator.
3910 	 */
3911 	ka_init();
3912 
3913 	/*
3914 	 * Initialize 32-bit ID cache.
3915 	 */
3916 	id32_init();
3917 
3918 	/*
3919 	 * Initialize the networking stack so modules loaded can
3920 	 * register their callbacks.
3921 	 */
3922 	netstack_init();
3923 }
3924 
3925 static void
3926 kmem_move_init(void)
3927 {
3928 	kmem_defrag_cache = kmem_cache_create("kmem_defrag_cache",
3929 	    sizeof (kmem_defrag_t), 0, NULL, NULL, NULL, NULL,
3930 	    kmem_msb_arena, KMC_NOHASH);
3931 	kmem_move_cache = kmem_cache_create("kmem_move_cache",
3932 	    sizeof (kmem_move_t), 0, NULL, NULL, NULL, NULL,
3933 	    kmem_msb_arena, KMC_NOHASH);
3934 
3935 	/*
3936 	 * kmem guarantees that move callbacks are sequential and that even
3937 	 * across multiple caches no two moves ever execute simultaneously.
3938 	 * Move callbacks are processed on a separate taskq so that client code
3939 	 * does not interfere with internal maintenance tasks.
3940 	 */
3941 	kmem_move_taskq = taskq_create_instance("kmem_move_taskq", 0, 1,
3942 	    minclsyspri, 100, INT_MAX, TASKQ_PREPOPULATE);
3943 }
3944 
3945 void
3946 kmem_thread_init(void)
3947 {
3948 	kmem_move_init();
3949 	kmem_taskq = taskq_create_instance("kmem_taskq", 0, 1, minclsyspri,
3950 	    300, INT_MAX, TASKQ_PREPOPULATE);
3951 }
3952 
3953 void
3954 kmem_mp_init(void)
3955 {
3956 	mutex_enter(&cpu_lock);
3957 	register_cpu_setup_func(kmem_cpu_setup, NULL);
3958 	mutex_exit(&cpu_lock);
3959 
3960 	kmem_update_timeout(NULL);
3961 }
3962 
3963 /*
3964  * Return the slab of the allocated buffer, or NULL if the buffer is not
3965  * allocated. This function may be called with a known slab address to determine
3966  * whether or not the buffer is allocated, or with a NULL slab address to obtain
3967  * an allocated buffer's slab.
3968  */
3969 static kmem_slab_t *
3970 kmem_slab_allocated(kmem_cache_t *cp, kmem_slab_t *sp, void *buf)
3971 {
3972 	kmem_bufctl_t *bcp, *bufbcp;
3973 
3974 	ASSERT(MUTEX_HELD(&cp->cache_lock));
3975 	ASSERT(sp == NULL || KMEM_SLAB_MEMBER(sp, buf));
3976 
3977 	if (cp->cache_flags & KMF_HASH) {
3978 		for (bcp = *KMEM_HASH(cp, buf);
3979 		    (bcp != NULL) && (bcp->bc_addr != buf);
3980 		    bcp = bcp->bc_next) {
3981 			continue;
3982 		}
3983 		ASSERT(sp != NULL && bcp != NULL ? sp == bcp->bc_slab : 1);
3984 		return (bcp == NULL ? NULL : bcp->bc_slab);
3985 	}
3986 
3987 	if (sp == NULL) {
3988 		sp = KMEM_SLAB(cp, buf);
3989 	}
3990 	bufbcp = KMEM_BUFCTL(cp, buf);
3991 	for (bcp = sp->slab_head;
3992 	    (bcp != NULL) && (bcp != bufbcp);
3993 	    bcp = bcp->bc_next) {
3994 		continue;
3995 	}
3996 	return (bcp == NULL ? sp : NULL);
3997 }
3998 
3999 static boolean_t
4000 kmem_slab_is_reclaimable(kmem_cache_t *cp, kmem_slab_t *sp, int flags)
4001 {
4002 	long refcnt;
4003 
4004 	ASSERT(cp->cache_defrag != NULL);
4005 
4006 	/* If we're desperate, we don't care if the client said NO. */
4007 	refcnt = sp->slab_refcnt;
4008 	if (flags & KMM_DESPERATE) {
4009 		return (refcnt < sp->slab_chunks); /* any partial */
4010 	}
4011 
4012 	if (sp->slab_flags & KMEM_SLAB_NOMOVE) {
4013 		return (B_FALSE);
4014 	}
4015 
4016 	if (kmem_move_any_partial) {
4017 		return (refcnt < sp->slab_chunks);
4018 	}
4019 
4020 	if ((refcnt == 1) && (refcnt < sp->slab_chunks)) {
4021 		return (B_TRUE);
4022 	}
4023 
4024 	/*
4025 	 * The reclaim threshold is adjusted at each kmem_cache_scan() so that
4026 	 * slabs with a progressively higher percentage of used buffers can be
4027 	 * reclaimed until the cache as a whole is no longer fragmented.
4028 	 *
4029 	 *	sp->slab_refcnt   kmd_reclaim_numer
4030 	 *	--------------- < ------------------
4031 	 *	sp->slab_chunks   KMEM_VOID_FRACTION
4032 	 */
4033 	return ((refcnt * KMEM_VOID_FRACTION) <
4034 	    (sp->slab_chunks * cp->cache_defrag->kmd_reclaim_numer));
4035 }
4036 
4037 static void *
4038 kmem_hunt_mag(kmem_cache_t *cp, kmem_magazine_t *m, int n, void *buf,
4039     void *tbuf)
4040 {
4041 	int i;		/* magazine round index */
4042 
4043 	for (i = 0; i < n; i++) {
4044 		if (buf == m->mag_round[i]) {
4045 			if (cp->cache_flags & KMF_BUFTAG) {
4046 				(void) kmem_cache_free_debug(cp, tbuf,
4047 				    caller());
4048 			}
4049 			m->mag_round[i] = tbuf;
4050 			return (buf);
4051 		}
4052 	}
4053 
4054 	return (NULL);
4055 }
4056 
4057 /*
4058  * Hunt the magazine layer for the given buffer. If found, the buffer is
4059  * removed from the magazine layer and returned, otherwise NULL is returned.
4060  * The state of the returned buffer is freed and constructed.
4061  */
4062 static void *
4063 kmem_hunt_mags(kmem_cache_t *cp, void *buf)
4064 {
4065 	kmem_cpu_cache_t *ccp;
4066 	kmem_magazine_t	*m;
4067 	int cpu_seqid;
4068 	int n;		/* magazine rounds */
4069 	void *tbuf;	/* temporary swap buffer */
4070 
4071 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4072 
4073 	/*
4074 	 * Allocated a buffer to swap with the one we hope to pull out of a
4075 	 * magazine when found.
4076 	 */
4077 	tbuf = kmem_cache_alloc(cp, KM_NOSLEEP);
4078 	if (tbuf == NULL) {
4079 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_alloc_fail);
4080 		return (NULL);
4081 	}
4082 	if (tbuf == buf) {
4083 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_lucky);
4084 		if (cp->cache_flags & KMF_BUFTAG) {
4085 			(void) kmem_cache_free_debug(cp, buf, caller());
4086 		}
4087 		return (buf);
4088 	}
4089 
4090 	/* Hunt the depot. */
4091 	mutex_enter(&cp->cache_depot_lock);
4092 	n = cp->cache_magtype->mt_magsize;
4093 	for (m = cp->cache_full.ml_list; m != NULL; m = m->mag_next) {
4094 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4095 			mutex_exit(&cp->cache_depot_lock);
4096 			return (buf);
4097 		}
4098 	}
4099 	mutex_exit(&cp->cache_depot_lock);
4100 
4101 	/* Hunt the per-CPU magazines. */
4102 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
4103 		ccp = &cp->cache_cpu[cpu_seqid];
4104 
4105 		mutex_enter(&ccp->cc_lock);
4106 		m = ccp->cc_loaded;
4107 		n = ccp->cc_rounds;
4108 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4109 			mutex_exit(&ccp->cc_lock);
4110 			return (buf);
4111 		}
4112 		m = ccp->cc_ploaded;
4113 		n = ccp->cc_prounds;
4114 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4115 			mutex_exit(&ccp->cc_lock);
4116 			return (buf);
4117 		}
4118 		mutex_exit(&ccp->cc_lock);
4119 	}
4120 
4121 	kmem_cache_free(cp, tbuf);
4122 	return (NULL);
4123 }
4124 
4125 /*
4126  * May be called from the kmem_move_taskq, from kmem_cache_move_notify_task(),
4127  * or when the buffer is freed.
4128  */
4129 static void
4130 kmem_slab_move_yes(kmem_cache_t *cp, kmem_slab_t *sp, void *from_buf)
4131 {
4132 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4133 	ASSERT(KMEM_SLAB_MEMBER(sp, from_buf));
4134 
4135 	if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4136 		return;
4137 	}
4138 
4139 	if (sp->slab_flags & KMEM_SLAB_NOMOVE) {
4140 		if (KMEM_SLAB_OFFSET(sp, from_buf) == sp->slab_stuck_offset) {
4141 			avl_remove(&cp->cache_partial_slabs, sp);
4142 			sp->slab_flags &= ~KMEM_SLAB_NOMOVE;
4143 			sp->slab_stuck_offset = (uint32_t)-1;
4144 			avl_add(&cp->cache_partial_slabs, sp);
4145 		}
4146 	} else {
4147 		sp->slab_later_count = 0;
4148 		sp->slab_stuck_offset = (uint32_t)-1;
4149 	}
4150 }
4151 
4152 static void
4153 kmem_slab_move_no(kmem_cache_t *cp, kmem_slab_t *sp, void *from_buf)
4154 {
4155 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4156 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4157 	ASSERT(KMEM_SLAB_MEMBER(sp, from_buf));
4158 
4159 	if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4160 		return;
4161 	}
4162 
4163 	avl_remove(&cp->cache_partial_slabs, sp);
4164 	sp->slab_later_count = 0;
4165 	sp->slab_flags |= KMEM_SLAB_NOMOVE;
4166 	sp->slab_stuck_offset = KMEM_SLAB_OFFSET(sp, from_buf);
4167 	avl_add(&cp->cache_partial_slabs, sp);
4168 }
4169 
4170 static void kmem_move_end(kmem_cache_t *, kmem_move_t *);
4171 
4172 /*
4173  * The move callback takes two buffer addresses, the buffer to be moved, and a
4174  * newly allocated and constructed buffer selected by kmem as the destination.
4175  * It also takes the size of the buffer and an optional user argument specified
4176  * at cache creation time. kmem guarantees that the buffer to be moved has not
4177  * been unmapped by the virtual memory subsystem. Beyond that, it cannot
4178  * guarantee the present whereabouts of the buffer to be moved, so it is up to
4179  * the client to safely determine whether or not it is still using the buffer.
4180  * The client must not free either of the buffers passed to the move callback,
4181  * since kmem wants to free them directly to the slab layer. The client response
4182  * tells kmem which of the two buffers to free:
4183  *
4184  * YES		kmem frees the old buffer (the move was successful)
4185  * NO		kmem frees the new buffer, marks the slab of the old buffer
4186  *              non-reclaimable to avoid bothering the client again
4187  * LATER	kmem frees the new buffer, increments slab_later_count
4188  * DONT_KNOW	kmem frees the new buffer, searches mags for the old buffer
4189  * DONT_NEED	kmem frees both the old buffer and the new buffer
4190  *
4191  * The pending callback argument now being processed contains both of the
4192  * buffers (old and new) passed to the move callback function, the slab of the
4193  * old buffer, and flags related to the move request, such as whether or not the
4194  * system was desperate for memory.
4195  */
4196 static void
4197 kmem_move_buffer(kmem_move_t *callback)
4198 {
4199 	kmem_cbrc_t response;
4200 	kmem_slab_t *sp = callback->kmm_from_slab;
4201 	kmem_cache_t *cp = sp->slab_cache;
4202 	boolean_t free_on_slab;
4203 
4204 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4205 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4206 	ASSERT(KMEM_SLAB_MEMBER(sp, callback->kmm_from_buf));
4207 
4208 	/*
4209 	 * The number of allocated buffers on the slab may have changed since we
4210 	 * last checked the slab's reclaimability (when the pending move was
4211 	 * enqueued), or the client may have responded NO when asked to move
4212 	 * another buffer on the same slab.
4213 	 */
4214 	if (!kmem_slab_is_reclaimable(cp, sp, callback->kmm_flags)) {
4215 		KMEM_STAT_ADD(kmem_move_stats.kms_no_longer_reclaimable);
4216 		KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY),
4217 		    kmem_move_stats.kms_notify_no_longer_reclaimable);
4218 		kmem_slab_free(cp, callback->kmm_to_buf);
4219 		kmem_move_end(cp, callback);
4220 		return;
4221 	}
4222 
4223 	/*
4224 	 * Hunting magazines is expensive, so we'll wait to do that until the
4225 	 * client responds KMEM_CBRC_DONT_KNOW. However, checking the slab layer
4226 	 * is cheap, so we might as well do that here in case we can avoid
4227 	 * bothering the client.
4228 	 */
4229 	mutex_enter(&cp->cache_lock);
4230 	free_on_slab = (kmem_slab_allocated(cp, sp,
4231 	    callback->kmm_from_buf) == NULL);
4232 	mutex_exit(&cp->cache_lock);
4233 
4234 	if (free_on_slab) {
4235 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_found_slab);
4236 		kmem_slab_free(cp, callback->kmm_to_buf);
4237 		kmem_move_end(cp, callback);
4238 		return;
4239 	}
4240 
4241 	if (cp->cache_flags & KMF_BUFTAG) {
4242 		/*
4243 		 * Make kmem_cache_alloc_debug() apply the constructor for us.
4244 		 */
4245 		if (kmem_cache_alloc_debug(cp, callback->kmm_to_buf,
4246 		    KM_NOSLEEP, 1, caller()) != 0) {
4247 			KMEM_STAT_ADD(kmem_move_stats.kms_alloc_fail);
4248 			kmem_move_end(cp, callback);
4249 			return;
4250 		}
4251 	} else if (cp->cache_constructor != NULL &&
4252 	    cp->cache_constructor(callback->kmm_to_buf, cp->cache_private,
4253 	    KM_NOSLEEP) != 0) {
4254 		atomic_add_64(&cp->cache_alloc_fail, 1);
4255 		KMEM_STAT_ADD(kmem_move_stats.kms_constructor_fail);
4256 		kmem_slab_free(cp, callback->kmm_to_buf);
4257 		kmem_move_end(cp, callback);
4258 		return;
4259 	}
4260 
4261 	KMEM_STAT_ADD(kmem_move_stats.kms_callbacks);
4262 	KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY),
4263 	    kmem_move_stats.kms_notify_callbacks);
4264 	cp->cache_defrag->kmd_callbacks++;
4265 	cp->cache_defrag->kmd_thread = curthread;
4266 	cp->cache_defrag->kmd_from_buf = callback->kmm_from_buf;
4267 	cp->cache_defrag->kmd_to_buf = callback->kmm_to_buf;
4268 	DTRACE_PROBE2(kmem__move__start, kmem_cache_t *, cp, kmem_move_t *,
4269 	    callback);
4270 
4271 	response = cp->cache_move(callback->kmm_from_buf,
4272 	    callback->kmm_to_buf, cp->cache_bufsize, cp->cache_private);
4273 
4274 	DTRACE_PROBE3(kmem__move__end, kmem_cache_t *, cp, kmem_move_t *,
4275 	    callback, kmem_cbrc_t, response);
4276 	cp->cache_defrag->kmd_thread = NULL;
4277 	cp->cache_defrag->kmd_from_buf = NULL;
4278 	cp->cache_defrag->kmd_to_buf = NULL;
4279 
4280 	if (response == KMEM_CBRC_YES) {
4281 		KMEM_STAT_ADD(kmem_move_stats.kms_yes);
4282 		cp->cache_defrag->kmd_yes++;
4283 		kmem_slab_free_constructed(cp, callback->kmm_from_buf, B_FALSE);
4284 		mutex_enter(&cp->cache_lock);
4285 		kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4286 		mutex_exit(&cp->cache_lock);
4287 		kmem_move_end(cp, callback);
4288 		return;
4289 	}
4290 
4291 	switch (response) {
4292 	case KMEM_CBRC_NO:
4293 		KMEM_STAT_ADD(kmem_move_stats.kms_no);
4294 		cp->cache_defrag->kmd_no++;
4295 		mutex_enter(&cp->cache_lock);
4296 		kmem_slab_move_no(cp, sp, callback->kmm_from_buf);
4297 		mutex_exit(&cp->cache_lock);
4298 		break;
4299 	case KMEM_CBRC_LATER:
4300 		KMEM_STAT_ADD(kmem_move_stats.kms_later);
4301 		cp->cache_defrag->kmd_later++;
4302 		mutex_enter(&cp->cache_lock);
4303 		if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4304 			mutex_exit(&cp->cache_lock);
4305 			break;
4306 		}
4307 
4308 		if (++sp->slab_later_count >= KMEM_DISBELIEF) {
4309 			KMEM_STAT_ADD(kmem_move_stats.kms_disbelief);
4310 			kmem_slab_move_no(cp, sp, callback->kmm_from_buf);
4311 		} else if (!(sp->slab_flags & KMEM_SLAB_NOMOVE)) {
4312 			sp->slab_stuck_offset = KMEM_SLAB_OFFSET(sp,
4313 			    callback->kmm_from_buf);
4314 		}
4315 		mutex_exit(&cp->cache_lock);
4316 		break;
4317 	case KMEM_CBRC_DONT_NEED:
4318 		KMEM_STAT_ADD(kmem_move_stats.kms_dont_need);
4319 		cp->cache_defrag->kmd_dont_need++;
4320 		kmem_slab_free_constructed(cp, callback->kmm_from_buf, B_FALSE);
4321 		mutex_enter(&cp->cache_lock);
4322 		kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4323 		mutex_exit(&cp->cache_lock);
4324 		break;
4325 	case KMEM_CBRC_DONT_KNOW:
4326 		KMEM_STAT_ADD(kmem_move_stats.kms_dont_know);
4327 		cp->cache_defrag->kmd_dont_know++;
4328 		if (kmem_hunt_mags(cp, callback->kmm_from_buf) != NULL) {
4329 			KMEM_STAT_ADD(kmem_move_stats.kms_hunt_found_mag);
4330 			cp->cache_defrag->kmd_hunt_found++;
4331 			kmem_slab_free_constructed(cp, callback->kmm_from_buf,
4332 			    B_TRUE);
4333 			mutex_enter(&cp->cache_lock);
4334 			kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4335 			mutex_exit(&cp->cache_lock);
4336 		}
4337 		break;
4338 	default:
4339 		panic("'%s' (%p) unexpected move callback response %d\n",
4340 		    cp->cache_name, (void *)cp, response);
4341 	}
4342 
4343 	kmem_slab_free_constructed(cp, callback->kmm_to_buf, B_FALSE);
4344 	kmem_move_end(cp, callback);
4345 }
4346 
4347 /* Return B_FALSE if there is insufficient memory for the move request. */
4348 static boolean_t
4349 kmem_move_begin(kmem_cache_t *cp, kmem_slab_t *sp, void *buf, int flags)
4350 {
4351 	void *to_buf;
4352 	avl_index_t index;
4353 	kmem_move_t *callback, *pending;
4354 
4355 	ASSERT(taskq_member(kmem_taskq, curthread));
4356 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4357 	ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4358 
4359 	callback = kmem_cache_alloc(kmem_move_cache, KM_NOSLEEP);
4360 	if (callback == NULL) {
4361 		KMEM_STAT_ADD(kmem_move_stats.kms_callback_alloc_fail);
4362 		return (B_FALSE);
4363 	}
4364 
4365 	callback->kmm_from_slab = sp;
4366 	callback->kmm_from_buf = buf;
4367 	callback->kmm_flags = flags;
4368 
4369 	mutex_enter(&cp->cache_lock);
4370 
4371 	if (avl_numnodes(&cp->cache_partial_slabs) <= 1) {
4372 		mutex_exit(&cp->cache_lock);
4373 		kmem_cache_free(kmem_move_cache, callback);
4374 		return (B_TRUE); /* there is no need for the move request */
4375 	}
4376 
4377 	pending = avl_find(&cp->cache_defrag->kmd_moves_pending, buf, &index);
4378 	if (pending != NULL) {
4379 		/*
4380 		 * If the move is already pending and we're desperate now,
4381 		 * update the move flags.
4382 		 */
4383 		if (flags & KMM_DESPERATE) {
4384 			pending->kmm_flags |= KMM_DESPERATE;
4385 		}
4386 		mutex_exit(&cp->cache_lock);
4387 		KMEM_STAT_ADD(kmem_move_stats.kms_already_pending);
4388 		kmem_cache_free(kmem_move_cache, callback);
4389 		return (B_TRUE);
4390 	}
4391 
4392 	to_buf = kmem_slab_alloc_impl(cp, avl_first(&cp->cache_partial_slabs));
4393 	callback->kmm_to_buf = to_buf;
4394 	avl_insert(&cp->cache_defrag->kmd_moves_pending, callback, index);
4395 
4396 	mutex_exit(&cp->cache_lock);
4397 
4398 	if (!taskq_dispatch(kmem_move_taskq, (task_func_t *)kmem_move_buffer,
4399 	    callback, TQ_NOSLEEP)) {
4400 		KMEM_STAT_ADD(kmem_move_stats.kms_callback_taskq_fail);
4401 		mutex_enter(&cp->cache_lock);
4402 		avl_remove(&cp->cache_defrag->kmd_moves_pending, callback);
4403 		mutex_exit(&cp->cache_lock);
4404 		kmem_slab_free(cp, to_buf);
4405 		kmem_cache_free(kmem_move_cache, callback);
4406 		return (B_FALSE);
4407 	}
4408 
4409 	return (B_TRUE);
4410 }
4411 
4412 static void
4413 kmem_move_end(kmem_cache_t *cp, kmem_move_t *callback)
4414 {
4415 	avl_index_t index;
4416 
4417 	ASSERT(cp->cache_defrag != NULL);
4418 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4419 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4420 
4421 	mutex_enter(&cp->cache_lock);
4422 	VERIFY(avl_find(&cp->cache_defrag->kmd_moves_pending,
4423 	    callback->kmm_from_buf, &index) != NULL);
4424 	avl_remove(&cp->cache_defrag->kmd_moves_pending, callback);
4425 	if (avl_is_empty(&cp->cache_defrag->kmd_moves_pending)) {
4426 		list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
4427 		kmem_slab_t *sp;
4428 
4429 		/*
4430 		 * The last pending move completed. Release all slabs from the
4431 		 * front of the dead list except for any slab at the tail that
4432 		 * needs to be released from the context of kmem_move_buffers().
4433 		 * kmem deferred unmapping the buffers on these slabs in order
4434 		 * to guarantee that buffers passed to the move callback have
4435 		 * been touched only by kmem or by the client itself.
4436 		 */
4437 		while ((sp = list_remove_head(deadlist)) != NULL) {
4438 			if (sp->slab_flags & KMEM_SLAB_MOVE_PENDING) {
4439 				list_insert_tail(deadlist, sp);
4440 				break;
4441 			}
4442 			cp->cache_defrag->kmd_deadcount--;
4443 			cp->cache_slab_destroy++;
4444 			mutex_exit(&cp->cache_lock);
4445 			kmem_slab_destroy(cp, sp);
4446 			KMEM_STAT_ADD(kmem_move_stats.kms_dead_slabs_freed);
4447 			mutex_enter(&cp->cache_lock);
4448 		}
4449 	}
4450 	mutex_exit(&cp->cache_lock);
4451 	kmem_cache_free(kmem_move_cache, callback);
4452 }
4453 
4454 /*
4455  * Move buffers from least used slabs first by scanning backwards from the end
4456  * of the partial slab list. Scan at most max_scan candidate slabs and move
4457  * buffers from at most max_slabs slabs (0 for all partial slabs in both cases).
4458  * If desperate to reclaim memory, move buffers from any partial slab, otherwise
4459  * skip slabs with a ratio of allocated buffers at or above the current
4460  * threshold. Return the number of unskipped slabs (at most max_slabs, -1 if the
4461  * scan is aborted) so that the caller can adjust the reclaimability threshold
4462  * depending on how many reclaimable slabs it finds.
4463  *
4464  * kmem_move_buffers() drops and reacquires cache_lock every time it issues a
4465  * move request, since it is not valid for kmem_move_begin() to call
4466  * kmem_cache_alloc() or taskq_dispatch() with cache_lock held.
4467  */
4468 static int
4469 kmem_move_buffers(kmem_cache_t *cp, size_t max_scan, size_t max_slabs,
4470     int flags)
4471 {
4472 	kmem_slab_t *sp;
4473 	void *buf;
4474 	int i, j; /* slab index, buffer index */
4475 	int s; /* reclaimable slabs */
4476 	int b; /* allocated (movable) buffers on reclaimable slab */
4477 	boolean_t success;
4478 	int refcnt;
4479 	int nomove;
4480 
4481 	ASSERT(taskq_member(kmem_taskq, curthread));
4482 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4483 	ASSERT(kmem_move_cache != NULL);
4484 	ASSERT(cp->cache_move != NULL && cp->cache_defrag != NULL);
4485 	ASSERT(avl_numnodes(&cp->cache_partial_slabs) > 1);
4486 
4487 	if (kmem_move_blocked) {
4488 		return (0);
4489 	}
4490 
4491 	if (kmem_move_fulltilt) {
4492 		max_slabs = 0;
4493 		flags |= KMM_DESPERATE;
4494 	}
4495 
4496 	if (max_scan == 0 || (flags & KMM_DESPERATE)) {
4497 		/*
4498 		 * Scan as many slabs as needed to find the desired number of
4499 		 * candidate slabs.
4500 		 */
4501 		max_scan = (size_t)-1;
4502 	}
4503 
4504 	if (max_slabs == 0 || (flags & KMM_DESPERATE)) {
4505 		/* Find as many candidate slabs as possible. */
4506 		max_slabs = (size_t)-1;
4507 	}
4508 
4509 	sp = avl_last(&cp->cache_partial_slabs);
4510 	ASSERT(sp != NULL && KMEM_SLAB_IS_PARTIAL(sp));
4511 	for (i = 0, s = 0; (i < max_scan) && (s < max_slabs) &&
4512 	    (sp != avl_first(&cp->cache_partial_slabs));
4513 	    sp = AVL_PREV(&cp->cache_partial_slabs, sp), i++) {
4514 
4515 		if (!kmem_slab_is_reclaimable(cp, sp, flags)) {
4516 			continue;
4517 		}
4518 		s++;
4519 
4520 		/* Look for allocated buffers to move. */
4521 		for (j = 0, b = 0, buf = sp->slab_base;
4522 		    (j < sp->slab_chunks) && (b < sp->slab_refcnt);
4523 		    buf = (((char *)buf) + cp->cache_chunksize), j++) {
4524 
4525 			if (kmem_slab_allocated(cp, sp, buf) == NULL) {
4526 				continue;
4527 			}
4528 
4529 			b++;
4530 
4531 			/*
4532 			 * Prevent the slab from being destroyed while we drop
4533 			 * cache_lock and while the pending move is not yet
4534 			 * registered. Flag the pending move while
4535 			 * kmd_moves_pending may still be empty, since we can't
4536 			 * yet rely on a non-zero pending move count to prevent
4537 			 * the slab from being destroyed.
4538 			 */
4539 			ASSERT(!(sp->slab_flags & KMEM_SLAB_MOVE_PENDING));
4540 			sp->slab_flags |= KMEM_SLAB_MOVE_PENDING;
4541 			/*
4542 			 * Recheck refcnt and nomove after reacquiring the lock,
4543 			 * since these control the order of partial slabs, and
4544 			 * we want to know if we can pick up the scan where we
4545 			 * left off.
4546 			 */
4547 			refcnt = sp->slab_refcnt;
4548 			nomove = (sp->slab_flags & KMEM_SLAB_NOMOVE);
4549 			mutex_exit(&cp->cache_lock);
4550 
4551 			success = kmem_move_begin(cp, sp, buf, flags);
4552 
4553 			/*
4554 			 * Now, before the lock is reacquired, kmem could
4555 			 * process all pending move requests and purge the
4556 			 * deadlist, so that upon reacquiring the lock, sp has
4557 			 * been remapped. Therefore, the KMEM_SLAB_MOVE_PENDING
4558 			 * flag causes the slab to be put at the end of the
4559 			 * deadlist and prevents it from being purged, since we
4560 			 * plan to destroy it here after reacquiring the lock.
4561 			 */
4562 			mutex_enter(&cp->cache_lock);
4563 			ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4564 			sp->slab_flags &= ~KMEM_SLAB_MOVE_PENDING;
4565 
4566 			/*
4567 			 * Destroy the slab now if it was completely freed while
4568 			 * we dropped cache_lock.
4569 			 */
4570 			if (sp->slab_refcnt == 0) {
4571 				list_t *deadlist =
4572 				    &cp->cache_defrag->kmd_deadlist;
4573 
4574 				ASSERT(!list_is_empty(deadlist));
4575 				ASSERT(list_link_active((list_node_t *)
4576 				    &sp->slab_link));
4577 
4578 				list_remove(deadlist, sp);
4579 				cp->cache_defrag->kmd_deadcount--;
4580 				cp->cache_slab_destroy++;
4581 				mutex_exit(&cp->cache_lock);
4582 				kmem_slab_destroy(cp, sp);
4583 				KMEM_STAT_ADD(kmem_move_stats.
4584 				    kms_dead_slabs_freed);
4585 				KMEM_STAT_ADD(kmem_move_stats.
4586 				    kms_endscan_slab_destroyed);
4587 				mutex_enter(&cp->cache_lock);
4588 				/*
4589 				 * Since we can't pick up the scan where we left
4590 				 * off, abort the scan and say nothing about the
4591 				 * number of reclaimable slabs.
4592 				 */
4593 				return (-1);
4594 			}
4595 
4596 			if (!success) {
4597 				/*
4598 				 * Abort the scan if there is not enough memory
4599 				 * for the request and say nothing about the
4600 				 * number of reclaimable slabs.
4601 				 */
4602 				KMEM_STAT_ADD(
4603 				    kmem_move_stats.kms_endscan_nomem);
4604 				return (-1);
4605 			}
4606 
4607 			/*
4608 			 * The slab may have been completely allocated while the
4609 			 * lock was dropped.
4610 			 */
4611 			if (KMEM_SLAB_IS_ALL_USED(sp)) {
4612 				KMEM_STAT_ADD(
4613 				    kmem_move_stats.kms_endscan_slab_all_used);
4614 				return (-1);
4615 			}
4616 
4617 			/*
4618 			 * The slab's position changed while the lock was
4619 			 * dropped, so we don't know where we are in the
4620 			 * sequence any more.
4621 			 */
4622 			if (sp->slab_refcnt != refcnt) {
4623 				KMEM_STAT_ADD(
4624 				    kmem_move_stats.kms_endscan_refcnt_changed);
4625 				return (-1);
4626 			}
4627 			if ((sp->slab_flags & KMEM_SLAB_NOMOVE) != nomove) {
4628 				KMEM_STAT_ADD(
4629 				    kmem_move_stats.kms_endscan_nomove_changed);
4630 				return (-1);
4631 			}
4632 
4633 			/*
4634 			 * Generating a move request allocates a destination
4635 			 * buffer from the slab layer, bumping the first slab if
4636 			 * it is completely allocated.
4637 			 */
4638 			ASSERT(!avl_is_empty(&cp->cache_partial_slabs));
4639 			if (sp == avl_first(&cp->cache_partial_slabs)) {
4640 				goto end_scan;
4641 			}
4642 		}
4643 	}
4644 end_scan:
4645 
4646 	KMEM_STAT_COND_ADD(sp == avl_first(&cp->cache_partial_slabs),
4647 	    kmem_move_stats.kms_endscan_freelist);
4648 
4649 	return (s);
4650 }
4651 
4652 typedef struct kmem_move_notify_args {
4653 	kmem_cache_t *kmna_cache;
4654 	void *kmna_buf;
4655 } kmem_move_notify_args_t;
4656 
4657 static void
4658 kmem_cache_move_notify_task(void *arg)
4659 {
4660 	kmem_move_notify_args_t *args = arg;
4661 	kmem_cache_t *cp = args->kmna_cache;
4662 	void *buf = args->kmna_buf;
4663 	kmem_slab_t *sp;
4664 
4665 	ASSERT(taskq_member(kmem_taskq, curthread));
4666 	ASSERT(list_link_active(&cp->cache_link));
4667 
4668 	kmem_free(args, sizeof (kmem_move_notify_args_t));
4669 	mutex_enter(&cp->cache_lock);
4670 	sp = kmem_slab_allocated(cp, NULL, buf);
4671 
4672 	/* Ignore the notification if the buffer is no longer allocated. */
4673 	if (sp == NULL) {
4674 		mutex_exit(&cp->cache_lock);
4675 		return;
4676 	}
4677 
4678 	/* Ignore the notification if there's no reason to move the buffer. */
4679 	if (avl_numnodes(&cp->cache_partial_slabs) > 1) {
4680 		/*
4681 		 * So far the notification is not ignored. Ignore the
4682 		 * notification if the slab is not marked by an earlier refusal
4683 		 * to move a buffer.
4684 		 */
4685 		if (!(sp->slab_flags & KMEM_SLAB_NOMOVE) &&
4686 		    (sp->slab_later_count == 0)) {
4687 			mutex_exit(&cp->cache_lock);
4688 			return;
4689 		}
4690 
4691 		kmem_slab_move_yes(cp, sp, buf);
4692 		ASSERT(!(sp->slab_flags & KMEM_SLAB_MOVE_PENDING));
4693 		sp->slab_flags |= KMEM_SLAB_MOVE_PENDING;
4694 		mutex_exit(&cp->cache_lock);
4695 		/* see kmem_move_buffers() about dropping the lock */
4696 		(void) kmem_move_begin(cp, sp, buf, KMM_NOTIFY);
4697 		mutex_enter(&cp->cache_lock);
4698 		ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4699 		sp->slab_flags &= ~KMEM_SLAB_MOVE_PENDING;
4700 		if (sp->slab_refcnt == 0) {
4701 			list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
4702 
4703 			ASSERT(!list_is_empty(deadlist));
4704 			ASSERT(list_link_active((list_node_t *)
4705 			    &sp->slab_link));
4706 
4707 			list_remove(deadlist, sp);
4708 			cp->cache_defrag->kmd_deadcount--;
4709 			cp->cache_slab_destroy++;
4710 			mutex_exit(&cp->cache_lock);
4711 			kmem_slab_destroy(cp, sp);
4712 			KMEM_STAT_ADD(kmem_move_stats.kms_dead_slabs_freed);
4713 			return;
4714 		}
4715 	} else {
4716 		kmem_slab_move_yes(cp, sp, buf);
4717 	}
4718 	mutex_exit(&cp->cache_lock);
4719 }
4720 
4721 void
4722 kmem_cache_move_notify(kmem_cache_t *cp, void *buf)
4723 {
4724 	kmem_move_notify_args_t *args;
4725 
4726 	KMEM_STAT_ADD(kmem_move_stats.kms_notify);
4727 	args = kmem_alloc(sizeof (kmem_move_notify_args_t), KM_NOSLEEP);
4728 	if (args != NULL) {
4729 		args->kmna_cache = cp;
4730 		args->kmna_buf = buf;
4731 		if (!taskq_dispatch(kmem_taskq,
4732 		    (task_func_t *)kmem_cache_move_notify_task, args,
4733 		    TQ_NOSLEEP))
4734 			kmem_free(args, sizeof (kmem_move_notify_args_t));
4735 	}
4736 }
4737 
4738 static void
4739 kmem_cache_defrag(kmem_cache_t *cp)
4740 {
4741 	size_t n;
4742 
4743 	ASSERT(cp->cache_defrag != NULL);
4744 
4745 	mutex_enter(&cp->cache_lock);
4746 	n = avl_numnodes(&cp->cache_partial_slabs);
4747 	if (n > 1) {
4748 		/* kmem_move_buffers() drops and reacquires cache_lock */
4749 		(void) kmem_move_buffers(cp, n, 0, KMM_DESPERATE);
4750 		KMEM_STAT_ADD(kmem_move_stats.kms_defrags);
4751 	}
4752 	mutex_exit(&cp->cache_lock);
4753 }
4754 
4755 /* Is this cache above the fragmentation threshold? */
4756 static boolean_t
4757 kmem_cache_frag_threshold(kmem_cache_t *cp, uint64_t nfree)
4758 {
4759 	if (avl_numnodes(&cp->cache_partial_slabs) <= 1)
4760 		return (B_FALSE);
4761 
4762 	/*
4763 	 *	nfree		kmem_frag_numer
4764 	 * ------------------ > ---------------
4765 	 * cp->cache_buftotal	kmem_frag_denom
4766 	 */
4767 	return ((nfree * kmem_frag_denom) >
4768 	    (cp->cache_buftotal * kmem_frag_numer));
4769 }
4770 
4771 static boolean_t
4772 kmem_cache_is_fragmented(kmem_cache_t *cp, boolean_t *doreap)
4773 {
4774 	boolean_t fragmented;
4775 	uint64_t nfree;
4776 
4777 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4778 	*doreap = B_FALSE;
4779 
4780 	if (!kmem_move_fulltilt && ((cp->cache_complete_slab_count +
4781 	    avl_numnodes(&cp->cache_partial_slabs)) < kmem_frag_minslabs))
4782 		return (B_FALSE);
4783 
4784 	nfree = cp->cache_bufslab;
4785 	fragmented = kmem_cache_frag_threshold(cp, nfree);
4786 	/*
4787 	 * Free buffers in the magazine layer appear allocated from the point of
4788 	 * view of the slab layer. We want to know if the slab layer would
4789 	 * appear fragmented if we included free buffers from magazines that
4790 	 * have fallen out of the working set.
4791 	 */
4792 	if (!fragmented) {
4793 		long reap;
4794 
4795 		mutex_enter(&cp->cache_depot_lock);
4796 		reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
4797 		reap = MIN(reap, cp->cache_full.ml_total);
4798 		mutex_exit(&cp->cache_depot_lock);
4799 
4800 		nfree += ((uint64_t)reap * cp->cache_magtype->mt_magsize);
4801 		if (kmem_cache_frag_threshold(cp, nfree)) {
4802 			*doreap = B_TRUE;
4803 		}
4804 	}
4805 
4806 	return (fragmented);
4807 }
4808 
4809 /* Called periodically from kmem_taskq */
4810 static void
4811 kmem_cache_scan(kmem_cache_t *cp)
4812 {
4813 	boolean_t reap = B_FALSE;
4814 
4815 	ASSERT(taskq_member(kmem_taskq, curthread));
4816 	ASSERT(cp->cache_defrag != NULL);
4817 
4818 	mutex_enter(&cp->cache_lock);
4819 
4820 	if (kmem_cache_is_fragmented(cp, &reap)) {
4821 		kmem_defrag_t *kmd = cp->cache_defrag;
4822 		size_t slabs_found;
4823 
4824 		/*
4825 		 * Consolidate reclaimable slabs from the end of the partial
4826 		 * slab list (scan at most kmem_reclaim_scan_range slabs to find
4827 		 * reclaimable slabs). Keep track of how many candidate slabs we
4828 		 * looked for and how many we actually found so we can adjust
4829 		 * the definition of a candidate slab if we're having trouble
4830 		 * finding them.
4831 		 *
4832 		 * kmem_move_buffers() drops and reacquires cache_lock.
4833 		 */
4834 		slabs_found = kmem_move_buffers(cp, kmem_reclaim_scan_range,
4835 		    kmem_reclaim_max_slabs, 0);
4836 		if (slabs_found >= 0) {
4837 			kmd->kmd_slabs_sought += kmem_reclaim_max_slabs;
4838 			kmd->kmd_slabs_found += slabs_found;
4839 		}
4840 
4841 		if (++kmd->kmd_scans >= kmem_reclaim_scan_range) {
4842 			kmd->kmd_scans = 0;
4843 
4844 			/*
4845 			 * If we had difficulty finding candidate slabs in
4846 			 * previous scans, adjust the threshold so that
4847 			 * candidates are easier to find.
4848 			 */
4849 			if (kmd->kmd_slabs_found == kmd->kmd_slabs_sought) {
4850 				kmem_adjust_reclaim_threshold(kmd, -1);
4851 			} else if ((kmd->kmd_slabs_found * 2) <
4852 			    kmd->kmd_slabs_sought) {
4853 				kmem_adjust_reclaim_threshold(kmd, 1);
4854 			}
4855 			kmd->kmd_slabs_sought = 0;
4856 			kmd->kmd_slabs_found = 0;
4857 		}
4858 	} else {
4859 		kmem_reset_reclaim_threshold(cp->cache_defrag);
4860 #ifdef	DEBUG
4861 		if (avl_numnodes(&cp->cache_partial_slabs) > 1) {
4862 			/*
4863 			 * In a debug kernel we want the consolidator to
4864 			 * run occasionally even when there is plenty of
4865 			 * memory.
4866 			 */
4867 			uint32_t debug_rand;
4868 
4869 			(void) random_get_bytes((uint8_t *)&debug_rand, 4);
4870 			if (!kmem_move_noreap &&
4871 			    ((debug_rand % kmem_mtb_reap) == 0)) {
4872 				mutex_exit(&cp->cache_lock);
4873 				kmem_cache_reap(cp);
4874 				KMEM_STAT_ADD(kmem_move_stats.kms_debug_reaps);
4875 				return;
4876 			} else if ((debug_rand % kmem_mtb_move) == 0) {
4877 				(void) kmem_move_buffers(cp,
4878 				    kmem_reclaim_scan_range, 1, 0);
4879 				KMEM_STAT_ADD(kmem_move_stats.
4880 				    kms_debug_move_scans);
4881 			}
4882 		}
4883 #endif	/* DEBUG */
4884 	}
4885 
4886 	mutex_exit(&cp->cache_lock);
4887 
4888 	if (reap) {
4889 		KMEM_STAT_ADD(kmem_move_stats.kms_scan_depot_ws_reaps);
4890 		kmem_depot_ws_reap(cp);
4891 	}
4892 }
4893