xref: /illumos-gate/usr/src/uts/common/os/kmem.c (revision 24b9abbad58fdd63dad716fd35a99a7944c4e3eb)
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 static boolean_t kmem_mp_init_done = B_FALSE;
989 
990 static kmem_cache_t	*kmem_slab_cache;
991 static kmem_cache_t	*kmem_bufctl_cache;
992 static kmem_cache_t	*kmem_bufctl_audit_cache;
993 
994 static kmutex_t		kmem_cache_lock;	/* inter-cache linkage only */
995 static list_t		kmem_caches;
996 
997 static taskq_t		*kmem_taskq;
998 static kmutex_t		kmem_flags_lock;
999 static vmem_t		*kmem_metadata_arena;
1000 static vmem_t		*kmem_msb_arena;	/* arena for metadata caches */
1001 static vmem_t		*kmem_cache_arena;
1002 static vmem_t		*kmem_hash_arena;
1003 static vmem_t		*kmem_log_arena;
1004 static vmem_t		*kmem_oversize_arena;
1005 static vmem_t		*kmem_va_arena;
1006 static vmem_t		*kmem_default_arena;
1007 static vmem_t		*kmem_firewall_va_arena;
1008 static vmem_t		*kmem_firewall_arena;
1009 
1010 /*
1011  * Define KMEM_STATS to turn on statistic gathering. By default, it is only
1012  * turned on when DEBUG is also defined.
1013  */
1014 #ifdef	DEBUG
1015 #define	KMEM_STATS
1016 #endif	/* DEBUG */
1017 
1018 #ifdef	KMEM_STATS
1019 #define	KMEM_STAT_ADD(stat)			((stat)++)
1020 #define	KMEM_STAT_COND_ADD(cond, stat)		((void) (!(cond) || (stat)++))
1021 #else
1022 #define	KMEM_STAT_ADD(stat)			/* nothing */
1023 #define	KMEM_STAT_COND_ADD(cond, stat)		/* nothing */
1024 #endif	/* KMEM_STATS */
1025 
1026 /*
1027  * kmem slab consolidator thresholds (tunables)
1028  */
1029 static size_t kmem_frag_minslabs = 101;	/* minimum total slabs */
1030 static size_t kmem_frag_numer = 1;	/* free buffers (numerator) */
1031 static size_t kmem_frag_denom = KMEM_VOID_FRACTION; /* buffers (denominator) */
1032 /*
1033  * Maximum number of slabs from which to move buffers during a single
1034  * maintenance interval while the system is not low on memory.
1035  */
1036 static size_t kmem_reclaim_max_slabs = 1;
1037 /*
1038  * Number of slabs to scan backwards from the end of the partial slab list
1039  * when searching for buffers to relocate.
1040  */
1041 static size_t kmem_reclaim_scan_range = 12;
1042 
1043 #ifdef	KMEM_STATS
1044 static struct {
1045 	uint64_t kms_callbacks;
1046 	uint64_t kms_yes;
1047 	uint64_t kms_no;
1048 	uint64_t kms_later;
1049 	uint64_t kms_dont_need;
1050 	uint64_t kms_dont_know;
1051 	uint64_t kms_hunt_found_slab;
1052 	uint64_t kms_hunt_found_mag;
1053 	uint64_t kms_hunt_alloc_fail;
1054 	uint64_t kms_hunt_lucky;
1055 	uint64_t kms_notify;
1056 	uint64_t kms_notify_callbacks;
1057 	uint64_t kms_disbelief;
1058 	uint64_t kms_already_pending;
1059 	uint64_t kms_callback_alloc_fail;
1060 	uint64_t kms_callback_taskq_fail;
1061 	uint64_t kms_endscan_slab_destroyed;
1062 	uint64_t kms_endscan_nomem;
1063 	uint64_t kms_endscan_slab_all_used;
1064 	uint64_t kms_endscan_refcnt_changed;
1065 	uint64_t kms_endscan_nomove_changed;
1066 	uint64_t kms_endscan_freelist;
1067 	uint64_t kms_avl_update;
1068 	uint64_t kms_avl_noupdate;
1069 	uint64_t kms_no_longer_reclaimable;
1070 	uint64_t kms_notify_no_longer_reclaimable;
1071 	uint64_t kms_alloc_fail;
1072 	uint64_t kms_constructor_fail;
1073 	uint64_t kms_dead_slabs_freed;
1074 	uint64_t kms_defrags;
1075 	uint64_t kms_scan_depot_ws_reaps;
1076 	uint64_t kms_debug_reaps;
1077 	uint64_t kms_debug_move_scans;
1078 } kmem_move_stats;
1079 #endif	/* KMEM_STATS */
1080 
1081 /* consolidator knobs */
1082 static boolean_t kmem_move_noreap;
1083 static boolean_t kmem_move_blocked;
1084 static boolean_t kmem_move_fulltilt;
1085 static boolean_t kmem_move_any_partial;
1086 
1087 #ifdef	DEBUG
1088 /*
1089  * Ensure code coverage by occasionally running the consolidator even when the
1090  * caches are not fragmented (they may never be). These intervals are mean time
1091  * in cache maintenance intervals (kmem_cache_update).
1092  */
1093 static int kmem_mtb_move = 60;		/* defrag 1 slab (~15min) */
1094 static int kmem_mtb_reap = 1800;	/* defrag all slabs (~7.5hrs) */
1095 #endif	/* DEBUG */
1096 
1097 static kmem_cache_t	*kmem_defrag_cache;
1098 static kmem_cache_t	*kmem_move_cache;
1099 static taskq_t		*kmem_move_taskq;
1100 
1101 static void kmem_cache_scan(kmem_cache_t *);
1102 static void kmem_cache_defrag(kmem_cache_t *);
1103 
1104 
1105 kmem_log_header_t	*kmem_transaction_log;
1106 kmem_log_header_t	*kmem_content_log;
1107 kmem_log_header_t	*kmem_failure_log;
1108 kmem_log_header_t	*kmem_slab_log;
1109 
1110 static int		kmem_lite_count; /* # of PCs in kmem_buftag_lite_t */
1111 
1112 #define	KMEM_BUFTAG_LITE_ENTER(bt, count, caller)			\
1113 	if ((count) > 0) {						\
1114 		pc_t *_s = ((kmem_buftag_lite_t *)(bt))->bt_history;	\
1115 		pc_t *_e;						\
1116 		/* memmove() the old entries down one notch */		\
1117 		for (_e = &_s[(count) - 1]; _e > _s; _e--)		\
1118 			*_e = *(_e - 1);				\
1119 		*_s = (uintptr_t)(caller);				\
1120 	}
1121 
1122 #define	KMERR_MODIFIED	0	/* buffer modified while on freelist */
1123 #define	KMERR_REDZONE	1	/* redzone violation (write past end of buf) */
1124 #define	KMERR_DUPFREE	2	/* freed a buffer twice */
1125 #define	KMERR_BADADDR	3	/* freed a bad (unallocated) address */
1126 #define	KMERR_BADBUFTAG	4	/* buftag corrupted */
1127 #define	KMERR_BADBUFCTL	5	/* bufctl corrupted */
1128 #define	KMERR_BADCACHE	6	/* freed a buffer to the wrong cache */
1129 #define	KMERR_BADSIZE	7	/* alloc size != free size */
1130 #define	KMERR_BADBASE	8	/* buffer base address wrong */
1131 
1132 struct {
1133 	hrtime_t	kmp_timestamp;	/* timestamp of panic */
1134 	int		kmp_error;	/* type of kmem error */
1135 	void		*kmp_buffer;	/* buffer that induced panic */
1136 	void		*kmp_realbuf;	/* real start address for buffer */
1137 	kmem_cache_t	*kmp_cache;	/* buffer's cache according to client */
1138 	kmem_cache_t	*kmp_realcache;	/* actual cache containing buffer */
1139 	kmem_slab_t	*kmp_slab;	/* slab accoring to kmem_findslab() */
1140 	kmem_bufctl_t	*kmp_bufctl;	/* bufctl */
1141 } kmem_panic_info;
1142 
1143 
1144 static void
1145 copy_pattern(uint64_t pattern, void *buf_arg, size_t size)
1146 {
1147 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1148 	uint64_t *buf = buf_arg;
1149 
1150 	while (buf < bufend)
1151 		*buf++ = pattern;
1152 }
1153 
1154 static void *
1155 verify_pattern(uint64_t pattern, void *buf_arg, size_t size)
1156 {
1157 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1158 	uint64_t *buf;
1159 
1160 	for (buf = buf_arg; buf < bufend; buf++)
1161 		if (*buf != pattern)
1162 			return (buf);
1163 	return (NULL);
1164 }
1165 
1166 static void *
1167 verify_and_copy_pattern(uint64_t old, uint64_t new, void *buf_arg, size_t size)
1168 {
1169 	uint64_t *bufend = (uint64_t *)((char *)buf_arg + size);
1170 	uint64_t *buf;
1171 
1172 	for (buf = buf_arg; buf < bufend; buf++) {
1173 		if (*buf != old) {
1174 			copy_pattern(old, buf_arg,
1175 			    (char *)buf - (char *)buf_arg);
1176 			return (buf);
1177 		}
1178 		*buf = new;
1179 	}
1180 
1181 	return (NULL);
1182 }
1183 
1184 static void
1185 kmem_cache_applyall(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
1186 {
1187 	kmem_cache_t *cp;
1188 
1189 	mutex_enter(&kmem_cache_lock);
1190 	for (cp = list_head(&kmem_caches); cp != NULL;
1191 	    cp = list_next(&kmem_caches, cp))
1192 		if (tq != NULL)
1193 			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
1194 			    tqflag);
1195 		else
1196 			func(cp);
1197 	mutex_exit(&kmem_cache_lock);
1198 }
1199 
1200 static void
1201 kmem_cache_applyall_id(void (*func)(kmem_cache_t *), taskq_t *tq, int tqflag)
1202 {
1203 	kmem_cache_t *cp;
1204 
1205 	mutex_enter(&kmem_cache_lock);
1206 	for (cp = list_head(&kmem_caches); cp != NULL;
1207 	    cp = list_next(&kmem_caches, cp)) {
1208 		if (!(cp->cache_cflags & KMC_IDENTIFIER))
1209 			continue;
1210 		if (tq != NULL)
1211 			(void) taskq_dispatch(tq, (task_func_t *)func, cp,
1212 			    tqflag);
1213 		else
1214 			func(cp);
1215 	}
1216 	mutex_exit(&kmem_cache_lock);
1217 }
1218 
1219 /*
1220  * Debugging support.  Given a buffer address, find its slab.
1221  */
1222 static kmem_slab_t *
1223 kmem_findslab(kmem_cache_t *cp, void *buf)
1224 {
1225 	kmem_slab_t *sp;
1226 
1227 	mutex_enter(&cp->cache_lock);
1228 	for (sp = list_head(&cp->cache_complete_slabs); sp != NULL;
1229 	    sp = list_next(&cp->cache_complete_slabs, sp)) {
1230 		if (KMEM_SLAB_MEMBER(sp, buf)) {
1231 			mutex_exit(&cp->cache_lock);
1232 			return (sp);
1233 		}
1234 	}
1235 	for (sp = avl_first(&cp->cache_partial_slabs); sp != NULL;
1236 	    sp = AVL_NEXT(&cp->cache_partial_slabs, sp)) {
1237 		if (KMEM_SLAB_MEMBER(sp, buf)) {
1238 			mutex_exit(&cp->cache_lock);
1239 			return (sp);
1240 		}
1241 	}
1242 	mutex_exit(&cp->cache_lock);
1243 
1244 	return (NULL);
1245 }
1246 
1247 static void
1248 kmem_error(int error, kmem_cache_t *cparg, void *bufarg)
1249 {
1250 	kmem_buftag_t *btp = NULL;
1251 	kmem_bufctl_t *bcp = NULL;
1252 	kmem_cache_t *cp = cparg;
1253 	kmem_slab_t *sp;
1254 	uint64_t *off;
1255 	void *buf = bufarg;
1256 
1257 	kmem_logging = 0;	/* stop logging when a bad thing happens */
1258 
1259 	kmem_panic_info.kmp_timestamp = gethrtime();
1260 
1261 	sp = kmem_findslab(cp, buf);
1262 	if (sp == NULL) {
1263 		for (cp = list_tail(&kmem_caches); cp != NULL;
1264 		    cp = list_prev(&kmem_caches, cp)) {
1265 			if ((sp = kmem_findslab(cp, buf)) != NULL)
1266 				break;
1267 		}
1268 	}
1269 
1270 	if (sp == NULL) {
1271 		cp = NULL;
1272 		error = KMERR_BADADDR;
1273 	} else {
1274 		if (cp != cparg)
1275 			error = KMERR_BADCACHE;
1276 		else
1277 			buf = (char *)bufarg - ((uintptr_t)bufarg -
1278 			    (uintptr_t)sp->slab_base) % cp->cache_chunksize;
1279 		if (buf != bufarg)
1280 			error = KMERR_BADBASE;
1281 		if (cp->cache_flags & KMF_BUFTAG)
1282 			btp = KMEM_BUFTAG(cp, buf);
1283 		if (cp->cache_flags & KMF_HASH) {
1284 			mutex_enter(&cp->cache_lock);
1285 			for (bcp = *KMEM_HASH(cp, buf); bcp; bcp = bcp->bc_next)
1286 				if (bcp->bc_addr == buf)
1287 					break;
1288 			mutex_exit(&cp->cache_lock);
1289 			if (bcp == NULL && btp != NULL)
1290 				bcp = btp->bt_bufctl;
1291 			if (kmem_findslab(cp->cache_bufctl_cache, bcp) ==
1292 			    NULL || P2PHASE((uintptr_t)bcp, KMEM_ALIGN) ||
1293 			    bcp->bc_addr != buf) {
1294 				error = KMERR_BADBUFCTL;
1295 				bcp = NULL;
1296 			}
1297 		}
1298 	}
1299 
1300 	kmem_panic_info.kmp_error = error;
1301 	kmem_panic_info.kmp_buffer = bufarg;
1302 	kmem_panic_info.kmp_realbuf = buf;
1303 	kmem_panic_info.kmp_cache = cparg;
1304 	kmem_panic_info.kmp_realcache = cp;
1305 	kmem_panic_info.kmp_slab = sp;
1306 	kmem_panic_info.kmp_bufctl = bcp;
1307 
1308 	printf("kernel memory allocator: ");
1309 
1310 	switch (error) {
1311 
1312 	case KMERR_MODIFIED:
1313 		printf("buffer modified after being freed\n");
1314 		off = verify_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1315 		if (off == NULL)	/* shouldn't happen */
1316 			off = buf;
1317 		printf("modification occurred at offset 0x%lx "
1318 		    "(0x%llx replaced by 0x%llx)\n",
1319 		    (uintptr_t)off - (uintptr_t)buf,
1320 		    (longlong_t)KMEM_FREE_PATTERN, (longlong_t)*off);
1321 		break;
1322 
1323 	case KMERR_REDZONE:
1324 		printf("redzone violation: write past end of buffer\n");
1325 		break;
1326 
1327 	case KMERR_BADADDR:
1328 		printf("invalid free: buffer not in cache\n");
1329 		break;
1330 
1331 	case KMERR_DUPFREE:
1332 		printf("duplicate free: buffer freed twice\n");
1333 		break;
1334 
1335 	case KMERR_BADBUFTAG:
1336 		printf("boundary tag corrupted\n");
1337 		printf("bcp ^ bxstat = %lx, should be %lx\n",
1338 		    (intptr_t)btp->bt_bufctl ^ btp->bt_bxstat,
1339 		    KMEM_BUFTAG_FREE);
1340 		break;
1341 
1342 	case KMERR_BADBUFCTL:
1343 		printf("bufctl corrupted\n");
1344 		break;
1345 
1346 	case KMERR_BADCACHE:
1347 		printf("buffer freed to wrong cache\n");
1348 		printf("buffer was allocated from %s,\n", cp->cache_name);
1349 		printf("caller attempting free to %s.\n", cparg->cache_name);
1350 		break;
1351 
1352 	case KMERR_BADSIZE:
1353 		printf("bad free: free size (%u) != alloc size (%u)\n",
1354 		    KMEM_SIZE_DECODE(((uint32_t *)btp)[0]),
1355 		    KMEM_SIZE_DECODE(((uint32_t *)btp)[1]));
1356 		break;
1357 
1358 	case KMERR_BADBASE:
1359 		printf("bad free: free address (%p) != alloc address (%p)\n",
1360 		    bufarg, buf);
1361 		break;
1362 	}
1363 
1364 	printf("buffer=%p  bufctl=%p  cache: %s\n",
1365 	    bufarg, (void *)bcp, cparg->cache_name);
1366 
1367 	if (bcp != NULL && (cp->cache_flags & KMF_AUDIT) &&
1368 	    error != KMERR_BADBUFCTL) {
1369 		int d;
1370 		timestruc_t ts;
1371 		kmem_bufctl_audit_t *bcap = (kmem_bufctl_audit_t *)bcp;
1372 
1373 		hrt2ts(kmem_panic_info.kmp_timestamp - bcap->bc_timestamp, &ts);
1374 		printf("previous transaction on buffer %p:\n", buf);
1375 		printf("thread=%p  time=T-%ld.%09ld  slab=%p  cache: %s\n",
1376 		    (void *)bcap->bc_thread, ts.tv_sec, ts.tv_nsec,
1377 		    (void *)sp, cp->cache_name);
1378 		for (d = 0; d < MIN(bcap->bc_depth, KMEM_STACK_DEPTH); d++) {
1379 			ulong_t off;
1380 			char *sym = kobj_getsymname(bcap->bc_stack[d], &off);
1381 			printf("%s+%lx\n", sym ? sym : "?", off);
1382 		}
1383 	}
1384 	if (kmem_panic > 0)
1385 		panic("kernel heap corruption detected");
1386 	if (kmem_panic == 0)
1387 		debug_enter(NULL);
1388 	kmem_logging = 1;	/* resume logging */
1389 }
1390 
1391 static kmem_log_header_t *
1392 kmem_log_init(size_t logsize)
1393 {
1394 	kmem_log_header_t *lhp;
1395 	int nchunks = 4 * max_ncpus;
1396 	size_t lhsize = (size_t)&((kmem_log_header_t *)0)->lh_cpu[max_ncpus];
1397 	int i;
1398 
1399 	/*
1400 	 * Make sure that lhp->lh_cpu[] is nicely aligned
1401 	 * to prevent false sharing of cache lines.
1402 	 */
1403 	lhsize = P2ROUNDUP(lhsize, KMEM_ALIGN);
1404 	lhp = vmem_xalloc(kmem_log_arena, lhsize, 64, P2NPHASE(lhsize, 64), 0,
1405 	    NULL, NULL, VM_SLEEP);
1406 	bzero(lhp, lhsize);
1407 
1408 	mutex_init(&lhp->lh_lock, NULL, MUTEX_DEFAULT, NULL);
1409 	lhp->lh_nchunks = nchunks;
1410 	lhp->lh_chunksize = P2ROUNDUP(logsize / nchunks + 1, PAGESIZE);
1411 	lhp->lh_base = vmem_alloc(kmem_log_arena,
1412 	    lhp->lh_chunksize * nchunks, VM_SLEEP);
1413 	lhp->lh_free = vmem_alloc(kmem_log_arena,
1414 	    nchunks * sizeof (int), VM_SLEEP);
1415 	bzero(lhp->lh_base, lhp->lh_chunksize * nchunks);
1416 
1417 	for (i = 0; i < max_ncpus; i++) {
1418 		kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[i];
1419 		mutex_init(&clhp->clh_lock, NULL, MUTEX_DEFAULT, NULL);
1420 		clhp->clh_chunk = i;
1421 	}
1422 
1423 	for (i = max_ncpus; i < nchunks; i++)
1424 		lhp->lh_free[i] = i;
1425 
1426 	lhp->lh_head = max_ncpus;
1427 	lhp->lh_tail = 0;
1428 
1429 	return (lhp);
1430 }
1431 
1432 static void *
1433 kmem_log_enter(kmem_log_header_t *lhp, void *data, size_t size)
1434 {
1435 	void *logspace;
1436 	kmem_cpu_log_header_t *clhp = &lhp->lh_cpu[CPU->cpu_seqid];
1437 
1438 	if (lhp == NULL || kmem_logging == 0 || panicstr)
1439 		return (NULL);
1440 
1441 	mutex_enter(&clhp->clh_lock);
1442 	clhp->clh_hits++;
1443 	if (size > clhp->clh_avail) {
1444 		mutex_enter(&lhp->lh_lock);
1445 		lhp->lh_hits++;
1446 		lhp->lh_free[lhp->lh_tail] = clhp->clh_chunk;
1447 		lhp->lh_tail = (lhp->lh_tail + 1) % lhp->lh_nchunks;
1448 		clhp->clh_chunk = lhp->lh_free[lhp->lh_head];
1449 		lhp->lh_head = (lhp->lh_head + 1) % lhp->lh_nchunks;
1450 		clhp->clh_current = lhp->lh_base +
1451 		    clhp->clh_chunk * lhp->lh_chunksize;
1452 		clhp->clh_avail = lhp->lh_chunksize;
1453 		if (size > lhp->lh_chunksize)
1454 			size = lhp->lh_chunksize;
1455 		mutex_exit(&lhp->lh_lock);
1456 	}
1457 	logspace = clhp->clh_current;
1458 	clhp->clh_current += size;
1459 	clhp->clh_avail -= size;
1460 	bcopy(data, logspace, size);
1461 	mutex_exit(&clhp->clh_lock);
1462 	return (logspace);
1463 }
1464 
1465 #define	KMEM_AUDIT(lp, cp, bcp)						\
1466 {									\
1467 	kmem_bufctl_audit_t *_bcp = (kmem_bufctl_audit_t *)(bcp);	\
1468 	_bcp->bc_timestamp = gethrtime();				\
1469 	_bcp->bc_thread = curthread;					\
1470 	_bcp->bc_depth = getpcstack(_bcp->bc_stack, KMEM_STACK_DEPTH);	\
1471 	_bcp->bc_lastlog = kmem_log_enter((lp), _bcp, sizeof (*_bcp));	\
1472 }
1473 
1474 static void
1475 kmem_log_event(kmem_log_header_t *lp, kmem_cache_t *cp,
1476 	kmem_slab_t *sp, void *addr)
1477 {
1478 	kmem_bufctl_audit_t bca;
1479 
1480 	bzero(&bca, sizeof (kmem_bufctl_audit_t));
1481 	bca.bc_addr = addr;
1482 	bca.bc_slab = sp;
1483 	bca.bc_cache = cp;
1484 	KMEM_AUDIT(lp, cp, &bca);
1485 }
1486 
1487 /*
1488  * Create a new slab for cache cp.
1489  */
1490 static kmem_slab_t *
1491 kmem_slab_create(kmem_cache_t *cp, int kmflag)
1492 {
1493 	size_t slabsize = cp->cache_slabsize;
1494 	size_t chunksize = cp->cache_chunksize;
1495 	int cache_flags = cp->cache_flags;
1496 	size_t color, chunks;
1497 	char *buf, *slab;
1498 	kmem_slab_t *sp;
1499 	kmem_bufctl_t *bcp;
1500 	vmem_t *vmp = cp->cache_arena;
1501 
1502 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
1503 
1504 	color = cp->cache_color + cp->cache_align;
1505 	if (color > cp->cache_maxcolor)
1506 		color = cp->cache_mincolor;
1507 	cp->cache_color = color;
1508 
1509 	slab = vmem_alloc(vmp, slabsize, kmflag & KM_VMFLAGS);
1510 
1511 	if (slab == NULL)
1512 		goto vmem_alloc_failure;
1513 
1514 	ASSERT(P2PHASE((uintptr_t)slab, vmp->vm_quantum) == 0);
1515 
1516 	/*
1517 	 * Reverify what was already checked in kmem_cache_set_move(), since the
1518 	 * consolidator depends (for correctness) on slabs being initialized
1519 	 * with the 0xbaddcafe memory pattern (setting a low order bit usable by
1520 	 * clients to distinguish uninitialized memory from known objects).
1521 	 */
1522 	ASSERT((cp->cache_move == NULL) || !(cp->cache_cflags & KMC_NOTOUCH));
1523 	if (!(cp->cache_cflags & KMC_NOTOUCH))
1524 		copy_pattern(KMEM_UNINITIALIZED_PATTERN, slab, slabsize);
1525 
1526 	if (cache_flags & KMF_HASH) {
1527 		if ((sp = kmem_cache_alloc(kmem_slab_cache, kmflag)) == NULL)
1528 			goto slab_alloc_failure;
1529 		chunks = (slabsize - color) / chunksize;
1530 	} else {
1531 		sp = KMEM_SLAB(cp, slab);
1532 		chunks = (slabsize - sizeof (kmem_slab_t) - color) / chunksize;
1533 	}
1534 
1535 	sp->slab_cache	= cp;
1536 	sp->slab_head	= NULL;
1537 	sp->slab_refcnt	= 0;
1538 	sp->slab_base	= buf = slab + color;
1539 	sp->slab_chunks	= chunks;
1540 	sp->slab_stuck_offset = (uint32_t)-1;
1541 	sp->slab_later_count = 0;
1542 	sp->slab_flags = 0;
1543 
1544 	ASSERT(chunks > 0);
1545 	while (chunks-- != 0) {
1546 		if (cache_flags & KMF_HASH) {
1547 			bcp = kmem_cache_alloc(cp->cache_bufctl_cache, kmflag);
1548 			if (bcp == NULL)
1549 				goto bufctl_alloc_failure;
1550 			if (cache_flags & KMF_AUDIT) {
1551 				kmem_bufctl_audit_t *bcap =
1552 				    (kmem_bufctl_audit_t *)bcp;
1553 				bzero(bcap, sizeof (kmem_bufctl_audit_t));
1554 				bcap->bc_cache = cp;
1555 			}
1556 			bcp->bc_addr = buf;
1557 			bcp->bc_slab = sp;
1558 		} else {
1559 			bcp = KMEM_BUFCTL(cp, buf);
1560 		}
1561 		if (cache_flags & KMF_BUFTAG) {
1562 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1563 			btp->bt_redzone = KMEM_REDZONE_PATTERN;
1564 			btp->bt_bufctl = bcp;
1565 			btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1566 			if (cache_flags & KMF_DEADBEEF) {
1567 				copy_pattern(KMEM_FREE_PATTERN, buf,
1568 				    cp->cache_verify);
1569 			}
1570 		}
1571 		bcp->bc_next = sp->slab_head;
1572 		sp->slab_head = bcp;
1573 		buf += chunksize;
1574 	}
1575 
1576 	kmem_log_event(kmem_slab_log, cp, sp, slab);
1577 
1578 	return (sp);
1579 
1580 bufctl_alloc_failure:
1581 
1582 	while ((bcp = sp->slab_head) != NULL) {
1583 		sp->slab_head = bcp->bc_next;
1584 		kmem_cache_free(cp->cache_bufctl_cache, bcp);
1585 	}
1586 	kmem_cache_free(kmem_slab_cache, sp);
1587 
1588 slab_alloc_failure:
1589 
1590 	vmem_free(vmp, slab, slabsize);
1591 
1592 vmem_alloc_failure:
1593 
1594 	kmem_log_event(kmem_failure_log, cp, NULL, NULL);
1595 	atomic_add_64(&cp->cache_alloc_fail, 1);
1596 
1597 	return (NULL);
1598 }
1599 
1600 /*
1601  * Destroy a slab.
1602  */
1603 static void
1604 kmem_slab_destroy(kmem_cache_t *cp, kmem_slab_t *sp)
1605 {
1606 	vmem_t *vmp = cp->cache_arena;
1607 	void *slab = (void *)P2ALIGN((uintptr_t)sp->slab_base, vmp->vm_quantum);
1608 
1609 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
1610 	ASSERT(sp->slab_refcnt == 0);
1611 
1612 	if (cp->cache_flags & KMF_HASH) {
1613 		kmem_bufctl_t *bcp;
1614 		while ((bcp = sp->slab_head) != NULL) {
1615 			sp->slab_head = bcp->bc_next;
1616 			kmem_cache_free(cp->cache_bufctl_cache, bcp);
1617 		}
1618 		kmem_cache_free(kmem_slab_cache, sp);
1619 	}
1620 	vmem_free(vmp, slab, cp->cache_slabsize);
1621 }
1622 
1623 static void *
1624 kmem_slab_alloc_impl(kmem_cache_t *cp, kmem_slab_t *sp)
1625 {
1626 	kmem_bufctl_t *bcp, **hash_bucket;
1627 	void *buf;
1628 
1629 	ASSERT(MUTEX_HELD(&cp->cache_lock));
1630 	/*
1631 	 * kmem_slab_alloc() drops cache_lock when it creates a new slab, so we
1632 	 * can't ASSERT(avl_is_empty(&cp->cache_partial_slabs)) here when the
1633 	 * slab is newly created (sp->slab_refcnt == 0).
1634 	 */
1635 	ASSERT((sp->slab_refcnt == 0) || (KMEM_SLAB_IS_PARTIAL(sp) &&
1636 	    (sp == avl_first(&cp->cache_partial_slabs))));
1637 	ASSERT(sp->slab_cache == cp);
1638 
1639 	cp->cache_slab_alloc++;
1640 	cp->cache_bufslab--;
1641 	sp->slab_refcnt++;
1642 
1643 	bcp = sp->slab_head;
1644 	if ((sp->slab_head = bcp->bc_next) == NULL) {
1645 		ASSERT(KMEM_SLAB_IS_ALL_USED(sp));
1646 		if (sp->slab_refcnt == 1) {
1647 			ASSERT(sp->slab_chunks == 1);
1648 		} else {
1649 			ASSERT(sp->slab_chunks > 1); /* the slab was partial */
1650 			avl_remove(&cp->cache_partial_slabs, sp);
1651 			sp->slab_later_count = 0; /* clear history */
1652 			sp->slab_flags &= ~KMEM_SLAB_NOMOVE;
1653 			sp->slab_stuck_offset = (uint32_t)-1;
1654 		}
1655 		list_insert_head(&cp->cache_complete_slabs, sp);
1656 		cp->cache_complete_slab_count++;
1657 	} else {
1658 		ASSERT(KMEM_SLAB_IS_PARTIAL(sp));
1659 		if (sp->slab_refcnt == 1) {
1660 			avl_add(&cp->cache_partial_slabs, sp);
1661 		} else {
1662 			/*
1663 			 * The slab is now more allocated than it was, so the
1664 			 * order remains unchanged.
1665 			 */
1666 			ASSERT(!avl_update(&cp->cache_partial_slabs, sp));
1667 		}
1668 	}
1669 
1670 	if (cp->cache_flags & KMF_HASH) {
1671 		/*
1672 		 * Add buffer to allocated-address hash table.
1673 		 */
1674 		buf = bcp->bc_addr;
1675 		hash_bucket = KMEM_HASH(cp, buf);
1676 		bcp->bc_next = *hash_bucket;
1677 		*hash_bucket = bcp;
1678 		if ((cp->cache_flags & (KMF_AUDIT | KMF_BUFTAG)) == KMF_AUDIT) {
1679 			KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1680 		}
1681 	} else {
1682 		buf = KMEM_BUF(cp, bcp);
1683 	}
1684 
1685 	ASSERT(KMEM_SLAB_MEMBER(sp, buf));
1686 	return (buf);
1687 }
1688 
1689 /*
1690  * Allocate a raw (unconstructed) buffer from cp's slab layer.
1691  */
1692 static void *
1693 kmem_slab_alloc(kmem_cache_t *cp, int kmflag)
1694 {
1695 	kmem_slab_t *sp;
1696 	void *buf;
1697 
1698 	mutex_enter(&cp->cache_lock);
1699 	sp = avl_first(&cp->cache_partial_slabs);
1700 	if (sp == NULL) {
1701 		ASSERT(cp->cache_bufslab == 0);
1702 
1703 		/*
1704 		 * The freelist is empty.  Create a new slab.
1705 		 */
1706 		mutex_exit(&cp->cache_lock);
1707 		if ((sp = kmem_slab_create(cp, kmflag)) == NULL) {
1708 			return (NULL);
1709 		}
1710 		mutex_enter(&cp->cache_lock);
1711 		cp->cache_slab_create++;
1712 		if ((cp->cache_buftotal += sp->slab_chunks) > cp->cache_bufmax)
1713 			cp->cache_bufmax = cp->cache_buftotal;
1714 		cp->cache_bufslab += sp->slab_chunks;
1715 	}
1716 
1717 	buf = kmem_slab_alloc_impl(cp, sp);
1718 	ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) ==
1719 	    (cp->cache_complete_slab_count +
1720 	    avl_numnodes(&cp->cache_partial_slabs) +
1721 	    (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount)));
1722 	mutex_exit(&cp->cache_lock);
1723 
1724 	return (buf);
1725 }
1726 
1727 static void kmem_slab_move_yes(kmem_cache_t *, kmem_slab_t *, void *);
1728 
1729 /*
1730  * Free a raw (unconstructed) buffer to cp's slab layer.
1731  */
1732 static void
1733 kmem_slab_free(kmem_cache_t *cp, void *buf)
1734 {
1735 	kmem_slab_t *sp;
1736 	kmem_bufctl_t *bcp, **prev_bcpp;
1737 
1738 	ASSERT(buf != NULL);
1739 
1740 	mutex_enter(&cp->cache_lock);
1741 	cp->cache_slab_free++;
1742 
1743 	if (cp->cache_flags & KMF_HASH) {
1744 		/*
1745 		 * Look up buffer in allocated-address hash table.
1746 		 */
1747 		prev_bcpp = KMEM_HASH(cp, buf);
1748 		while ((bcp = *prev_bcpp) != NULL) {
1749 			if (bcp->bc_addr == buf) {
1750 				*prev_bcpp = bcp->bc_next;
1751 				sp = bcp->bc_slab;
1752 				break;
1753 			}
1754 			cp->cache_lookup_depth++;
1755 			prev_bcpp = &bcp->bc_next;
1756 		}
1757 	} else {
1758 		bcp = KMEM_BUFCTL(cp, buf);
1759 		sp = KMEM_SLAB(cp, buf);
1760 	}
1761 
1762 	if (bcp == NULL || sp->slab_cache != cp || !KMEM_SLAB_MEMBER(sp, buf)) {
1763 		mutex_exit(&cp->cache_lock);
1764 		kmem_error(KMERR_BADADDR, cp, buf);
1765 		return;
1766 	}
1767 
1768 	if (KMEM_SLAB_OFFSET(sp, buf) == sp->slab_stuck_offset) {
1769 		/*
1770 		 * If this is the buffer that prevented the consolidator from
1771 		 * clearing the slab, we can reset the slab flags now that the
1772 		 * buffer is freed. (It makes sense to do this in
1773 		 * kmem_cache_free(), where the client gives up ownership of the
1774 		 * buffer, but on the hot path the test is too expensive.)
1775 		 */
1776 		kmem_slab_move_yes(cp, sp, buf);
1777 	}
1778 
1779 	if ((cp->cache_flags & (KMF_AUDIT | KMF_BUFTAG)) == KMF_AUDIT) {
1780 		if (cp->cache_flags & KMF_CONTENTS)
1781 			((kmem_bufctl_audit_t *)bcp)->bc_contents =
1782 			    kmem_log_enter(kmem_content_log, buf,
1783 			    cp->cache_contents);
1784 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1785 	}
1786 
1787 	bcp->bc_next = sp->slab_head;
1788 	sp->slab_head = bcp;
1789 
1790 	cp->cache_bufslab++;
1791 	ASSERT(sp->slab_refcnt >= 1);
1792 
1793 	if (--sp->slab_refcnt == 0) {
1794 		/*
1795 		 * There are no outstanding allocations from this slab,
1796 		 * so we can reclaim the memory.
1797 		 */
1798 		if (sp->slab_chunks == 1) {
1799 			list_remove(&cp->cache_complete_slabs, sp);
1800 			cp->cache_complete_slab_count--;
1801 		} else {
1802 			avl_remove(&cp->cache_partial_slabs, sp);
1803 		}
1804 
1805 		cp->cache_buftotal -= sp->slab_chunks;
1806 		cp->cache_bufslab -= sp->slab_chunks;
1807 		/*
1808 		 * Defer releasing the slab to the virtual memory subsystem
1809 		 * while there is a pending move callback, since we guarantee
1810 		 * that buffers passed to the move callback have only been
1811 		 * touched by kmem or by the client itself. Since the memory
1812 		 * patterns baddcafe (uninitialized) and deadbeef (freed) both
1813 		 * set at least one of the two lowest order bits, the client can
1814 		 * test those bits in the move callback to determine whether or
1815 		 * not it knows about the buffer (assuming that the client also
1816 		 * sets one of those low order bits whenever it frees a buffer).
1817 		 */
1818 		if (cp->cache_defrag == NULL ||
1819 		    (avl_is_empty(&cp->cache_defrag->kmd_moves_pending) &&
1820 		    !(sp->slab_flags & KMEM_SLAB_MOVE_PENDING))) {
1821 			cp->cache_slab_destroy++;
1822 			mutex_exit(&cp->cache_lock);
1823 			kmem_slab_destroy(cp, sp);
1824 		} else {
1825 			list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
1826 			/*
1827 			 * Slabs are inserted at both ends of the deadlist to
1828 			 * distinguish between slabs freed while move callbacks
1829 			 * are pending (list head) and a slab freed while the
1830 			 * lock is dropped in kmem_move_buffers() (list tail) so
1831 			 * that in both cases slab_destroy() is called from the
1832 			 * right context.
1833 			 */
1834 			if (sp->slab_flags & KMEM_SLAB_MOVE_PENDING) {
1835 				list_insert_tail(deadlist, sp);
1836 			} else {
1837 				list_insert_head(deadlist, sp);
1838 			}
1839 			cp->cache_defrag->kmd_deadcount++;
1840 			mutex_exit(&cp->cache_lock);
1841 		}
1842 		return;
1843 	}
1844 
1845 	if (bcp->bc_next == NULL) {
1846 		/* Transition the slab from completely allocated to partial. */
1847 		ASSERT(sp->slab_refcnt == (sp->slab_chunks - 1));
1848 		ASSERT(sp->slab_chunks > 1);
1849 		list_remove(&cp->cache_complete_slabs, sp);
1850 		cp->cache_complete_slab_count--;
1851 		avl_add(&cp->cache_partial_slabs, sp);
1852 	} else {
1853 #ifdef	DEBUG
1854 		if (avl_update_gt(&cp->cache_partial_slabs, sp)) {
1855 			KMEM_STAT_ADD(kmem_move_stats.kms_avl_update);
1856 		} else {
1857 			KMEM_STAT_ADD(kmem_move_stats.kms_avl_noupdate);
1858 		}
1859 #else
1860 		(void) avl_update_gt(&cp->cache_partial_slabs, sp);
1861 #endif
1862 	}
1863 
1864 	ASSERT((cp->cache_slab_create - cp->cache_slab_destroy) ==
1865 	    (cp->cache_complete_slab_count +
1866 	    avl_numnodes(&cp->cache_partial_slabs) +
1867 	    (cp->cache_defrag == NULL ? 0 : cp->cache_defrag->kmd_deadcount)));
1868 	mutex_exit(&cp->cache_lock);
1869 }
1870 
1871 /*
1872  * Return -1 if kmem_error, 1 if constructor fails, 0 if successful.
1873  */
1874 static int
1875 kmem_cache_alloc_debug(kmem_cache_t *cp, void *buf, int kmflag, int construct,
1876     caddr_t caller)
1877 {
1878 	kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1879 	kmem_bufctl_audit_t *bcp = (kmem_bufctl_audit_t *)btp->bt_bufctl;
1880 	uint32_t mtbf;
1881 
1882 	if (btp->bt_bxstat != ((intptr_t)bcp ^ KMEM_BUFTAG_FREE)) {
1883 		kmem_error(KMERR_BADBUFTAG, cp, buf);
1884 		return (-1);
1885 	}
1886 
1887 	btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_ALLOC;
1888 
1889 	if ((cp->cache_flags & KMF_HASH) && bcp->bc_addr != buf) {
1890 		kmem_error(KMERR_BADBUFCTL, cp, buf);
1891 		return (-1);
1892 	}
1893 
1894 	if (cp->cache_flags & KMF_DEADBEEF) {
1895 		if (!construct && (cp->cache_flags & KMF_LITE)) {
1896 			if (*(uint64_t *)buf != KMEM_FREE_PATTERN) {
1897 				kmem_error(KMERR_MODIFIED, cp, buf);
1898 				return (-1);
1899 			}
1900 			if (cp->cache_constructor != NULL)
1901 				*(uint64_t *)buf = btp->bt_redzone;
1902 			else
1903 				*(uint64_t *)buf = KMEM_UNINITIALIZED_PATTERN;
1904 		} else {
1905 			construct = 1;
1906 			if (verify_and_copy_pattern(KMEM_FREE_PATTERN,
1907 			    KMEM_UNINITIALIZED_PATTERN, buf,
1908 			    cp->cache_verify)) {
1909 				kmem_error(KMERR_MODIFIED, cp, buf);
1910 				return (-1);
1911 			}
1912 		}
1913 	}
1914 	btp->bt_redzone = KMEM_REDZONE_PATTERN;
1915 
1916 	if ((mtbf = kmem_mtbf | cp->cache_mtbf) != 0 &&
1917 	    gethrtime() % mtbf == 0 &&
1918 	    (kmflag & (KM_NOSLEEP | KM_PANIC)) == KM_NOSLEEP) {
1919 		kmem_log_event(kmem_failure_log, cp, NULL, NULL);
1920 		if (!construct && cp->cache_destructor != NULL)
1921 			cp->cache_destructor(buf, cp->cache_private);
1922 	} else {
1923 		mtbf = 0;
1924 	}
1925 
1926 	if (mtbf || (construct && cp->cache_constructor != NULL &&
1927 	    cp->cache_constructor(buf, cp->cache_private, kmflag) != 0)) {
1928 		atomic_add_64(&cp->cache_alloc_fail, 1);
1929 		btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1930 		if (cp->cache_flags & KMF_DEADBEEF)
1931 			copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1932 		kmem_slab_free(cp, buf);
1933 		return (1);
1934 	}
1935 
1936 	if (cp->cache_flags & KMF_AUDIT) {
1937 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1938 	}
1939 
1940 	if ((cp->cache_flags & KMF_LITE) &&
1941 	    !(cp->cache_cflags & KMC_KMEM_ALLOC)) {
1942 		KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller);
1943 	}
1944 
1945 	return (0);
1946 }
1947 
1948 static int
1949 kmem_cache_free_debug(kmem_cache_t *cp, void *buf, caddr_t caller)
1950 {
1951 	kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
1952 	kmem_bufctl_audit_t *bcp = (kmem_bufctl_audit_t *)btp->bt_bufctl;
1953 	kmem_slab_t *sp;
1954 
1955 	if (btp->bt_bxstat != ((intptr_t)bcp ^ KMEM_BUFTAG_ALLOC)) {
1956 		if (btp->bt_bxstat == ((intptr_t)bcp ^ KMEM_BUFTAG_FREE)) {
1957 			kmem_error(KMERR_DUPFREE, cp, buf);
1958 			return (-1);
1959 		}
1960 		sp = kmem_findslab(cp, buf);
1961 		if (sp == NULL || sp->slab_cache != cp)
1962 			kmem_error(KMERR_BADADDR, cp, buf);
1963 		else
1964 			kmem_error(KMERR_REDZONE, cp, buf);
1965 		return (-1);
1966 	}
1967 
1968 	btp->bt_bxstat = (intptr_t)bcp ^ KMEM_BUFTAG_FREE;
1969 
1970 	if ((cp->cache_flags & KMF_HASH) && bcp->bc_addr != buf) {
1971 		kmem_error(KMERR_BADBUFCTL, cp, buf);
1972 		return (-1);
1973 	}
1974 
1975 	if (btp->bt_redzone != KMEM_REDZONE_PATTERN) {
1976 		kmem_error(KMERR_REDZONE, cp, buf);
1977 		return (-1);
1978 	}
1979 
1980 	if (cp->cache_flags & KMF_AUDIT) {
1981 		if (cp->cache_flags & KMF_CONTENTS)
1982 			bcp->bc_contents = kmem_log_enter(kmem_content_log,
1983 			    buf, cp->cache_contents);
1984 		KMEM_AUDIT(kmem_transaction_log, cp, bcp);
1985 	}
1986 
1987 	if ((cp->cache_flags & KMF_LITE) &&
1988 	    !(cp->cache_cflags & KMC_KMEM_ALLOC)) {
1989 		KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count, caller);
1990 	}
1991 
1992 	if (cp->cache_flags & KMF_DEADBEEF) {
1993 		if (cp->cache_flags & KMF_LITE)
1994 			btp->bt_redzone = *(uint64_t *)buf;
1995 		else if (cp->cache_destructor != NULL)
1996 			cp->cache_destructor(buf, cp->cache_private);
1997 
1998 		copy_pattern(KMEM_FREE_PATTERN, buf, cp->cache_verify);
1999 	}
2000 
2001 	return (0);
2002 }
2003 
2004 /*
2005  * Free each object in magazine mp to cp's slab layer, and free mp itself.
2006  */
2007 static void
2008 kmem_magazine_destroy(kmem_cache_t *cp, kmem_magazine_t *mp, int nrounds)
2009 {
2010 	int round;
2011 
2012 	ASSERT(!list_link_active(&cp->cache_link) ||
2013 	    taskq_member(kmem_taskq, curthread));
2014 
2015 	for (round = 0; round < nrounds; round++) {
2016 		void *buf = mp->mag_round[round];
2017 
2018 		if (cp->cache_flags & KMF_DEADBEEF) {
2019 			if (verify_pattern(KMEM_FREE_PATTERN, buf,
2020 			    cp->cache_verify) != NULL) {
2021 				kmem_error(KMERR_MODIFIED, cp, buf);
2022 				continue;
2023 			}
2024 			if ((cp->cache_flags & KMF_LITE) &&
2025 			    cp->cache_destructor != NULL) {
2026 				kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2027 				*(uint64_t *)buf = btp->bt_redzone;
2028 				cp->cache_destructor(buf, cp->cache_private);
2029 				*(uint64_t *)buf = KMEM_FREE_PATTERN;
2030 			}
2031 		} else if (cp->cache_destructor != NULL) {
2032 			cp->cache_destructor(buf, cp->cache_private);
2033 		}
2034 
2035 		kmem_slab_free(cp, buf);
2036 	}
2037 	ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2038 	kmem_cache_free(cp->cache_magtype->mt_cache, mp);
2039 }
2040 
2041 /*
2042  * Allocate a magazine from the depot.
2043  */
2044 static kmem_magazine_t *
2045 kmem_depot_alloc(kmem_cache_t *cp, kmem_maglist_t *mlp)
2046 {
2047 	kmem_magazine_t *mp;
2048 
2049 	/*
2050 	 * If we can't get the depot lock without contention,
2051 	 * update our contention count.  We use the depot
2052 	 * contention rate to determine whether we need to
2053 	 * increase the magazine size for better scalability.
2054 	 */
2055 	if (!mutex_tryenter(&cp->cache_depot_lock)) {
2056 		mutex_enter(&cp->cache_depot_lock);
2057 		cp->cache_depot_contention++;
2058 	}
2059 
2060 	if ((mp = mlp->ml_list) != NULL) {
2061 		ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2062 		mlp->ml_list = mp->mag_next;
2063 		if (--mlp->ml_total < mlp->ml_min)
2064 			mlp->ml_min = mlp->ml_total;
2065 		mlp->ml_alloc++;
2066 	}
2067 
2068 	mutex_exit(&cp->cache_depot_lock);
2069 
2070 	return (mp);
2071 }
2072 
2073 /*
2074  * Free a magazine to the depot.
2075  */
2076 static void
2077 kmem_depot_free(kmem_cache_t *cp, kmem_maglist_t *mlp, kmem_magazine_t *mp)
2078 {
2079 	mutex_enter(&cp->cache_depot_lock);
2080 	ASSERT(KMEM_MAGAZINE_VALID(cp, mp));
2081 	mp->mag_next = mlp->ml_list;
2082 	mlp->ml_list = mp;
2083 	mlp->ml_total++;
2084 	mutex_exit(&cp->cache_depot_lock);
2085 }
2086 
2087 /*
2088  * Update the working set statistics for cp's depot.
2089  */
2090 static void
2091 kmem_depot_ws_update(kmem_cache_t *cp)
2092 {
2093 	mutex_enter(&cp->cache_depot_lock);
2094 	cp->cache_full.ml_reaplimit = cp->cache_full.ml_min;
2095 	cp->cache_full.ml_min = cp->cache_full.ml_total;
2096 	cp->cache_empty.ml_reaplimit = cp->cache_empty.ml_min;
2097 	cp->cache_empty.ml_min = cp->cache_empty.ml_total;
2098 	mutex_exit(&cp->cache_depot_lock);
2099 }
2100 
2101 /*
2102  * Reap all magazines that have fallen out of the depot's working set.
2103  */
2104 static void
2105 kmem_depot_ws_reap(kmem_cache_t *cp)
2106 {
2107 	long reap;
2108 	kmem_magazine_t *mp;
2109 
2110 	ASSERT(!list_link_active(&cp->cache_link) ||
2111 	    taskq_member(kmem_taskq, curthread));
2112 
2113 	reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
2114 	while (reap-- && (mp = kmem_depot_alloc(cp, &cp->cache_full)) != NULL)
2115 		kmem_magazine_destroy(cp, mp, cp->cache_magtype->mt_magsize);
2116 
2117 	reap = MIN(cp->cache_empty.ml_reaplimit, cp->cache_empty.ml_min);
2118 	while (reap-- && (mp = kmem_depot_alloc(cp, &cp->cache_empty)) != NULL)
2119 		kmem_magazine_destroy(cp, mp, 0);
2120 }
2121 
2122 static void
2123 kmem_cpu_reload(kmem_cpu_cache_t *ccp, kmem_magazine_t *mp, int rounds)
2124 {
2125 	ASSERT((ccp->cc_loaded == NULL && ccp->cc_rounds == -1) ||
2126 	    (ccp->cc_loaded && ccp->cc_rounds + rounds == ccp->cc_magsize));
2127 	ASSERT(ccp->cc_magsize > 0);
2128 
2129 	ccp->cc_ploaded = ccp->cc_loaded;
2130 	ccp->cc_prounds = ccp->cc_rounds;
2131 	ccp->cc_loaded = mp;
2132 	ccp->cc_rounds = rounds;
2133 }
2134 
2135 /*
2136  * Allocate a constructed object from cache cp.
2137  */
2138 void *
2139 kmem_cache_alloc(kmem_cache_t *cp, int kmflag)
2140 {
2141 	kmem_cpu_cache_t *ccp = KMEM_CPU_CACHE(cp);
2142 	kmem_magazine_t *fmp;
2143 	void *buf;
2144 
2145 	mutex_enter(&ccp->cc_lock);
2146 	for (;;) {
2147 		/*
2148 		 * If there's an object available in the current CPU's
2149 		 * loaded magazine, just take it and return.
2150 		 */
2151 		if (ccp->cc_rounds > 0) {
2152 			buf = ccp->cc_loaded->mag_round[--ccp->cc_rounds];
2153 			ccp->cc_alloc++;
2154 			mutex_exit(&ccp->cc_lock);
2155 			if ((ccp->cc_flags & KMF_BUFTAG) &&
2156 			    kmem_cache_alloc_debug(cp, buf, kmflag, 0,
2157 			    caller()) != 0) {
2158 				if (kmflag & KM_NOSLEEP)
2159 					return (NULL);
2160 				mutex_enter(&ccp->cc_lock);
2161 				continue;
2162 			}
2163 			return (buf);
2164 		}
2165 
2166 		/*
2167 		 * The loaded magazine is empty.  If the previously loaded
2168 		 * magazine was full, exchange them and try again.
2169 		 */
2170 		if (ccp->cc_prounds > 0) {
2171 			kmem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
2172 			continue;
2173 		}
2174 
2175 		/*
2176 		 * If the magazine layer is disabled, break out now.
2177 		 */
2178 		if (ccp->cc_magsize == 0)
2179 			break;
2180 
2181 		/*
2182 		 * Try to get a full magazine from the depot.
2183 		 */
2184 		fmp = kmem_depot_alloc(cp, &cp->cache_full);
2185 		if (fmp != NULL) {
2186 			if (ccp->cc_ploaded != NULL)
2187 				kmem_depot_free(cp, &cp->cache_empty,
2188 				    ccp->cc_ploaded);
2189 			kmem_cpu_reload(ccp, fmp, ccp->cc_magsize);
2190 			continue;
2191 		}
2192 
2193 		/*
2194 		 * There are no full magazines in the depot,
2195 		 * so fall through to the slab layer.
2196 		 */
2197 		break;
2198 	}
2199 	mutex_exit(&ccp->cc_lock);
2200 
2201 	/*
2202 	 * We couldn't allocate a constructed object from the magazine layer,
2203 	 * so get a raw buffer from the slab layer and apply its constructor.
2204 	 */
2205 	buf = kmem_slab_alloc(cp, kmflag);
2206 
2207 	if (buf == NULL)
2208 		return (NULL);
2209 
2210 	if (cp->cache_flags & KMF_BUFTAG) {
2211 		/*
2212 		 * Make kmem_cache_alloc_debug() apply the constructor for us.
2213 		 */
2214 		int rc = kmem_cache_alloc_debug(cp, buf, kmflag, 1, caller());
2215 		if (rc != 0) {
2216 			if (kmflag & KM_NOSLEEP)
2217 				return (NULL);
2218 			/*
2219 			 * kmem_cache_alloc_debug() detected corruption
2220 			 * but didn't panic (kmem_panic <= 0). We should not be
2221 			 * here because the constructor failed (indicated by a
2222 			 * return code of 1). Try again.
2223 			 */
2224 			ASSERT(rc == -1);
2225 			return (kmem_cache_alloc(cp, kmflag));
2226 		}
2227 		return (buf);
2228 	}
2229 
2230 	if (cp->cache_constructor != NULL &&
2231 	    cp->cache_constructor(buf, cp->cache_private, kmflag) != 0) {
2232 		atomic_add_64(&cp->cache_alloc_fail, 1);
2233 		kmem_slab_free(cp, buf);
2234 		return (NULL);
2235 	}
2236 
2237 	return (buf);
2238 }
2239 
2240 /*
2241  * The freed argument tells whether or not kmem_cache_free_debug() has already
2242  * been called so that we can avoid the duplicate free error. For example, a
2243  * buffer on a magazine has already been freed by the client but is still
2244  * constructed.
2245  */
2246 static void
2247 kmem_slab_free_constructed(kmem_cache_t *cp, void *buf, boolean_t freed)
2248 {
2249 	if (!freed && (cp->cache_flags & KMF_BUFTAG))
2250 		if (kmem_cache_free_debug(cp, buf, caller()) == -1)
2251 			return;
2252 
2253 	/*
2254 	 * Note that if KMF_DEADBEEF is in effect and KMF_LITE is not,
2255 	 * kmem_cache_free_debug() will have already applied the destructor.
2256 	 */
2257 	if ((cp->cache_flags & (KMF_DEADBEEF | KMF_LITE)) != KMF_DEADBEEF &&
2258 	    cp->cache_destructor != NULL) {
2259 		if (cp->cache_flags & KMF_DEADBEEF) {	/* KMF_LITE implied */
2260 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2261 			*(uint64_t *)buf = btp->bt_redzone;
2262 			cp->cache_destructor(buf, cp->cache_private);
2263 			*(uint64_t *)buf = KMEM_FREE_PATTERN;
2264 		} else {
2265 			cp->cache_destructor(buf, cp->cache_private);
2266 		}
2267 	}
2268 
2269 	kmem_slab_free(cp, buf);
2270 }
2271 
2272 /*
2273  * Free a constructed object to cache cp.
2274  */
2275 void
2276 kmem_cache_free(kmem_cache_t *cp, void *buf)
2277 {
2278 	kmem_cpu_cache_t *ccp = KMEM_CPU_CACHE(cp);
2279 	kmem_magazine_t *emp;
2280 	kmem_magtype_t *mtp;
2281 
2282 	/*
2283 	 * The client must not free either of the buffers passed to the move
2284 	 * callback function.
2285 	 */
2286 	ASSERT(cp->cache_defrag == NULL ||
2287 	    cp->cache_defrag->kmd_thread != curthread ||
2288 	    (buf != cp->cache_defrag->kmd_from_buf &&
2289 	    buf != cp->cache_defrag->kmd_to_buf));
2290 
2291 	if (ccp->cc_flags & KMF_BUFTAG)
2292 		if (kmem_cache_free_debug(cp, buf, caller()) == -1)
2293 			return;
2294 
2295 	mutex_enter(&ccp->cc_lock);
2296 	for (;;) {
2297 		/*
2298 		 * If there's a slot available in the current CPU's
2299 		 * loaded magazine, just put the object there and return.
2300 		 */
2301 		if ((uint_t)ccp->cc_rounds < ccp->cc_magsize) {
2302 			ccp->cc_loaded->mag_round[ccp->cc_rounds++] = buf;
2303 			ccp->cc_free++;
2304 			mutex_exit(&ccp->cc_lock);
2305 			return;
2306 		}
2307 
2308 		/*
2309 		 * The loaded magazine is full.  If the previously loaded
2310 		 * magazine was empty, exchange them and try again.
2311 		 */
2312 		if (ccp->cc_prounds == 0) {
2313 			kmem_cpu_reload(ccp, ccp->cc_ploaded, ccp->cc_prounds);
2314 			continue;
2315 		}
2316 
2317 		/*
2318 		 * If the magazine layer is disabled, break out now.
2319 		 */
2320 		if (ccp->cc_magsize == 0)
2321 			break;
2322 
2323 		/*
2324 		 * Try to get an empty magazine from the depot.
2325 		 */
2326 		emp = kmem_depot_alloc(cp, &cp->cache_empty);
2327 		if (emp != NULL) {
2328 			if (ccp->cc_ploaded != NULL)
2329 				kmem_depot_free(cp, &cp->cache_full,
2330 				    ccp->cc_ploaded);
2331 			kmem_cpu_reload(ccp, emp, 0);
2332 			continue;
2333 		}
2334 
2335 		/*
2336 		 * There are no empty magazines in the depot,
2337 		 * so try to allocate a new one.  We must drop all locks
2338 		 * across kmem_cache_alloc() because lower layers may
2339 		 * attempt to allocate from this cache.
2340 		 */
2341 		mtp = cp->cache_magtype;
2342 		mutex_exit(&ccp->cc_lock);
2343 		emp = kmem_cache_alloc(mtp->mt_cache, KM_NOSLEEP);
2344 		mutex_enter(&ccp->cc_lock);
2345 
2346 		if (emp != NULL) {
2347 			/*
2348 			 * We successfully allocated an empty magazine.
2349 			 * However, we had to drop ccp->cc_lock to do it,
2350 			 * so the cache's magazine size may have changed.
2351 			 * If so, free the magazine and try again.
2352 			 */
2353 			if (ccp->cc_magsize != mtp->mt_magsize) {
2354 				mutex_exit(&ccp->cc_lock);
2355 				kmem_cache_free(mtp->mt_cache, emp);
2356 				mutex_enter(&ccp->cc_lock);
2357 				continue;
2358 			}
2359 
2360 			/*
2361 			 * We got a magazine of the right size.  Add it to
2362 			 * the depot and try the whole dance again.
2363 			 */
2364 			kmem_depot_free(cp, &cp->cache_empty, emp);
2365 			continue;
2366 		}
2367 
2368 		/*
2369 		 * We couldn't allocate an empty magazine,
2370 		 * so fall through to the slab layer.
2371 		 */
2372 		break;
2373 	}
2374 	mutex_exit(&ccp->cc_lock);
2375 
2376 	/*
2377 	 * We couldn't free our constructed object to the magazine layer,
2378 	 * so apply its destructor and free it to the slab layer.
2379 	 */
2380 	kmem_slab_free_constructed(cp, buf, B_TRUE);
2381 }
2382 
2383 void *
2384 kmem_zalloc(size_t size, int kmflag)
2385 {
2386 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2387 	void *buf;
2388 
2389 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2390 		kmem_cache_t *cp = kmem_alloc_table[index];
2391 		buf = kmem_cache_alloc(cp, kmflag);
2392 		if (buf != NULL) {
2393 			if (cp->cache_flags & KMF_BUFTAG) {
2394 				kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2395 				((uint8_t *)buf)[size] = KMEM_REDZONE_BYTE;
2396 				((uint32_t *)btp)[1] = KMEM_SIZE_ENCODE(size);
2397 
2398 				if (cp->cache_flags & KMF_LITE) {
2399 					KMEM_BUFTAG_LITE_ENTER(btp,
2400 					    kmem_lite_count, caller());
2401 				}
2402 			}
2403 			bzero(buf, size);
2404 		}
2405 	} else {
2406 		buf = kmem_alloc(size, kmflag);
2407 		if (buf != NULL)
2408 			bzero(buf, size);
2409 	}
2410 	return (buf);
2411 }
2412 
2413 void *
2414 kmem_alloc(size_t size, int kmflag)
2415 {
2416 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2417 	void *buf;
2418 
2419 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2420 		kmem_cache_t *cp = kmem_alloc_table[index];
2421 		buf = kmem_cache_alloc(cp, kmflag);
2422 		if ((cp->cache_flags & KMF_BUFTAG) && buf != NULL) {
2423 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2424 			((uint8_t *)buf)[size] = KMEM_REDZONE_BYTE;
2425 			((uint32_t *)btp)[1] = KMEM_SIZE_ENCODE(size);
2426 
2427 			if (cp->cache_flags & KMF_LITE) {
2428 				KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count,
2429 				    caller());
2430 			}
2431 		}
2432 		return (buf);
2433 	}
2434 	if (size == 0)
2435 		return (NULL);
2436 	buf = vmem_alloc(kmem_oversize_arena, size, kmflag & KM_VMFLAGS);
2437 	if (buf == NULL)
2438 		kmem_log_event(kmem_failure_log, NULL, NULL, (void *)size);
2439 	return (buf);
2440 }
2441 
2442 void
2443 kmem_free(void *buf, size_t size)
2444 {
2445 	size_t index = (size - 1) >> KMEM_ALIGN_SHIFT;
2446 
2447 	if (index < KMEM_MAXBUF >> KMEM_ALIGN_SHIFT) {
2448 		kmem_cache_t *cp = kmem_alloc_table[index];
2449 		if (cp->cache_flags & KMF_BUFTAG) {
2450 			kmem_buftag_t *btp = KMEM_BUFTAG(cp, buf);
2451 			uint32_t *ip = (uint32_t *)btp;
2452 			if (ip[1] != KMEM_SIZE_ENCODE(size)) {
2453 				if (*(uint64_t *)buf == KMEM_FREE_PATTERN) {
2454 					kmem_error(KMERR_DUPFREE, cp, buf);
2455 					return;
2456 				}
2457 				if (KMEM_SIZE_VALID(ip[1])) {
2458 					ip[0] = KMEM_SIZE_ENCODE(size);
2459 					kmem_error(KMERR_BADSIZE, cp, buf);
2460 				} else {
2461 					kmem_error(KMERR_REDZONE, cp, buf);
2462 				}
2463 				return;
2464 			}
2465 			if (((uint8_t *)buf)[size] != KMEM_REDZONE_BYTE) {
2466 				kmem_error(KMERR_REDZONE, cp, buf);
2467 				return;
2468 			}
2469 			btp->bt_redzone = KMEM_REDZONE_PATTERN;
2470 			if (cp->cache_flags & KMF_LITE) {
2471 				KMEM_BUFTAG_LITE_ENTER(btp, kmem_lite_count,
2472 				    caller());
2473 			}
2474 		}
2475 		kmem_cache_free(cp, buf);
2476 	} else {
2477 		if (buf == NULL && size == 0)
2478 			return;
2479 		vmem_free(kmem_oversize_arena, buf, size);
2480 	}
2481 }
2482 
2483 void *
2484 kmem_firewall_va_alloc(vmem_t *vmp, size_t size, int vmflag)
2485 {
2486 	size_t realsize = size + vmp->vm_quantum;
2487 	void *addr;
2488 
2489 	/*
2490 	 * Annoying edge case: if 'size' is just shy of ULONG_MAX, adding
2491 	 * vm_quantum will cause integer wraparound.  Check for this, and
2492 	 * blow off the firewall page in this case.  Note that such a
2493 	 * giant allocation (the entire kernel address space) can never
2494 	 * be satisfied, so it will either fail immediately (VM_NOSLEEP)
2495 	 * or sleep forever (VM_SLEEP).  Thus, there is no need for a
2496 	 * corresponding check in kmem_firewall_va_free().
2497 	 */
2498 	if (realsize < size)
2499 		realsize = size;
2500 
2501 	/*
2502 	 * While boot still owns resource management, make sure that this
2503 	 * redzone virtual address allocation is properly accounted for in
2504 	 * OBPs "virtual-memory" "available" lists because we're
2505 	 * effectively claiming them for a red zone.  If we don't do this,
2506 	 * the available lists become too fragmented and too large for the
2507 	 * current boot/kernel memory list interface.
2508 	 */
2509 	addr = vmem_alloc(vmp, realsize, vmflag | VM_NEXTFIT);
2510 
2511 	if (addr != NULL && kvseg.s_base == NULL && realsize != size)
2512 		(void) boot_virt_alloc((char *)addr + size, vmp->vm_quantum);
2513 
2514 	return (addr);
2515 }
2516 
2517 void
2518 kmem_firewall_va_free(vmem_t *vmp, void *addr, size_t size)
2519 {
2520 	ASSERT((kvseg.s_base == NULL ?
2521 	    va_to_pfn((char *)addr + size) :
2522 	    hat_getpfnum(kas.a_hat, (caddr_t)addr + size)) == PFN_INVALID);
2523 
2524 	vmem_free(vmp, addr, size + vmp->vm_quantum);
2525 }
2526 
2527 /*
2528  * Try to allocate at least `size' bytes of memory without sleeping or
2529  * panicking. Return actual allocated size in `asize'. If allocation failed,
2530  * try final allocation with sleep or panic allowed.
2531  */
2532 void *
2533 kmem_alloc_tryhard(size_t size, size_t *asize, int kmflag)
2534 {
2535 	void *p;
2536 
2537 	*asize = P2ROUNDUP(size, KMEM_ALIGN);
2538 	do {
2539 		p = kmem_alloc(*asize, (kmflag | KM_NOSLEEP) & ~KM_PANIC);
2540 		if (p != NULL)
2541 			return (p);
2542 		*asize += KMEM_ALIGN;
2543 	} while (*asize <= PAGESIZE);
2544 
2545 	*asize = P2ROUNDUP(size, KMEM_ALIGN);
2546 	return (kmem_alloc(*asize, kmflag));
2547 }
2548 
2549 /*
2550  * Reclaim all unused memory from a cache.
2551  */
2552 static void
2553 kmem_cache_reap(kmem_cache_t *cp)
2554 {
2555 	ASSERT(taskq_member(kmem_taskq, curthread));
2556 
2557 	/*
2558 	 * Ask the cache's owner to free some memory if possible.
2559 	 * The idea is to handle things like the inode cache, which
2560 	 * typically sits on a bunch of memory that it doesn't truly
2561 	 * *need*.  Reclaim policy is entirely up to the owner; this
2562 	 * callback is just an advisory plea for help.
2563 	 */
2564 	if (cp->cache_reclaim != NULL) {
2565 		long delta;
2566 
2567 		/*
2568 		 * Reclaimed memory should be reapable (not included in the
2569 		 * depot's working set).
2570 		 */
2571 		delta = cp->cache_full.ml_total;
2572 		cp->cache_reclaim(cp->cache_private);
2573 		delta = cp->cache_full.ml_total - delta;
2574 		if (delta > 0) {
2575 			mutex_enter(&cp->cache_depot_lock);
2576 			cp->cache_full.ml_reaplimit += delta;
2577 			cp->cache_full.ml_min += delta;
2578 			mutex_exit(&cp->cache_depot_lock);
2579 		}
2580 	}
2581 
2582 	kmem_depot_ws_reap(cp);
2583 
2584 	if (cp->cache_defrag != NULL && !kmem_move_noreap) {
2585 		kmem_cache_defrag(cp);
2586 	}
2587 }
2588 
2589 static void
2590 kmem_reap_timeout(void *flag_arg)
2591 {
2592 	uint32_t *flag = (uint32_t *)flag_arg;
2593 
2594 	ASSERT(flag == &kmem_reaping || flag == &kmem_reaping_idspace);
2595 	*flag = 0;
2596 }
2597 
2598 static void
2599 kmem_reap_done(void *flag)
2600 {
2601 	(void) timeout(kmem_reap_timeout, flag, kmem_reap_interval);
2602 }
2603 
2604 static void
2605 kmem_reap_start(void *flag)
2606 {
2607 	ASSERT(flag == &kmem_reaping || flag == &kmem_reaping_idspace);
2608 
2609 	if (flag == &kmem_reaping) {
2610 		kmem_cache_applyall(kmem_cache_reap, kmem_taskq, TQ_NOSLEEP);
2611 		/*
2612 		 * if we have segkp under heap, reap segkp cache.
2613 		 */
2614 		if (segkp_fromheap)
2615 			segkp_cache_free();
2616 	}
2617 	else
2618 		kmem_cache_applyall_id(kmem_cache_reap, kmem_taskq, TQ_NOSLEEP);
2619 
2620 	/*
2621 	 * We use taskq_dispatch() to schedule a timeout to clear
2622 	 * the flag so that kmem_reap() becomes self-throttling:
2623 	 * we won't reap again until the current reap completes *and*
2624 	 * at least kmem_reap_interval ticks have elapsed.
2625 	 */
2626 	if (!taskq_dispatch(kmem_taskq, kmem_reap_done, flag, TQ_NOSLEEP))
2627 		kmem_reap_done(flag);
2628 }
2629 
2630 static void
2631 kmem_reap_common(void *flag_arg)
2632 {
2633 	uint32_t *flag = (uint32_t *)flag_arg;
2634 
2635 	if (MUTEX_HELD(&kmem_cache_lock) || kmem_taskq == NULL ||
2636 	    cas32(flag, 0, 1) != 0)
2637 		return;
2638 
2639 	/*
2640 	 * It may not be kosher to do memory allocation when a reap is called
2641 	 * is called (for example, if vmem_populate() is in the call chain).
2642 	 * So we start the reap going with a TQ_NOALLOC dispatch.  If the
2643 	 * dispatch fails, we reset the flag, and the next reap will try again.
2644 	 */
2645 	if (!taskq_dispatch(kmem_taskq, kmem_reap_start, flag, TQ_NOALLOC))
2646 		*flag = 0;
2647 }
2648 
2649 /*
2650  * Reclaim all unused memory from all caches.  Called from the VM system
2651  * when memory gets tight.
2652  */
2653 void
2654 kmem_reap(void)
2655 {
2656 	kmem_reap_common(&kmem_reaping);
2657 }
2658 
2659 /*
2660  * Reclaim all unused memory from identifier arenas, called when a vmem
2661  * arena not back by memory is exhausted.  Since reaping memory-backed caches
2662  * cannot help with identifier exhaustion, we avoid both a large amount of
2663  * work and unwanted side-effects from reclaim callbacks.
2664  */
2665 void
2666 kmem_reap_idspace(void)
2667 {
2668 	kmem_reap_common(&kmem_reaping_idspace);
2669 }
2670 
2671 /*
2672  * Purge all magazines from a cache and set its magazine limit to zero.
2673  * All calls are serialized by the kmem_taskq lock, except for the final
2674  * call from kmem_cache_destroy().
2675  */
2676 static void
2677 kmem_cache_magazine_purge(kmem_cache_t *cp)
2678 {
2679 	kmem_cpu_cache_t *ccp;
2680 	kmem_magazine_t *mp, *pmp;
2681 	int rounds, prounds, cpu_seqid;
2682 
2683 	ASSERT(!list_link_active(&cp->cache_link) ||
2684 	    taskq_member(kmem_taskq, curthread));
2685 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
2686 
2687 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2688 		ccp = &cp->cache_cpu[cpu_seqid];
2689 
2690 		mutex_enter(&ccp->cc_lock);
2691 		mp = ccp->cc_loaded;
2692 		pmp = ccp->cc_ploaded;
2693 		rounds = ccp->cc_rounds;
2694 		prounds = ccp->cc_prounds;
2695 		ccp->cc_loaded = NULL;
2696 		ccp->cc_ploaded = NULL;
2697 		ccp->cc_rounds = -1;
2698 		ccp->cc_prounds = -1;
2699 		ccp->cc_magsize = 0;
2700 		mutex_exit(&ccp->cc_lock);
2701 
2702 		if (mp)
2703 			kmem_magazine_destroy(cp, mp, rounds);
2704 		if (pmp)
2705 			kmem_magazine_destroy(cp, pmp, prounds);
2706 	}
2707 
2708 	/*
2709 	 * Updating the working set statistics twice in a row has the
2710 	 * effect of setting the working set size to zero, so everything
2711 	 * is eligible for reaping.
2712 	 */
2713 	kmem_depot_ws_update(cp);
2714 	kmem_depot_ws_update(cp);
2715 
2716 	kmem_depot_ws_reap(cp);
2717 }
2718 
2719 /*
2720  * Enable per-cpu magazines on a cache.
2721  */
2722 static void
2723 kmem_cache_magazine_enable(kmem_cache_t *cp)
2724 {
2725 	int cpu_seqid;
2726 
2727 	if (cp->cache_flags & KMF_NOMAGAZINE)
2728 		return;
2729 
2730 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2731 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2732 		mutex_enter(&ccp->cc_lock);
2733 		ccp->cc_magsize = cp->cache_magtype->mt_magsize;
2734 		mutex_exit(&ccp->cc_lock);
2735 	}
2736 
2737 }
2738 
2739 /*
2740  * Reap (almost) everything right now.  See kmem_cache_magazine_purge()
2741  * for explanation of the back-to-back kmem_depot_ws_update() calls.
2742  */
2743 void
2744 kmem_cache_reap_now(kmem_cache_t *cp)
2745 {
2746 	ASSERT(list_link_active(&cp->cache_link));
2747 
2748 	kmem_depot_ws_update(cp);
2749 	kmem_depot_ws_update(cp);
2750 
2751 	(void) taskq_dispatch(kmem_taskq,
2752 	    (task_func_t *)kmem_depot_ws_reap, cp, TQ_SLEEP);
2753 	taskq_wait(kmem_taskq);
2754 }
2755 
2756 /*
2757  * Recompute a cache's magazine size.  The trade-off is that larger magazines
2758  * provide a higher transfer rate with the depot, while smaller magazines
2759  * reduce memory consumption.  Magazine resizing is an expensive operation;
2760  * it should not be done frequently.
2761  *
2762  * Changes to the magazine size are serialized by the kmem_taskq lock.
2763  *
2764  * Note: at present this only grows the magazine size.  It might be useful
2765  * to allow shrinkage too.
2766  */
2767 static void
2768 kmem_cache_magazine_resize(kmem_cache_t *cp)
2769 {
2770 	kmem_magtype_t *mtp = cp->cache_magtype;
2771 
2772 	ASSERT(taskq_member(kmem_taskq, curthread));
2773 
2774 	if (cp->cache_chunksize < mtp->mt_maxbuf) {
2775 		kmem_cache_magazine_purge(cp);
2776 		mutex_enter(&cp->cache_depot_lock);
2777 		cp->cache_magtype = ++mtp;
2778 		cp->cache_depot_contention_prev =
2779 		    cp->cache_depot_contention + INT_MAX;
2780 		mutex_exit(&cp->cache_depot_lock);
2781 		kmem_cache_magazine_enable(cp);
2782 	}
2783 }
2784 
2785 /*
2786  * Rescale a cache's hash table, so that the table size is roughly the
2787  * cache size.  We want the average lookup time to be extremely small.
2788  */
2789 static void
2790 kmem_hash_rescale(kmem_cache_t *cp)
2791 {
2792 	kmem_bufctl_t **old_table, **new_table, *bcp;
2793 	size_t old_size, new_size, h;
2794 
2795 	ASSERT(taskq_member(kmem_taskq, curthread));
2796 
2797 	new_size = MAX(KMEM_HASH_INITIAL,
2798 	    1 << (highbit(3 * cp->cache_buftotal + 4) - 2));
2799 	old_size = cp->cache_hash_mask + 1;
2800 
2801 	if ((old_size >> 1) <= new_size && new_size <= (old_size << 1))
2802 		return;
2803 
2804 	new_table = vmem_alloc(kmem_hash_arena, new_size * sizeof (void *),
2805 	    VM_NOSLEEP);
2806 	if (new_table == NULL)
2807 		return;
2808 	bzero(new_table, new_size * sizeof (void *));
2809 
2810 	mutex_enter(&cp->cache_lock);
2811 
2812 	old_size = cp->cache_hash_mask + 1;
2813 	old_table = cp->cache_hash_table;
2814 
2815 	cp->cache_hash_mask = new_size - 1;
2816 	cp->cache_hash_table = new_table;
2817 	cp->cache_rescale++;
2818 
2819 	for (h = 0; h < old_size; h++) {
2820 		bcp = old_table[h];
2821 		while (bcp != NULL) {
2822 			void *addr = bcp->bc_addr;
2823 			kmem_bufctl_t *next_bcp = bcp->bc_next;
2824 			kmem_bufctl_t **hash_bucket = KMEM_HASH(cp, addr);
2825 			bcp->bc_next = *hash_bucket;
2826 			*hash_bucket = bcp;
2827 			bcp = next_bcp;
2828 		}
2829 	}
2830 
2831 	mutex_exit(&cp->cache_lock);
2832 
2833 	vmem_free(kmem_hash_arena, old_table, old_size * sizeof (void *));
2834 }
2835 
2836 /*
2837  * Perform periodic maintenance on a cache: hash rescaling, depot working-set
2838  * update, magazine resizing, and slab consolidation.
2839  */
2840 static void
2841 kmem_cache_update(kmem_cache_t *cp)
2842 {
2843 	int need_hash_rescale = 0;
2844 	int need_magazine_resize = 0;
2845 
2846 	ASSERT(MUTEX_HELD(&kmem_cache_lock));
2847 
2848 	/*
2849 	 * If the cache has become much larger or smaller than its hash table,
2850 	 * fire off a request to rescale the hash table.
2851 	 */
2852 	mutex_enter(&cp->cache_lock);
2853 
2854 	if ((cp->cache_flags & KMF_HASH) &&
2855 	    (cp->cache_buftotal > (cp->cache_hash_mask << 1) ||
2856 	    (cp->cache_buftotal < (cp->cache_hash_mask >> 1) &&
2857 	    cp->cache_hash_mask > KMEM_HASH_INITIAL)))
2858 		need_hash_rescale = 1;
2859 
2860 	mutex_exit(&cp->cache_lock);
2861 
2862 	/*
2863 	 * Update the depot working set statistics.
2864 	 */
2865 	kmem_depot_ws_update(cp);
2866 
2867 	/*
2868 	 * If there's a lot of contention in the depot,
2869 	 * increase the magazine size.
2870 	 */
2871 	mutex_enter(&cp->cache_depot_lock);
2872 
2873 	if (cp->cache_chunksize < cp->cache_magtype->mt_maxbuf &&
2874 	    (int)(cp->cache_depot_contention -
2875 	    cp->cache_depot_contention_prev) > kmem_depot_contention)
2876 		need_magazine_resize = 1;
2877 
2878 	cp->cache_depot_contention_prev = cp->cache_depot_contention;
2879 
2880 	mutex_exit(&cp->cache_depot_lock);
2881 
2882 	if (need_hash_rescale)
2883 		(void) taskq_dispatch(kmem_taskq,
2884 		    (task_func_t *)kmem_hash_rescale, cp, TQ_NOSLEEP);
2885 
2886 	if (need_magazine_resize)
2887 		(void) taskq_dispatch(kmem_taskq,
2888 		    (task_func_t *)kmem_cache_magazine_resize, cp, TQ_NOSLEEP);
2889 
2890 	if (cp->cache_defrag != NULL)
2891 		(void) taskq_dispatch(kmem_taskq,
2892 		    (task_func_t *)kmem_cache_scan, cp, TQ_NOSLEEP);
2893 }
2894 
2895 static void
2896 kmem_update_timeout(void *dummy)
2897 {
2898 	static void kmem_update(void *);
2899 
2900 	(void) timeout(kmem_update, dummy, kmem_reap_interval);
2901 }
2902 
2903 static void
2904 kmem_update(void *dummy)
2905 {
2906 	kmem_cache_applyall(kmem_cache_update, NULL, TQ_NOSLEEP);
2907 
2908 	/*
2909 	 * We use taskq_dispatch() to reschedule the timeout so that
2910 	 * kmem_update() becomes self-throttling: it won't schedule
2911 	 * new tasks until all previous tasks have completed.
2912 	 */
2913 	if (!taskq_dispatch(kmem_taskq, kmem_update_timeout, dummy, TQ_NOSLEEP))
2914 		kmem_update_timeout(NULL);
2915 }
2916 
2917 static int
2918 kmem_cache_kstat_update(kstat_t *ksp, int rw)
2919 {
2920 	struct kmem_cache_kstat *kmcp = &kmem_cache_kstat;
2921 	kmem_cache_t *cp = ksp->ks_private;
2922 	uint64_t cpu_buf_avail;
2923 	uint64_t buf_avail = 0;
2924 	int cpu_seqid;
2925 
2926 	ASSERT(MUTEX_HELD(&kmem_cache_kstat_lock));
2927 
2928 	if (rw == KSTAT_WRITE)
2929 		return (EACCES);
2930 
2931 	mutex_enter(&cp->cache_lock);
2932 
2933 	kmcp->kmc_alloc_fail.value.ui64		= cp->cache_alloc_fail;
2934 	kmcp->kmc_alloc.value.ui64		= cp->cache_slab_alloc;
2935 	kmcp->kmc_free.value.ui64		= cp->cache_slab_free;
2936 	kmcp->kmc_slab_alloc.value.ui64		= cp->cache_slab_alloc;
2937 	kmcp->kmc_slab_free.value.ui64		= cp->cache_slab_free;
2938 
2939 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
2940 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
2941 
2942 		mutex_enter(&ccp->cc_lock);
2943 
2944 		cpu_buf_avail = 0;
2945 		if (ccp->cc_rounds > 0)
2946 			cpu_buf_avail += ccp->cc_rounds;
2947 		if (ccp->cc_prounds > 0)
2948 			cpu_buf_avail += ccp->cc_prounds;
2949 
2950 		kmcp->kmc_alloc.value.ui64	+= ccp->cc_alloc;
2951 		kmcp->kmc_free.value.ui64	+= ccp->cc_free;
2952 		buf_avail			+= cpu_buf_avail;
2953 
2954 		mutex_exit(&ccp->cc_lock);
2955 	}
2956 
2957 	mutex_enter(&cp->cache_depot_lock);
2958 
2959 	kmcp->kmc_depot_alloc.value.ui64	= cp->cache_full.ml_alloc;
2960 	kmcp->kmc_depot_free.value.ui64		= cp->cache_empty.ml_alloc;
2961 	kmcp->kmc_depot_contention.value.ui64	= cp->cache_depot_contention;
2962 	kmcp->kmc_full_magazines.value.ui64	= cp->cache_full.ml_total;
2963 	kmcp->kmc_empty_magazines.value.ui64	= cp->cache_empty.ml_total;
2964 	kmcp->kmc_magazine_size.value.ui64	=
2965 	    (cp->cache_flags & KMF_NOMAGAZINE) ?
2966 	    0 : cp->cache_magtype->mt_magsize;
2967 
2968 	kmcp->kmc_alloc.value.ui64		+= cp->cache_full.ml_alloc;
2969 	kmcp->kmc_free.value.ui64		+= cp->cache_empty.ml_alloc;
2970 	buf_avail += cp->cache_full.ml_total * cp->cache_magtype->mt_magsize;
2971 
2972 	mutex_exit(&cp->cache_depot_lock);
2973 
2974 	kmcp->kmc_buf_size.value.ui64	= cp->cache_bufsize;
2975 	kmcp->kmc_align.value.ui64	= cp->cache_align;
2976 	kmcp->kmc_chunk_size.value.ui64	= cp->cache_chunksize;
2977 	kmcp->kmc_slab_size.value.ui64	= cp->cache_slabsize;
2978 	kmcp->kmc_buf_constructed.value.ui64 = buf_avail;
2979 	buf_avail += cp->cache_bufslab;
2980 	kmcp->kmc_buf_avail.value.ui64	= buf_avail;
2981 	kmcp->kmc_buf_inuse.value.ui64	= cp->cache_buftotal - buf_avail;
2982 	kmcp->kmc_buf_total.value.ui64	= cp->cache_buftotal;
2983 	kmcp->kmc_buf_max.value.ui64	= cp->cache_bufmax;
2984 	kmcp->kmc_slab_create.value.ui64	= cp->cache_slab_create;
2985 	kmcp->kmc_slab_destroy.value.ui64	= cp->cache_slab_destroy;
2986 	kmcp->kmc_hash_size.value.ui64	= (cp->cache_flags & KMF_HASH) ?
2987 	    cp->cache_hash_mask + 1 : 0;
2988 	kmcp->kmc_hash_lookup_depth.value.ui64	= cp->cache_lookup_depth;
2989 	kmcp->kmc_hash_rescale.value.ui64	= cp->cache_rescale;
2990 	kmcp->kmc_vmem_source.value.ui64	= cp->cache_arena->vm_id;
2991 
2992 	if (cp->cache_defrag == NULL) {
2993 		kmcp->kmc_move_callbacks.value.ui64	= 0;
2994 		kmcp->kmc_move_yes.value.ui64		= 0;
2995 		kmcp->kmc_move_no.value.ui64		= 0;
2996 		kmcp->kmc_move_later.value.ui64		= 0;
2997 		kmcp->kmc_move_dont_need.value.ui64	= 0;
2998 		kmcp->kmc_move_dont_know.value.ui64	= 0;
2999 		kmcp->kmc_move_hunt_found.value.ui64	= 0;
3000 	} else {
3001 		kmem_defrag_t *kd = cp->cache_defrag;
3002 		kmcp->kmc_move_callbacks.value.ui64	= kd->kmd_callbacks;
3003 		kmcp->kmc_move_yes.value.ui64		= kd->kmd_yes;
3004 		kmcp->kmc_move_no.value.ui64		= kd->kmd_no;
3005 		kmcp->kmc_move_later.value.ui64		= kd->kmd_later;
3006 		kmcp->kmc_move_dont_need.value.ui64	= kd->kmd_dont_need;
3007 		kmcp->kmc_move_dont_know.value.ui64	= kd->kmd_dont_know;
3008 		kmcp->kmc_move_hunt_found.value.ui64	= kd->kmd_hunt_found;
3009 	}
3010 
3011 	mutex_exit(&cp->cache_lock);
3012 	return (0);
3013 }
3014 
3015 /*
3016  * Return a named statistic about a particular cache.
3017  * This shouldn't be called very often, so it's currently designed for
3018  * simplicity (leverages existing kstat support) rather than efficiency.
3019  */
3020 uint64_t
3021 kmem_cache_stat(kmem_cache_t *cp, char *name)
3022 {
3023 	int i;
3024 	kstat_t *ksp = cp->cache_kstat;
3025 	kstat_named_t *knp = (kstat_named_t *)&kmem_cache_kstat;
3026 	uint64_t value = 0;
3027 
3028 	if (ksp != NULL) {
3029 		mutex_enter(&kmem_cache_kstat_lock);
3030 		(void) kmem_cache_kstat_update(ksp, KSTAT_READ);
3031 		for (i = 0; i < ksp->ks_ndata; i++) {
3032 			if (strcmp(knp[i].name, name) == 0) {
3033 				value = knp[i].value.ui64;
3034 				break;
3035 			}
3036 		}
3037 		mutex_exit(&kmem_cache_kstat_lock);
3038 	}
3039 	return (value);
3040 }
3041 
3042 /*
3043  * Return an estimate of currently available kernel heap memory.
3044  * On 32-bit systems, physical memory may exceed virtual memory,
3045  * we just truncate the result at 1GB.
3046  */
3047 size_t
3048 kmem_avail(void)
3049 {
3050 	spgcnt_t rmem = availrmem - tune.t_minarmem;
3051 	spgcnt_t fmem = freemem - minfree;
3052 
3053 	return ((size_t)ptob(MIN(MAX(MIN(rmem, fmem), 0),
3054 	    1 << (30 - PAGESHIFT))));
3055 }
3056 
3057 /*
3058  * Return the maximum amount of memory that is (in theory) allocatable
3059  * from the heap. This may be used as an estimate only since there
3060  * is no guarentee this space will still be available when an allocation
3061  * request is made, nor that the space may be allocated in one big request
3062  * due to kernel heap fragmentation.
3063  */
3064 size_t
3065 kmem_maxavail(void)
3066 {
3067 	spgcnt_t pmem = availrmem - tune.t_minarmem;
3068 	spgcnt_t vmem = btop(vmem_size(heap_arena, VMEM_FREE));
3069 
3070 	return ((size_t)ptob(MAX(MIN(pmem, vmem), 0)));
3071 }
3072 
3073 /*
3074  * Indicate whether memory-intensive kmem debugging is enabled.
3075  */
3076 int
3077 kmem_debugging(void)
3078 {
3079 	return (kmem_flags & (KMF_AUDIT | KMF_REDZONE));
3080 }
3081 
3082 /* binning function, sorts finely at the two extremes */
3083 #define	KMEM_PARTIAL_SLAB_WEIGHT(sp, binshift)				\
3084 	((((sp)->slab_refcnt <= (binshift)) ||				\
3085 	    (((sp)->slab_chunks - (sp)->slab_refcnt) <= (binshift)))	\
3086 	    ? -(sp)->slab_refcnt					\
3087 	    : -((binshift) + ((sp)->slab_refcnt >> (binshift))))
3088 
3089 /*
3090  * Minimizing the number of partial slabs on the freelist minimizes
3091  * fragmentation (the ratio of unused buffers held by the slab layer). There are
3092  * two ways to get a slab off of the freelist: 1) free all the buffers on the
3093  * slab, and 2) allocate all the buffers on the slab. It follows that we want
3094  * the most-used slabs at the front of the list where they have the best chance
3095  * of being completely allocated, and the least-used slabs at a safe distance
3096  * from the front to improve the odds that the few remaining buffers will all be
3097  * freed before another allocation can tie up the slab. For that reason a slab
3098  * with a higher slab_refcnt sorts less than than a slab with a lower
3099  * slab_refcnt.
3100  *
3101  * However, if a slab has at least one buffer that is deemed unfreeable, we
3102  * would rather have that slab at the front of the list regardless of
3103  * slab_refcnt, since even one unfreeable buffer makes the entire slab
3104  * unfreeable. If the client returns KMEM_CBRC_NO in response to a cache_move()
3105  * callback, the slab is marked unfreeable for as long as it remains on the
3106  * freelist.
3107  */
3108 static int
3109 kmem_partial_slab_cmp(const void *p0, const void *p1)
3110 {
3111 	const kmem_cache_t *cp;
3112 	const kmem_slab_t *s0 = p0;
3113 	const kmem_slab_t *s1 = p1;
3114 	int w0, w1;
3115 	size_t binshift;
3116 
3117 	ASSERT(KMEM_SLAB_IS_PARTIAL(s0));
3118 	ASSERT(KMEM_SLAB_IS_PARTIAL(s1));
3119 	ASSERT(s0->slab_cache == s1->slab_cache);
3120 	cp = s1->slab_cache;
3121 	ASSERT(MUTEX_HELD(&cp->cache_lock));
3122 	binshift = cp->cache_partial_binshift;
3123 
3124 	/* weight of first slab */
3125 	w0 = KMEM_PARTIAL_SLAB_WEIGHT(s0, binshift);
3126 	if (s0->slab_flags & KMEM_SLAB_NOMOVE) {
3127 		w0 -= cp->cache_maxchunks;
3128 	}
3129 
3130 	/* weight of second slab */
3131 	w1 = KMEM_PARTIAL_SLAB_WEIGHT(s1, binshift);
3132 	if (s1->slab_flags & KMEM_SLAB_NOMOVE) {
3133 		w1 -= cp->cache_maxchunks;
3134 	}
3135 
3136 	if (w0 < w1)
3137 		return (-1);
3138 	if (w0 > w1)
3139 		return (1);
3140 
3141 	/* compare pointer values */
3142 	if ((uintptr_t)s0 < (uintptr_t)s1)
3143 		return (-1);
3144 	if ((uintptr_t)s0 > (uintptr_t)s1)
3145 		return (1);
3146 
3147 	return (0);
3148 }
3149 
3150 static void
3151 kmem_check_destructor(kmem_cache_t *cp)
3152 {
3153 	void *buf;
3154 
3155 	if (cp->cache_destructor == NULL)
3156 		return;
3157 
3158 	/*
3159 	 * Assert that it is valid to call the destructor on a newly constructed
3160 	 * object without any intervening client code using the object.
3161 	 * Allocate from the slab layer to ensure that the client has not
3162 	 * touched the buffer.
3163 	 */
3164 	buf = kmem_slab_alloc(cp, KM_NOSLEEP);
3165 	if (buf == NULL)
3166 		return;
3167 
3168 	if (cp->cache_flags & KMF_BUFTAG) {
3169 		if (kmem_cache_alloc_debug(cp, buf, KM_NOSLEEP, 1,
3170 		    caller()) != 0)
3171 			return;
3172 	} else if (cp->cache_constructor != NULL &&
3173 	    cp->cache_constructor(buf, cp->cache_private, KM_NOSLEEP) != 0) {
3174 		atomic_add_64(&cp->cache_alloc_fail, 1);
3175 		kmem_slab_free(cp, buf);
3176 		return;
3177 	}
3178 
3179 	kmem_slab_free_constructed(cp, buf, B_FALSE);
3180 }
3181 
3182 /*
3183  * It must be valid to call the destructor (if any) on a newly created object.
3184  * That is, the constructor (if any) must leave the object in a valid state for
3185  * the destructor.
3186  */
3187 kmem_cache_t *
3188 kmem_cache_create(
3189 	char *name,		/* descriptive name for this cache */
3190 	size_t bufsize,		/* size of the objects it manages */
3191 	size_t align,		/* required object alignment */
3192 	int (*constructor)(void *, void *, int), /* object constructor */
3193 	void (*destructor)(void *, void *),	/* object destructor */
3194 	void (*reclaim)(void *), /* memory reclaim callback */
3195 	void *private,		/* pass-thru arg for constr/destr/reclaim */
3196 	vmem_t *vmp,		/* vmem source for slab allocation */
3197 	int cflags)		/* cache creation flags */
3198 {
3199 	int cpu_seqid;
3200 	size_t chunksize;
3201 	kmem_cache_t *cp;
3202 	kmem_magtype_t *mtp;
3203 	size_t csize = KMEM_CACHE_SIZE(max_ncpus);
3204 
3205 #ifdef	DEBUG
3206 	/*
3207 	 * Cache names should conform to the rules for valid C identifiers
3208 	 */
3209 	if (!strident_valid(name)) {
3210 		cmn_err(CE_CONT,
3211 		    "kmem_cache_create: '%s' is an invalid cache name\n"
3212 		    "cache names must conform to the rules for "
3213 		    "C identifiers\n", name);
3214 	}
3215 #endif	/* DEBUG */
3216 
3217 	if (vmp == NULL)
3218 		vmp = kmem_default_arena;
3219 
3220 	/*
3221 	 * If this kmem cache has an identifier vmem arena as its source, mark
3222 	 * it such to allow kmem_reap_idspace().
3223 	 */
3224 	ASSERT(!(cflags & KMC_IDENTIFIER));   /* consumer should not set this */
3225 	if (vmp->vm_cflags & VMC_IDENTIFIER)
3226 		cflags |= KMC_IDENTIFIER;
3227 
3228 	/*
3229 	 * Get a kmem_cache structure.  We arrange that cp->cache_cpu[]
3230 	 * is aligned on a KMEM_CPU_CACHE_SIZE boundary to prevent
3231 	 * false sharing of per-CPU data.
3232 	 */
3233 	cp = vmem_xalloc(kmem_cache_arena, csize, KMEM_CPU_CACHE_SIZE,
3234 	    P2NPHASE(csize, KMEM_CPU_CACHE_SIZE), 0, NULL, NULL, VM_SLEEP);
3235 	bzero(cp, csize);
3236 	list_link_init(&cp->cache_link);
3237 
3238 	if (align == 0)
3239 		align = KMEM_ALIGN;
3240 
3241 	/*
3242 	 * If we're not at least KMEM_ALIGN aligned, we can't use free
3243 	 * memory to hold bufctl information (because we can't safely
3244 	 * perform word loads and stores on it).
3245 	 */
3246 	if (align < KMEM_ALIGN)
3247 		cflags |= KMC_NOTOUCH;
3248 
3249 	if ((align & (align - 1)) != 0 || align > vmp->vm_quantum)
3250 		panic("kmem_cache_create: bad alignment %lu", align);
3251 
3252 	mutex_enter(&kmem_flags_lock);
3253 	if (kmem_flags & KMF_RANDOMIZE)
3254 		kmem_flags = (((kmem_flags | ~KMF_RANDOM) + 1) & KMF_RANDOM) |
3255 		    KMF_RANDOMIZE;
3256 	cp->cache_flags = (kmem_flags | cflags) & KMF_DEBUG;
3257 	mutex_exit(&kmem_flags_lock);
3258 
3259 	/*
3260 	 * Make sure all the various flags are reasonable.
3261 	 */
3262 	ASSERT(!(cflags & KMC_NOHASH) || !(cflags & KMC_NOTOUCH));
3263 
3264 	if (cp->cache_flags & KMF_LITE) {
3265 		if (bufsize >= kmem_lite_minsize &&
3266 		    align <= kmem_lite_maxalign &&
3267 		    P2PHASE(bufsize, kmem_lite_maxalign) != 0) {
3268 			cp->cache_flags |= KMF_BUFTAG;
3269 			cp->cache_flags &= ~(KMF_AUDIT | KMF_FIREWALL);
3270 		} else {
3271 			cp->cache_flags &= ~KMF_DEBUG;
3272 		}
3273 	}
3274 
3275 	if (cp->cache_flags & KMF_DEADBEEF)
3276 		cp->cache_flags |= KMF_REDZONE;
3277 
3278 	if ((cflags & KMC_QCACHE) && (cp->cache_flags & KMF_AUDIT))
3279 		cp->cache_flags |= KMF_NOMAGAZINE;
3280 
3281 	if (cflags & KMC_NODEBUG)
3282 		cp->cache_flags &= ~KMF_DEBUG;
3283 
3284 	if (cflags & KMC_NOTOUCH)
3285 		cp->cache_flags &= ~KMF_TOUCH;
3286 
3287 	if (cflags & KMC_NOHASH)
3288 		cp->cache_flags &= ~(KMF_AUDIT | KMF_FIREWALL);
3289 
3290 	if (cflags & KMC_NOMAGAZINE)
3291 		cp->cache_flags |= KMF_NOMAGAZINE;
3292 
3293 	if ((cp->cache_flags & KMF_AUDIT) && !(cflags & KMC_NOTOUCH))
3294 		cp->cache_flags |= KMF_REDZONE;
3295 
3296 	if (!(cp->cache_flags & KMF_AUDIT))
3297 		cp->cache_flags &= ~KMF_CONTENTS;
3298 
3299 	if ((cp->cache_flags & KMF_BUFTAG) && bufsize >= kmem_minfirewall &&
3300 	    !(cp->cache_flags & KMF_LITE) && !(cflags & KMC_NOHASH))
3301 		cp->cache_flags |= KMF_FIREWALL;
3302 
3303 	if (vmp != kmem_default_arena || kmem_firewall_arena == NULL)
3304 		cp->cache_flags &= ~KMF_FIREWALL;
3305 
3306 	if (cp->cache_flags & KMF_FIREWALL) {
3307 		cp->cache_flags &= ~KMF_BUFTAG;
3308 		cp->cache_flags |= KMF_NOMAGAZINE;
3309 		ASSERT(vmp == kmem_default_arena);
3310 		vmp = kmem_firewall_arena;
3311 	}
3312 
3313 	/*
3314 	 * Set cache properties.
3315 	 */
3316 	(void) strncpy(cp->cache_name, name, KMEM_CACHE_NAMELEN);
3317 	strident_canon(cp->cache_name, KMEM_CACHE_NAMELEN + 1);
3318 	cp->cache_bufsize = bufsize;
3319 	cp->cache_align = align;
3320 	cp->cache_constructor = constructor;
3321 	cp->cache_destructor = destructor;
3322 	cp->cache_reclaim = reclaim;
3323 	cp->cache_private = private;
3324 	cp->cache_arena = vmp;
3325 	cp->cache_cflags = cflags;
3326 
3327 	/*
3328 	 * Determine the chunk size.
3329 	 */
3330 	chunksize = bufsize;
3331 
3332 	if (align >= KMEM_ALIGN) {
3333 		chunksize = P2ROUNDUP(chunksize, KMEM_ALIGN);
3334 		cp->cache_bufctl = chunksize - KMEM_ALIGN;
3335 	}
3336 
3337 	if (cp->cache_flags & KMF_BUFTAG) {
3338 		cp->cache_bufctl = chunksize;
3339 		cp->cache_buftag = chunksize;
3340 		if (cp->cache_flags & KMF_LITE)
3341 			chunksize += KMEM_BUFTAG_LITE_SIZE(kmem_lite_count);
3342 		else
3343 			chunksize += sizeof (kmem_buftag_t);
3344 	}
3345 
3346 	if (cp->cache_flags & KMF_DEADBEEF) {
3347 		cp->cache_verify = MIN(cp->cache_buftag, kmem_maxverify);
3348 		if (cp->cache_flags & KMF_LITE)
3349 			cp->cache_verify = sizeof (uint64_t);
3350 	}
3351 
3352 	cp->cache_contents = MIN(cp->cache_bufctl, kmem_content_maxsave);
3353 
3354 	cp->cache_chunksize = chunksize = P2ROUNDUP(chunksize, align);
3355 
3356 	/*
3357 	 * Now that we know the chunk size, determine the optimal slab size.
3358 	 */
3359 	if (vmp == kmem_firewall_arena) {
3360 		cp->cache_slabsize = P2ROUNDUP(chunksize, vmp->vm_quantum);
3361 		cp->cache_mincolor = cp->cache_slabsize - chunksize;
3362 		cp->cache_maxcolor = cp->cache_mincolor;
3363 		cp->cache_flags |= KMF_HASH;
3364 		ASSERT(!(cp->cache_flags & KMF_BUFTAG));
3365 	} else if ((cflags & KMC_NOHASH) || (!(cflags & KMC_NOTOUCH) &&
3366 	    !(cp->cache_flags & KMF_AUDIT) &&
3367 	    chunksize < vmp->vm_quantum / KMEM_VOID_FRACTION)) {
3368 		cp->cache_slabsize = vmp->vm_quantum;
3369 		cp->cache_mincolor = 0;
3370 		cp->cache_maxcolor =
3371 		    (cp->cache_slabsize - sizeof (kmem_slab_t)) % chunksize;
3372 		ASSERT(chunksize + sizeof (kmem_slab_t) <= cp->cache_slabsize);
3373 		ASSERT(!(cp->cache_flags & KMF_AUDIT));
3374 	} else {
3375 		size_t chunks, bestfit, waste, slabsize;
3376 		size_t minwaste = LONG_MAX;
3377 
3378 		for (chunks = 1; chunks <= KMEM_VOID_FRACTION; chunks++) {
3379 			slabsize = P2ROUNDUP(chunksize * chunks,
3380 			    vmp->vm_quantum);
3381 			chunks = slabsize / chunksize;
3382 			waste = (slabsize % chunksize) / chunks;
3383 			if (waste < minwaste) {
3384 				minwaste = waste;
3385 				bestfit = slabsize;
3386 			}
3387 		}
3388 		if (cflags & KMC_QCACHE)
3389 			bestfit = VMEM_QCACHE_SLABSIZE(vmp->vm_qcache_max);
3390 		cp->cache_slabsize = bestfit;
3391 		cp->cache_mincolor = 0;
3392 		cp->cache_maxcolor = bestfit % chunksize;
3393 		cp->cache_flags |= KMF_HASH;
3394 	}
3395 
3396 	cp->cache_maxchunks = (cp->cache_slabsize / cp->cache_chunksize);
3397 	cp->cache_partial_binshift = highbit(cp->cache_maxchunks / 16) + 1;
3398 
3399 	if (cp->cache_flags & KMF_HASH) {
3400 		ASSERT(!(cflags & KMC_NOHASH));
3401 		cp->cache_bufctl_cache = (cp->cache_flags & KMF_AUDIT) ?
3402 		    kmem_bufctl_audit_cache : kmem_bufctl_cache;
3403 	}
3404 
3405 	if (cp->cache_maxcolor >= vmp->vm_quantum)
3406 		cp->cache_maxcolor = vmp->vm_quantum - 1;
3407 
3408 	cp->cache_color = cp->cache_mincolor;
3409 
3410 	/*
3411 	 * Initialize the rest of the slab layer.
3412 	 */
3413 	mutex_init(&cp->cache_lock, NULL, MUTEX_DEFAULT, NULL);
3414 
3415 	avl_create(&cp->cache_partial_slabs, kmem_partial_slab_cmp,
3416 	    sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link));
3417 	/* LINTED: E_TRUE_LOGICAL_EXPR */
3418 	ASSERT(sizeof (list_node_t) <= sizeof (avl_node_t));
3419 	/* reuse partial slab AVL linkage for complete slab list linkage */
3420 	list_create(&cp->cache_complete_slabs,
3421 	    sizeof (kmem_slab_t), offsetof(kmem_slab_t, slab_link));
3422 
3423 	if (cp->cache_flags & KMF_HASH) {
3424 		cp->cache_hash_table = vmem_alloc(kmem_hash_arena,
3425 		    KMEM_HASH_INITIAL * sizeof (void *), VM_SLEEP);
3426 		bzero(cp->cache_hash_table,
3427 		    KMEM_HASH_INITIAL * sizeof (void *));
3428 		cp->cache_hash_mask = KMEM_HASH_INITIAL - 1;
3429 		cp->cache_hash_shift = highbit((ulong_t)chunksize) - 1;
3430 	}
3431 
3432 	/*
3433 	 * Initialize the depot.
3434 	 */
3435 	mutex_init(&cp->cache_depot_lock, NULL, MUTEX_DEFAULT, NULL);
3436 
3437 	for (mtp = kmem_magtype; chunksize <= mtp->mt_minbuf; mtp++)
3438 		continue;
3439 
3440 	cp->cache_magtype = mtp;
3441 
3442 	/*
3443 	 * Initialize the CPU layer.
3444 	 */
3445 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
3446 		kmem_cpu_cache_t *ccp = &cp->cache_cpu[cpu_seqid];
3447 		mutex_init(&ccp->cc_lock, NULL, MUTEX_DEFAULT, NULL);
3448 		ccp->cc_flags = cp->cache_flags;
3449 		ccp->cc_rounds = -1;
3450 		ccp->cc_prounds = -1;
3451 	}
3452 
3453 	/*
3454 	 * Create the cache's kstats.
3455 	 */
3456 	if ((cp->cache_kstat = kstat_create("unix", 0, cp->cache_name,
3457 	    "kmem_cache", KSTAT_TYPE_NAMED,
3458 	    sizeof (kmem_cache_kstat) / sizeof (kstat_named_t),
3459 	    KSTAT_FLAG_VIRTUAL)) != NULL) {
3460 		cp->cache_kstat->ks_data = &kmem_cache_kstat;
3461 		cp->cache_kstat->ks_update = kmem_cache_kstat_update;
3462 		cp->cache_kstat->ks_private = cp;
3463 		cp->cache_kstat->ks_lock = &kmem_cache_kstat_lock;
3464 		kstat_install(cp->cache_kstat);
3465 	}
3466 
3467 	/*
3468 	 * Add the cache to the global list.  This makes it visible
3469 	 * to kmem_update(), so the cache must be ready for business.
3470 	 */
3471 	mutex_enter(&kmem_cache_lock);
3472 	list_insert_tail(&kmem_caches, cp);
3473 	mutex_exit(&kmem_cache_lock);
3474 
3475 	if (kmem_ready)
3476 		kmem_cache_magazine_enable(cp);
3477 
3478 	if (kmem_mp_init_done && cp->cache_destructor != NULL) {
3479 		kmem_check_destructor(cp);
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 }
3987 
3988 void
3989 kmem_mp_init(void)
3990 {
3991 	mutex_enter(&cpu_lock);
3992 	register_cpu_setup_func(kmem_cpu_setup, NULL);
3993 	mutex_exit(&cpu_lock);
3994 
3995 	kmem_update_timeout(NULL);
3996 
3997 	kmem_mp_init_done = B_TRUE;
3998 	/*
3999 	 * Defer checking destructors until now to avoid constructor
4000 	 * dependencies during startup.
4001 	 */
4002 	kmem_cache_applyall(kmem_check_destructor, NULL, 0);
4003 }
4004 
4005 /*
4006  * Return the slab of the allocated buffer, or NULL if the buffer is not
4007  * allocated. This function may be called with a known slab address to determine
4008  * whether or not the buffer is allocated, or with a NULL slab address to obtain
4009  * an allocated buffer's slab.
4010  */
4011 static kmem_slab_t *
4012 kmem_slab_allocated(kmem_cache_t *cp, kmem_slab_t *sp, void *buf)
4013 {
4014 	kmem_bufctl_t *bcp, *bufbcp;
4015 
4016 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4017 	ASSERT(sp == NULL || KMEM_SLAB_MEMBER(sp, buf));
4018 
4019 	if (cp->cache_flags & KMF_HASH) {
4020 		for (bcp = *KMEM_HASH(cp, buf);
4021 		    (bcp != NULL) && (bcp->bc_addr != buf);
4022 		    bcp = bcp->bc_next) {
4023 			continue;
4024 		}
4025 		ASSERT(sp != NULL && bcp != NULL ? sp == bcp->bc_slab : 1);
4026 		return (bcp == NULL ? NULL : bcp->bc_slab);
4027 	}
4028 
4029 	if (sp == NULL) {
4030 		sp = KMEM_SLAB(cp, buf);
4031 	}
4032 	bufbcp = KMEM_BUFCTL(cp, buf);
4033 	for (bcp = sp->slab_head;
4034 	    (bcp != NULL) && (bcp != bufbcp);
4035 	    bcp = bcp->bc_next) {
4036 		continue;
4037 	}
4038 	return (bcp == NULL ? sp : NULL);
4039 }
4040 
4041 static boolean_t
4042 kmem_slab_is_reclaimable(kmem_cache_t *cp, kmem_slab_t *sp, int flags)
4043 {
4044 	long refcnt;
4045 
4046 	ASSERT(cp->cache_defrag != NULL);
4047 
4048 	/* If we're desperate, we don't care if the client said NO. */
4049 	refcnt = sp->slab_refcnt;
4050 	if (flags & KMM_DESPERATE) {
4051 		return (refcnt < sp->slab_chunks); /* any partial */
4052 	}
4053 
4054 	if (sp->slab_flags & KMEM_SLAB_NOMOVE) {
4055 		return (B_FALSE);
4056 	}
4057 
4058 	if (kmem_move_any_partial) {
4059 		return (refcnt < sp->slab_chunks);
4060 	}
4061 
4062 	if ((refcnt == 1) && (refcnt < sp->slab_chunks)) {
4063 		return (B_TRUE);
4064 	}
4065 
4066 	/*
4067 	 * The reclaim threshold is adjusted at each kmem_cache_scan() so that
4068 	 * slabs with a progressively higher percentage of used buffers can be
4069 	 * reclaimed until the cache as a whole is no longer fragmented.
4070 	 *
4071 	 *	sp->slab_refcnt   kmd_reclaim_numer
4072 	 *	--------------- < ------------------
4073 	 *	sp->slab_chunks   KMEM_VOID_FRACTION
4074 	 */
4075 	return ((refcnt * KMEM_VOID_FRACTION) <
4076 	    (sp->slab_chunks * cp->cache_defrag->kmd_reclaim_numer));
4077 }
4078 
4079 static void *
4080 kmem_hunt_mag(kmem_cache_t *cp, kmem_magazine_t *m, int n, void *buf,
4081     void *tbuf)
4082 {
4083 	int i;		/* magazine round index */
4084 
4085 	for (i = 0; i < n; i++) {
4086 		if (buf == m->mag_round[i]) {
4087 			if (cp->cache_flags & KMF_BUFTAG) {
4088 				(void) kmem_cache_free_debug(cp, tbuf,
4089 				    caller());
4090 			}
4091 			m->mag_round[i] = tbuf;
4092 			return (buf);
4093 		}
4094 	}
4095 
4096 	return (NULL);
4097 }
4098 
4099 /*
4100  * Hunt the magazine layer for the given buffer. If found, the buffer is
4101  * removed from the magazine layer and returned, otherwise NULL is returned.
4102  * The state of the returned buffer is freed and constructed.
4103  */
4104 static void *
4105 kmem_hunt_mags(kmem_cache_t *cp, void *buf)
4106 {
4107 	kmem_cpu_cache_t *ccp;
4108 	kmem_magazine_t	*m;
4109 	int cpu_seqid;
4110 	int n;		/* magazine rounds */
4111 	void *tbuf;	/* temporary swap buffer */
4112 
4113 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4114 
4115 	/*
4116 	 * Allocated a buffer to swap with the one we hope to pull out of a
4117 	 * magazine when found.
4118 	 */
4119 	tbuf = kmem_cache_alloc(cp, KM_NOSLEEP);
4120 	if (tbuf == NULL) {
4121 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_alloc_fail);
4122 		return (NULL);
4123 	}
4124 	if (tbuf == buf) {
4125 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_lucky);
4126 		if (cp->cache_flags & KMF_BUFTAG) {
4127 			(void) kmem_cache_free_debug(cp, buf, caller());
4128 		}
4129 		return (buf);
4130 	}
4131 
4132 	/* Hunt the depot. */
4133 	mutex_enter(&cp->cache_depot_lock);
4134 	n = cp->cache_magtype->mt_magsize;
4135 	for (m = cp->cache_full.ml_list; m != NULL; m = m->mag_next) {
4136 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4137 			mutex_exit(&cp->cache_depot_lock);
4138 			return (buf);
4139 		}
4140 	}
4141 	mutex_exit(&cp->cache_depot_lock);
4142 
4143 	/* Hunt the per-CPU magazines. */
4144 	for (cpu_seqid = 0; cpu_seqid < max_ncpus; cpu_seqid++) {
4145 		ccp = &cp->cache_cpu[cpu_seqid];
4146 
4147 		mutex_enter(&ccp->cc_lock);
4148 		m = ccp->cc_loaded;
4149 		n = ccp->cc_rounds;
4150 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4151 			mutex_exit(&ccp->cc_lock);
4152 			return (buf);
4153 		}
4154 		m = ccp->cc_ploaded;
4155 		n = ccp->cc_prounds;
4156 		if (kmem_hunt_mag(cp, m, n, buf, tbuf) != NULL) {
4157 			mutex_exit(&ccp->cc_lock);
4158 			return (buf);
4159 		}
4160 		mutex_exit(&ccp->cc_lock);
4161 	}
4162 
4163 	kmem_cache_free(cp, tbuf);
4164 	return (NULL);
4165 }
4166 
4167 /*
4168  * May be called from the kmem_move_taskq, from kmem_cache_move_notify_task(),
4169  * or when the buffer is freed.
4170  */
4171 static void
4172 kmem_slab_move_yes(kmem_cache_t *cp, kmem_slab_t *sp, void *from_buf)
4173 {
4174 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4175 	ASSERT(KMEM_SLAB_MEMBER(sp, from_buf));
4176 
4177 	if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4178 		return;
4179 	}
4180 
4181 	if (sp->slab_flags & KMEM_SLAB_NOMOVE) {
4182 		if (KMEM_SLAB_OFFSET(sp, from_buf) == sp->slab_stuck_offset) {
4183 			avl_remove(&cp->cache_partial_slabs, sp);
4184 			sp->slab_flags &= ~KMEM_SLAB_NOMOVE;
4185 			sp->slab_stuck_offset = (uint32_t)-1;
4186 			avl_add(&cp->cache_partial_slabs, sp);
4187 		}
4188 	} else {
4189 		sp->slab_later_count = 0;
4190 		sp->slab_stuck_offset = (uint32_t)-1;
4191 	}
4192 }
4193 
4194 static void
4195 kmem_slab_move_no(kmem_cache_t *cp, kmem_slab_t *sp, void *from_buf)
4196 {
4197 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4198 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4199 	ASSERT(KMEM_SLAB_MEMBER(sp, from_buf));
4200 
4201 	if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4202 		return;
4203 	}
4204 
4205 	avl_remove(&cp->cache_partial_slabs, sp);
4206 	sp->slab_later_count = 0;
4207 	sp->slab_flags |= KMEM_SLAB_NOMOVE;
4208 	sp->slab_stuck_offset = KMEM_SLAB_OFFSET(sp, from_buf);
4209 	avl_add(&cp->cache_partial_slabs, sp);
4210 }
4211 
4212 static void kmem_move_end(kmem_cache_t *, kmem_move_t *);
4213 
4214 /*
4215  * The move callback takes two buffer addresses, the buffer to be moved, and a
4216  * newly allocated and constructed buffer selected by kmem as the destination.
4217  * It also takes the size of the buffer and an optional user argument specified
4218  * at cache creation time. kmem guarantees that the buffer to be moved has not
4219  * been unmapped by the virtual memory subsystem. Beyond that, it cannot
4220  * guarantee the present whereabouts of the buffer to be moved, so it is up to
4221  * the client to safely determine whether or not it is still using the buffer.
4222  * The client must not free either of the buffers passed to the move callback,
4223  * since kmem wants to free them directly to the slab layer. The client response
4224  * tells kmem which of the two buffers to free:
4225  *
4226  * YES		kmem frees the old buffer (the move was successful)
4227  * NO		kmem frees the new buffer, marks the slab of the old buffer
4228  *              non-reclaimable to avoid bothering the client again
4229  * LATER	kmem frees the new buffer, increments slab_later_count
4230  * DONT_KNOW	kmem frees the new buffer, searches mags for the old buffer
4231  * DONT_NEED	kmem frees both the old buffer and the new buffer
4232  *
4233  * The pending callback argument now being processed contains both of the
4234  * buffers (old and new) passed to the move callback function, the slab of the
4235  * old buffer, and flags related to the move request, such as whether or not the
4236  * system was desperate for memory.
4237  */
4238 static void
4239 kmem_move_buffer(kmem_move_t *callback)
4240 {
4241 	kmem_cbrc_t response;
4242 	kmem_slab_t *sp = callback->kmm_from_slab;
4243 	kmem_cache_t *cp = sp->slab_cache;
4244 	boolean_t free_on_slab;
4245 
4246 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4247 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4248 	ASSERT(KMEM_SLAB_MEMBER(sp, callback->kmm_from_buf));
4249 
4250 	/*
4251 	 * The number of allocated buffers on the slab may have changed since we
4252 	 * last checked the slab's reclaimability (when the pending move was
4253 	 * enqueued), or the client may have responded NO when asked to move
4254 	 * another buffer on the same slab.
4255 	 */
4256 	if (!kmem_slab_is_reclaimable(cp, sp, callback->kmm_flags)) {
4257 		KMEM_STAT_ADD(kmem_move_stats.kms_no_longer_reclaimable);
4258 		KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY),
4259 		    kmem_move_stats.kms_notify_no_longer_reclaimable);
4260 		kmem_slab_free(cp, callback->kmm_to_buf);
4261 		kmem_move_end(cp, callback);
4262 		return;
4263 	}
4264 
4265 	/*
4266 	 * Hunting magazines is expensive, so we'll wait to do that until the
4267 	 * client responds KMEM_CBRC_DONT_KNOW. However, checking the slab layer
4268 	 * is cheap, so we might as well do that here in case we can avoid
4269 	 * bothering the client.
4270 	 */
4271 	mutex_enter(&cp->cache_lock);
4272 	free_on_slab = (kmem_slab_allocated(cp, sp,
4273 	    callback->kmm_from_buf) == NULL);
4274 	mutex_exit(&cp->cache_lock);
4275 
4276 	if (free_on_slab) {
4277 		KMEM_STAT_ADD(kmem_move_stats.kms_hunt_found_slab);
4278 		kmem_slab_free(cp, callback->kmm_to_buf);
4279 		kmem_move_end(cp, callback);
4280 		return;
4281 	}
4282 
4283 	if (cp->cache_flags & KMF_BUFTAG) {
4284 		/*
4285 		 * Make kmem_cache_alloc_debug() apply the constructor for us.
4286 		 */
4287 		if (kmem_cache_alloc_debug(cp, callback->kmm_to_buf,
4288 		    KM_NOSLEEP, 1, caller()) != 0) {
4289 			KMEM_STAT_ADD(kmem_move_stats.kms_alloc_fail);
4290 			kmem_move_end(cp, callback);
4291 			return;
4292 		}
4293 	} else if (cp->cache_constructor != NULL &&
4294 	    cp->cache_constructor(callback->kmm_to_buf, cp->cache_private,
4295 	    KM_NOSLEEP) != 0) {
4296 		atomic_add_64(&cp->cache_alloc_fail, 1);
4297 		KMEM_STAT_ADD(kmem_move_stats.kms_constructor_fail);
4298 		kmem_slab_free(cp, callback->kmm_to_buf);
4299 		kmem_move_end(cp, callback);
4300 		return;
4301 	}
4302 
4303 	KMEM_STAT_ADD(kmem_move_stats.kms_callbacks);
4304 	KMEM_STAT_COND_ADD((callback->kmm_flags & KMM_NOTIFY),
4305 	    kmem_move_stats.kms_notify_callbacks);
4306 	cp->cache_defrag->kmd_callbacks++;
4307 	cp->cache_defrag->kmd_thread = curthread;
4308 	cp->cache_defrag->kmd_from_buf = callback->kmm_from_buf;
4309 	cp->cache_defrag->kmd_to_buf = callback->kmm_to_buf;
4310 	DTRACE_PROBE2(kmem__move__start, kmem_cache_t *, cp, kmem_move_t *,
4311 	    callback);
4312 
4313 	response = cp->cache_move(callback->kmm_from_buf,
4314 	    callback->kmm_to_buf, cp->cache_bufsize, cp->cache_private);
4315 
4316 	DTRACE_PROBE3(kmem__move__end, kmem_cache_t *, cp, kmem_move_t *,
4317 	    callback, kmem_cbrc_t, response);
4318 	cp->cache_defrag->kmd_thread = NULL;
4319 	cp->cache_defrag->kmd_from_buf = NULL;
4320 	cp->cache_defrag->kmd_to_buf = NULL;
4321 
4322 	if (response == KMEM_CBRC_YES) {
4323 		KMEM_STAT_ADD(kmem_move_stats.kms_yes);
4324 		cp->cache_defrag->kmd_yes++;
4325 		kmem_slab_free_constructed(cp, callback->kmm_from_buf, B_FALSE);
4326 		mutex_enter(&cp->cache_lock);
4327 		kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4328 		mutex_exit(&cp->cache_lock);
4329 		kmem_move_end(cp, callback);
4330 		return;
4331 	}
4332 
4333 	switch (response) {
4334 	case KMEM_CBRC_NO:
4335 		KMEM_STAT_ADD(kmem_move_stats.kms_no);
4336 		cp->cache_defrag->kmd_no++;
4337 		mutex_enter(&cp->cache_lock);
4338 		kmem_slab_move_no(cp, sp, callback->kmm_from_buf);
4339 		mutex_exit(&cp->cache_lock);
4340 		break;
4341 	case KMEM_CBRC_LATER:
4342 		KMEM_STAT_ADD(kmem_move_stats.kms_later);
4343 		cp->cache_defrag->kmd_later++;
4344 		mutex_enter(&cp->cache_lock);
4345 		if (!KMEM_SLAB_IS_PARTIAL(sp)) {
4346 			mutex_exit(&cp->cache_lock);
4347 			break;
4348 		}
4349 
4350 		if (++sp->slab_later_count >= KMEM_DISBELIEF) {
4351 			KMEM_STAT_ADD(kmem_move_stats.kms_disbelief);
4352 			kmem_slab_move_no(cp, sp, callback->kmm_from_buf);
4353 		} else if (!(sp->slab_flags & KMEM_SLAB_NOMOVE)) {
4354 			sp->slab_stuck_offset = KMEM_SLAB_OFFSET(sp,
4355 			    callback->kmm_from_buf);
4356 		}
4357 		mutex_exit(&cp->cache_lock);
4358 		break;
4359 	case KMEM_CBRC_DONT_NEED:
4360 		KMEM_STAT_ADD(kmem_move_stats.kms_dont_need);
4361 		cp->cache_defrag->kmd_dont_need++;
4362 		kmem_slab_free_constructed(cp, callback->kmm_from_buf, B_FALSE);
4363 		mutex_enter(&cp->cache_lock);
4364 		kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4365 		mutex_exit(&cp->cache_lock);
4366 		break;
4367 	case KMEM_CBRC_DONT_KNOW:
4368 		KMEM_STAT_ADD(kmem_move_stats.kms_dont_know);
4369 		cp->cache_defrag->kmd_dont_know++;
4370 		if (kmem_hunt_mags(cp, callback->kmm_from_buf) != NULL) {
4371 			KMEM_STAT_ADD(kmem_move_stats.kms_hunt_found_mag);
4372 			cp->cache_defrag->kmd_hunt_found++;
4373 			kmem_slab_free_constructed(cp, callback->kmm_from_buf,
4374 			    B_TRUE);
4375 			mutex_enter(&cp->cache_lock);
4376 			kmem_slab_move_yes(cp, sp, callback->kmm_from_buf);
4377 			mutex_exit(&cp->cache_lock);
4378 		}
4379 		break;
4380 	default:
4381 		panic("'%s' (%p) unexpected move callback response %d\n",
4382 		    cp->cache_name, (void *)cp, response);
4383 	}
4384 
4385 	kmem_slab_free_constructed(cp, callback->kmm_to_buf, B_FALSE);
4386 	kmem_move_end(cp, callback);
4387 }
4388 
4389 /* Return B_FALSE if there is insufficient memory for the move request. */
4390 static boolean_t
4391 kmem_move_begin(kmem_cache_t *cp, kmem_slab_t *sp, void *buf, int flags)
4392 {
4393 	void *to_buf;
4394 	avl_index_t index;
4395 	kmem_move_t *callback, *pending;
4396 
4397 	ASSERT(taskq_member(kmem_taskq, curthread));
4398 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4399 	ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4400 
4401 	callback = kmem_cache_alloc(kmem_move_cache, KM_NOSLEEP);
4402 	if (callback == NULL) {
4403 		KMEM_STAT_ADD(kmem_move_stats.kms_callback_alloc_fail);
4404 		return (B_FALSE);
4405 	}
4406 
4407 	callback->kmm_from_slab = sp;
4408 	callback->kmm_from_buf = buf;
4409 	callback->kmm_flags = flags;
4410 
4411 	mutex_enter(&cp->cache_lock);
4412 
4413 	if (avl_numnodes(&cp->cache_partial_slabs) <= 1) {
4414 		mutex_exit(&cp->cache_lock);
4415 		kmem_cache_free(kmem_move_cache, callback);
4416 		return (B_TRUE); /* there is no need for the move request */
4417 	}
4418 
4419 	pending = avl_find(&cp->cache_defrag->kmd_moves_pending, buf, &index);
4420 	if (pending != NULL) {
4421 		/*
4422 		 * If the move is already pending and we're desperate now,
4423 		 * update the move flags.
4424 		 */
4425 		if (flags & KMM_DESPERATE) {
4426 			pending->kmm_flags |= KMM_DESPERATE;
4427 		}
4428 		mutex_exit(&cp->cache_lock);
4429 		KMEM_STAT_ADD(kmem_move_stats.kms_already_pending);
4430 		kmem_cache_free(kmem_move_cache, callback);
4431 		return (B_TRUE);
4432 	}
4433 
4434 	to_buf = kmem_slab_alloc_impl(cp, avl_first(&cp->cache_partial_slabs));
4435 	callback->kmm_to_buf = to_buf;
4436 	avl_insert(&cp->cache_defrag->kmd_moves_pending, callback, index);
4437 
4438 	mutex_exit(&cp->cache_lock);
4439 
4440 	if (!taskq_dispatch(kmem_move_taskq, (task_func_t *)kmem_move_buffer,
4441 	    callback, TQ_NOSLEEP)) {
4442 		KMEM_STAT_ADD(kmem_move_stats.kms_callback_taskq_fail);
4443 		mutex_enter(&cp->cache_lock);
4444 		avl_remove(&cp->cache_defrag->kmd_moves_pending, callback);
4445 		mutex_exit(&cp->cache_lock);
4446 		kmem_slab_free(cp, to_buf);
4447 		kmem_cache_free(kmem_move_cache, callback);
4448 		return (B_FALSE);
4449 	}
4450 
4451 	return (B_TRUE);
4452 }
4453 
4454 static void
4455 kmem_move_end(kmem_cache_t *cp, kmem_move_t *callback)
4456 {
4457 	avl_index_t index;
4458 
4459 	ASSERT(cp->cache_defrag != NULL);
4460 	ASSERT(taskq_member(kmem_move_taskq, curthread));
4461 	ASSERT(MUTEX_NOT_HELD(&cp->cache_lock));
4462 
4463 	mutex_enter(&cp->cache_lock);
4464 	VERIFY(avl_find(&cp->cache_defrag->kmd_moves_pending,
4465 	    callback->kmm_from_buf, &index) != NULL);
4466 	avl_remove(&cp->cache_defrag->kmd_moves_pending, callback);
4467 	if (avl_is_empty(&cp->cache_defrag->kmd_moves_pending)) {
4468 		list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
4469 		kmem_slab_t *sp;
4470 
4471 		/*
4472 		 * The last pending move completed. Release all slabs from the
4473 		 * front of the dead list except for any slab at the tail that
4474 		 * needs to be released from the context of kmem_move_buffers().
4475 		 * kmem deferred unmapping the buffers on these slabs in order
4476 		 * to guarantee that buffers passed to the move callback have
4477 		 * been touched only by kmem or by the client itself.
4478 		 */
4479 		while ((sp = list_remove_head(deadlist)) != NULL) {
4480 			if (sp->slab_flags & KMEM_SLAB_MOVE_PENDING) {
4481 				list_insert_tail(deadlist, sp);
4482 				break;
4483 			}
4484 			cp->cache_defrag->kmd_deadcount--;
4485 			cp->cache_slab_destroy++;
4486 			mutex_exit(&cp->cache_lock);
4487 			kmem_slab_destroy(cp, sp);
4488 			KMEM_STAT_ADD(kmem_move_stats.kms_dead_slabs_freed);
4489 			mutex_enter(&cp->cache_lock);
4490 		}
4491 	}
4492 	mutex_exit(&cp->cache_lock);
4493 	kmem_cache_free(kmem_move_cache, callback);
4494 }
4495 
4496 /*
4497  * Move buffers from least used slabs first by scanning backwards from the end
4498  * of the partial slab list. Scan at most max_scan candidate slabs and move
4499  * buffers from at most max_slabs slabs (0 for all partial slabs in both cases).
4500  * If desperate to reclaim memory, move buffers from any partial slab, otherwise
4501  * skip slabs with a ratio of allocated buffers at or above the current
4502  * threshold. Return the number of unskipped slabs (at most max_slabs, -1 if the
4503  * scan is aborted) so that the caller can adjust the reclaimability threshold
4504  * depending on how many reclaimable slabs it finds.
4505  *
4506  * kmem_move_buffers() drops and reacquires cache_lock every time it issues a
4507  * move request, since it is not valid for kmem_move_begin() to call
4508  * kmem_cache_alloc() or taskq_dispatch() with cache_lock held.
4509  */
4510 static int
4511 kmem_move_buffers(kmem_cache_t *cp, size_t max_scan, size_t max_slabs,
4512     int flags)
4513 {
4514 	kmem_slab_t *sp;
4515 	void *buf;
4516 	int i, j; /* slab index, buffer index */
4517 	int s; /* reclaimable slabs */
4518 	int b; /* allocated (movable) buffers on reclaimable slab */
4519 	boolean_t success;
4520 	int refcnt;
4521 	int nomove;
4522 
4523 	ASSERT(taskq_member(kmem_taskq, curthread));
4524 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4525 	ASSERT(kmem_move_cache != NULL);
4526 	ASSERT(cp->cache_move != NULL && cp->cache_defrag != NULL);
4527 	ASSERT(avl_numnodes(&cp->cache_partial_slabs) > 1);
4528 
4529 	if (kmem_move_blocked) {
4530 		return (0);
4531 	}
4532 
4533 	if (kmem_move_fulltilt) {
4534 		max_slabs = 0;
4535 		flags |= KMM_DESPERATE;
4536 	}
4537 
4538 	if (max_scan == 0 || (flags & KMM_DESPERATE)) {
4539 		/*
4540 		 * Scan as many slabs as needed to find the desired number of
4541 		 * candidate slabs.
4542 		 */
4543 		max_scan = (size_t)-1;
4544 	}
4545 
4546 	if (max_slabs == 0 || (flags & KMM_DESPERATE)) {
4547 		/* Find as many candidate slabs as possible. */
4548 		max_slabs = (size_t)-1;
4549 	}
4550 
4551 	sp = avl_last(&cp->cache_partial_slabs);
4552 	ASSERT(sp != NULL && KMEM_SLAB_IS_PARTIAL(sp));
4553 	for (i = 0, s = 0; (i < max_scan) && (s < max_slabs) &&
4554 	    (sp != avl_first(&cp->cache_partial_slabs));
4555 	    sp = AVL_PREV(&cp->cache_partial_slabs, sp), i++) {
4556 
4557 		if (!kmem_slab_is_reclaimable(cp, sp, flags)) {
4558 			continue;
4559 		}
4560 		s++;
4561 
4562 		/* Look for allocated buffers to move. */
4563 		for (j = 0, b = 0, buf = sp->slab_base;
4564 		    (j < sp->slab_chunks) && (b < sp->slab_refcnt);
4565 		    buf = (((char *)buf) + cp->cache_chunksize), j++) {
4566 
4567 			if (kmem_slab_allocated(cp, sp, buf) == NULL) {
4568 				continue;
4569 			}
4570 
4571 			b++;
4572 
4573 			/*
4574 			 * Prevent the slab from being destroyed while we drop
4575 			 * cache_lock and while the pending move is not yet
4576 			 * registered. Flag the pending move while
4577 			 * kmd_moves_pending may still be empty, since we can't
4578 			 * yet rely on a non-zero pending move count to prevent
4579 			 * the slab from being destroyed.
4580 			 */
4581 			ASSERT(!(sp->slab_flags & KMEM_SLAB_MOVE_PENDING));
4582 			sp->slab_flags |= KMEM_SLAB_MOVE_PENDING;
4583 			/*
4584 			 * Recheck refcnt and nomove after reacquiring the lock,
4585 			 * since these control the order of partial slabs, and
4586 			 * we want to know if we can pick up the scan where we
4587 			 * left off.
4588 			 */
4589 			refcnt = sp->slab_refcnt;
4590 			nomove = (sp->slab_flags & KMEM_SLAB_NOMOVE);
4591 			mutex_exit(&cp->cache_lock);
4592 
4593 			success = kmem_move_begin(cp, sp, buf, flags);
4594 
4595 			/*
4596 			 * Now, before the lock is reacquired, kmem could
4597 			 * process all pending move requests and purge the
4598 			 * deadlist, so that upon reacquiring the lock, sp has
4599 			 * been remapped. Therefore, the KMEM_SLAB_MOVE_PENDING
4600 			 * flag causes the slab to be put at the end of the
4601 			 * deadlist and prevents it from being purged, since we
4602 			 * plan to destroy it here after reacquiring the lock.
4603 			 */
4604 			mutex_enter(&cp->cache_lock);
4605 			ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4606 			sp->slab_flags &= ~KMEM_SLAB_MOVE_PENDING;
4607 
4608 			/*
4609 			 * Destroy the slab now if it was completely freed while
4610 			 * we dropped cache_lock.
4611 			 */
4612 			if (sp->slab_refcnt == 0) {
4613 				list_t *deadlist =
4614 				    &cp->cache_defrag->kmd_deadlist;
4615 
4616 				ASSERT(!list_is_empty(deadlist));
4617 				ASSERT(list_link_active((list_node_t *)
4618 				    &sp->slab_link));
4619 
4620 				list_remove(deadlist, sp);
4621 				cp->cache_defrag->kmd_deadcount--;
4622 				cp->cache_slab_destroy++;
4623 				mutex_exit(&cp->cache_lock);
4624 				kmem_slab_destroy(cp, sp);
4625 				KMEM_STAT_ADD(kmem_move_stats.
4626 				    kms_dead_slabs_freed);
4627 				KMEM_STAT_ADD(kmem_move_stats.
4628 				    kms_endscan_slab_destroyed);
4629 				mutex_enter(&cp->cache_lock);
4630 				/*
4631 				 * Since we can't pick up the scan where we left
4632 				 * off, abort the scan and say nothing about the
4633 				 * number of reclaimable slabs.
4634 				 */
4635 				return (-1);
4636 			}
4637 
4638 			if (!success) {
4639 				/*
4640 				 * Abort the scan if there is not enough memory
4641 				 * for the request and say nothing about the
4642 				 * number of reclaimable slabs.
4643 				 */
4644 				KMEM_STAT_ADD(
4645 				    kmem_move_stats.kms_endscan_nomem);
4646 				return (-1);
4647 			}
4648 
4649 			/*
4650 			 * The slab may have been completely allocated while the
4651 			 * lock was dropped.
4652 			 */
4653 			if (KMEM_SLAB_IS_ALL_USED(sp)) {
4654 				KMEM_STAT_ADD(
4655 				    kmem_move_stats.kms_endscan_slab_all_used);
4656 				return (-1);
4657 			}
4658 
4659 			/*
4660 			 * The slab's position changed while the lock was
4661 			 * dropped, so we don't know where we are in the
4662 			 * sequence any more.
4663 			 */
4664 			if (sp->slab_refcnt != refcnt) {
4665 				KMEM_STAT_ADD(
4666 				    kmem_move_stats.kms_endscan_refcnt_changed);
4667 				return (-1);
4668 			}
4669 			if ((sp->slab_flags & KMEM_SLAB_NOMOVE) != nomove) {
4670 				KMEM_STAT_ADD(
4671 				    kmem_move_stats.kms_endscan_nomove_changed);
4672 				return (-1);
4673 			}
4674 
4675 			/*
4676 			 * Generating a move request allocates a destination
4677 			 * buffer from the slab layer, bumping the first slab if
4678 			 * it is completely allocated.
4679 			 */
4680 			ASSERT(!avl_is_empty(&cp->cache_partial_slabs));
4681 			if (sp == avl_first(&cp->cache_partial_slabs)) {
4682 				goto end_scan;
4683 			}
4684 		}
4685 	}
4686 end_scan:
4687 
4688 	KMEM_STAT_COND_ADD(sp == avl_first(&cp->cache_partial_slabs),
4689 	    kmem_move_stats.kms_endscan_freelist);
4690 
4691 	return (s);
4692 }
4693 
4694 typedef struct kmem_move_notify_args {
4695 	kmem_cache_t *kmna_cache;
4696 	void *kmna_buf;
4697 } kmem_move_notify_args_t;
4698 
4699 static void
4700 kmem_cache_move_notify_task(void *arg)
4701 {
4702 	kmem_move_notify_args_t *args = arg;
4703 	kmem_cache_t *cp = args->kmna_cache;
4704 	void *buf = args->kmna_buf;
4705 	kmem_slab_t *sp;
4706 
4707 	ASSERT(taskq_member(kmem_taskq, curthread));
4708 	ASSERT(list_link_active(&cp->cache_link));
4709 
4710 	kmem_free(args, sizeof (kmem_move_notify_args_t));
4711 	mutex_enter(&cp->cache_lock);
4712 	sp = kmem_slab_allocated(cp, NULL, buf);
4713 
4714 	/* Ignore the notification if the buffer is no longer allocated. */
4715 	if (sp == NULL) {
4716 		mutex_exit(&cp->cache_lock);
4717 		return;
4718 	}
4719 
4720 	/* Ignore the notification if there's no reason to move the buffer. */
4721 	if (avl_numnodes(&cp->cache_partial_slabs) > 1) {
4722 		/*
4723 		 * So far the notification is not ignored. Ignore the
4724 		 * notification if the slab is not marked by an earlier refusal
4725 		 * to move a buffer.
4726 		 */
4727 		if (!(sp->slab_flags & KMEM_SLAB_NOMOVE) &&
4728 		    (sp->slab_later_count == 0)) {
4729 			mutex_exit(&cp->cache_lock);
4730 			return;
4731 		}
4732 
4733 		kmem_slab_move_yes(cp, sp, buf);
4734 		ASSERT(!(sp->slab_flags & KMEM_SLAB_MOVE_PENDING));
4735 		sp->slab_flags |= KMEM_SLAB_MOVE_PENDING;
4736 		mutex_exit(&cp->cache_lock);
4737 		/* see kmem_move_buffers() about dropping the lock */
4738 		(void) kmem_move_begin(cp, sp, buf, KMM_NOTIFY);
4739 		mutex_enter(&cp->cache_lock);
4740 		ASSERT(sp->slab_flags & KMEM_SLAB_MOVE_PENDING);
4741 		sp->slab_flags &= ~KMEM_SLAB_MOVE_PENDING;
4742 		if (sp->slab_refcnt == 0) {
4743 			list_t *deadlist = &cp->cache_defrag->kmd_deadlist;
4744 
4745 			ASSERT(!list_is_empty(deadlist));
4746 			ASSERT(list_link_active((list_node_t *)
4747 			    &sp->slab_link));
4748 
4749 			list_remove(deadlist, sp);
4750 			cp->cache_defrag->kmd_deadcount--;
4751 			cp->cache_slab_destroy++;
4752 			mutex_exit(&cp->cache_lock);
4753 			kmem_slab_destroy(cp, sp);
4754 			KMEM_STAT_ADD(kmem_move_stats.kms_dead_slabs_freed);
4755 			return;
4756 		}
4757 	} else {
4758 		kmem_slab_move_yes(cp, sp, buf);
4759 	}
4760 	mutex_exit(&cp->cache_lock);
4761 }
4762 
4763 void
4764 kmem_cache_move_notify(kmem_cache_t *cp, void *buf)
4765 {
4766 	kmem_move_notify_args_t *args;
4767 
4768 	KMEM_STAT_ADD(kmem_move_stats.kms_notify);
4769 	args = kmem_alloc(sizeof (kmem_move_notify_args_t), KM_NOSLEEP);
4770 	if (args != NULL) {
4771 		args->kmna_cache = cp;
4772 		args->kmna_buf = buf;
4773 		if (!taskq_dispatch(kmem_taskq,
4774 		    (task_func_t *)kmem_cache_move_notify_task, args,
4775 		    TQ_NOSLEEP))
4776 			kmem_free(args, sizeof (kmem_move_notify_args_t));
4777 	}
4778 }
4779 
4780 static void
4781 kmem_cache_defrag(kmem_cache_t *cp)
4782 {
4783 	size_t n;
4784 
4785 	ASSERT(cp->cache_defrag != NULL);
4786 
4787 	mutex_enter(&cp->cache_lock);
4788 	n = avl_numnodes(&cp->cache_partial_slabs);
4789 	if (n > 1) {
4790 		/* kmem_move_buffers() drops and reacquires cache_lock */
4791 		(void) kmem_move_buffers(cp, n, 0, KMM_DESPERATE);
4792 		KMEM_STAT_ADD(kmem_move_stats.kms_defrags);
4793 	}
4794 	mutex_exit(&cp->cache_lock);
4795 }
4796 
4797 /* Is this cache above the fragmentation threshold? */
4798 static boolean_t
4799 kmem_cache_frag_threshold(kmem_cache_t *cp, uint64_t nfree)
4800 {
4801 	if (avl_numnodes(&cp->cache_partial_slabs) <= 1)
4802 		return (B_FALSE);
4803 
4804 	/*
4805 	 *	nfree		kmem_frag_numer
4806 	 * ------------------ > ---------------
4807 	 * cp->cache_buftotal	kmem_frag_denom
4808 	 */
4809 	return ((nfree * kmem_frag_denom) >
4810 	    (cp->cache_buftotal * kmem_frag_numer));
4811 }
4812 
4813 static boolean_t
4814 kmem_cache_is_fragmented(kmem_cache_t *cp, boolean_t *doreap)
4815 {
4816 	boolean_t fragmented;
4817 	uint64_t nfree;
4818 
4819 	ASSERT(MUTEX_HELD(&cp->cache_lock));
4820 	*doreap = B_FALSE;
4821 
4822 	if (!kmem_move_fulltilt && ((cp->cache_complete_slab_count +
4823 	    avl_numnodes(&cp->cache_partial_slabs)) < kmem_frag_minslabs))
4824 		return (B_FALSE);
4825 
4826 	nfree = cp->cache_bufslab;
4827 	fragmented = kmem_cache_frag_threshold(cp, nfree);
4828 	/*
4829 	 * Free buffers in the magazine layer appear allocated from the point of
4830 	 * view of the slab layer. We want to know if the slab layer would
4831 	 * appear fragmented if we included free buffers from magazines that
4832 	 * have fallen out of the working set.
4833 	 */
4834 	if (!fragmented) {
4835 		long reap;
4836 
4837 		mutex_enter(&cp->cache_depot_lock);
4838 		reap = MIN(cp->cache_full.ml_reaplimit, cp->cache_full.ml_min);
4839 		reap = MIN(reap, cp->cache_full.ml_total);
4840 		mutex_exit(&cp->cache_depot_lock);
4841 
4842 		nfree += ((uint64_t)reap * cp->cache_magtype->mt_magsize);
4843 		if (kmem_cache_frag_threshold(cp, nfree)) {
4844 			*doreap = B_TRUE;
4845 		}
4846 	}
4847 
4848 	return (fragmented);
4849 }
4850 
4851 /* Called periodically from kmem_taskq */
4852 static void
4853 kmem_cache_scan(kmem_cache_t *cp)
4854 {
4855 	boolean_t reap = B_FALSE;
4856 
4857 	ASSERT(taskq_member(kmem_taskq, curthread));
4858 	ASSERT(cp->cache_defrag != NULL);
4859 
4860 	mutex_enter(&cp->cache_lock);
4861 
4862 	if (kmem_cache_is_fragmented(cp, &reap)) {
4863 		kmem_defrag_t *kmd = cp->cache_defrag;
4864 		size_t slabs_found;
4865 
4866 		/*
4867 		 * Consolidate reclaimable slabs from the end of the partial
4868 		 * slab list (scan at most kmem_reclaim_scan_range slabs to find
4869 		 * reclaimable slabs). Keep track of how many candidate slabs we
4870 		 * looked for and how many we actually found so we can adjust
4871 		 * the definition of a candidate slab if we're having trouble
4872 		 * finding them.
4873 		 *
4874 		 * kmem_move_buffers() drops and reacquires cache_lock.
4875 		 */
4876 		slabs_found = kmem_move_buffers(cp, kmem_reclaim_scan_range,
4877 		    kmem_reclaim_max_slabs, 0);
4878 		if (slabs_found >= 0) {
4879 			kmd->kmd_slabs_sought += kmem_reclaim_max_slabs;
4880 			kmd->kmd_slabs_found += slabs_found;
4881 		}
4882 
4883 		if (++kmd->kmd_scans >= kmem_reclaim_scan_range) {
4884 			kmd->kmd_scans = 0;
4885 
4886 			/*
4887 			 * If we had difficulty finding candidate slabs in
4888 			 * previous scans, adjust the threshold so that
4889 			 * candidates are easier to find.
4890 			 */
4891 			if (kmd->kmd_slabs_found == kmd->kmd_slabs_sought) {
4892 				kmem_adjust_reclaim_threshold(kmd, -1);
4893 			} else if ((kmd->kmd_slabs_found * 2) <
4894 			    kmd->kmd_slabs_sought) {
4895 				kmem_adjust_reclaim_threshold(kmd, 1);
4896 			}
4897 			kmd->kmd_slabs_sought = 0;
4898 			kmd->kmd_slabs_found = 0;
4899 		}
4900 	} else {
4901 		kmem_reset_reclaim_threshold(cp->cache_defrag);
4902 #ifdef	DEBUG
4903 		if (avl_numnodes(&cp->cache_partial_slabs) > 1) {
4904 			/*
4905 			 * In a debug kernel we want the consolidator to
4906 			 * run occasionally even when there is plenty of
4907 			 * memory.
4908 			 */
4909 			uint32_t debug_rand;
4910 
4911 			(void) random_get_bytes((uint8_t *)&debug_rand, 4);
4912 			if (!kmem_move_noreap &&
4913 			    ((debug_rand % kmem_mtb_reap) == 0)) {
4914 				mutex_exit(&cp->cache_lock);
4915 				kmem_cache_reap(cp);
4916 				KMEM_STAT_ADD(kmem_move_stats.kms_debug_reaps);
4917 				return;
4918 			} else if ((debug_rand % kmem_mtb_move) == 0) {
4919 				(void) kmem_move_buffers(cp,
4920 				    kmem_reclaim_scan_range, 1, 0);
4921 				KMEM_STAT_ADD(kmem_move_stats.
4922 				    kms_debug_move_scans);
4923 			}
4924 		}
4925 #endif	/* DEBUG */
4926 	}
4927 
4928 	mutex_exit(&cp->cache_lock);
4929 
4930 	if (reap) {
4931 		KMEM_STAT_ADD(kmem_move_stats.kms_scan_depot_ws_reaps);
4932 		kmem_depot_ws_reap(cp);
4933 	}
4934 }
4935