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