objcache: objcache_create on longer changes cluster_limit
[dragonfly.git] / sys / kern / kern_objcache.c
1 /*
2  * Copyright (c) 2005 Jeffrey M. Hsu.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $DragonFly: src/sys/kern/kern_objcache.c,v 1.23 2008/10/26 04:29:19 sephe Exp $
33  */
34
35 #include <sys/param.h>
36 #include <sys/kernel.h>
37 #include <sys/systm.h>
38 #include <sys/callout.h>
39 #include <sys/globaldata.h>
40 #include <sys/malloc.h>
41 #include <sys/queue.h>
42 #include <sys/objcache.h>
43 #include <sys/spinlock.h>
44 #include <sys/thread.h>
45 #include <sys/thread2.h>
46 #include <sys/spinlock2.h>
47
48 static MALLOC_DEFINE(M_OBJCACHE, "objcache", "Object Cache");
49 static MALLOC_DEFINE(M_OBJMAG, "objcache magazine", "Object Cache Magazine");
50
51 #define INITIAL_MAG_CAPACITY    64
52
53 struct magazine {
54         int                      rounds;
55         int                      capacity;
56         SLIST_ENTRY(magazine)    nextmagazine;
57         void                    *objects[];
58 };
59
60 SLIST_HEAD(magazinelist, magazine);
61
62 /*
63  * per-cluster cache of magazines
64  *
65  * All fields in this structure are protected by the spinlock.
66  */
67 struct magazinedepot {
68         /*
69          * The per-cpu object caches only exchanges completely full or
70          * completely empty magazines with the depot layer, so only have
71          * to cache these two types of magazines.
72          */
73         struct magazinelist     fullmagazines;
74         struct magazinelist     emptymagazines;
75         int                     magcapacity;
76
77         /* protect this structure */
78         struct spinlock         spin;
79
80         /* magazines not yet allocated towards limit */
81         int                     unallocated_objects;
82
83         /* infrequently used fields */
84         int                     waiting;        /* waiting for another cpu to
85                                                  * return a full magazine to
86                                                  * the depot */
87         int                     contested;      /* depot contention count */
88 } __cachealign;
89
90 /*
91  * per-cpu object cache
92  * All fields in this structure are protected by crit_enter().
93  */
94 struct percpu_objcache {
95         struct magazine *loaded_magazine;       /* active magazine */
96         struct magazine *previous_magazine;     /* backup magazine */
97
98         /* statistics */
99         int             gets_cumulative;        /* total calls to get */
100         int             gets_null;              /* objcache_get returned NULL */
101         int             puts_cumulative;        /* total calls to put */
102         int             puts_othercluster;      /* returned to other cluster */
103
104         /* infrequently used fields */
105         int             waiting;        /* waiting for a thread on this cpu to
106                                          * return an obj to the per-cpu cache */
107 } __cachealign;
108
109 /* only until we have NUMA cluster topology information XXX */
110 #define MAXCLUSTERS 1
111 #define myclusterid 0
112 #define CLUSTER_OF(obj) 0
113
114 /*
115  * Two-level object cache consisting of NUMA cluster-level depots of
116  * fully loaded or completely empty magazines and cpu-level caches of
117  * individual objects.
118  */
119 struct objcache {
120         char                    *name;
121
122         /* object constructor and destructor from blank storage */
123         objcache_ctor_fn        *ctor;
124         objcache_dtor_fn        *dtor;
125         void                    *privdata;
126
127         /* interface to underlying allocator */
128         objcache_alloc_fn       *alloc;
129         objcache_free_fn        *free;
130         void                    *allocator_args;
131
132         LIST_ENTRY(objcache)    oc_next;
133         int                     exhausted;      /* oops */
134
135         /* NUMA-cluster level caches */
136         struct magazinedepot    depot[MAXCLUSTERS];
137
138         struct percpu_objcache  cache_percpu[];         /* per-cpu caches */
139 };
140
141 static struct spinlock objcachelist_spin;
142 static LIST_HEAD(objcachelist, objcache) allobjcaches;
143
144 static struct magazine *
145 mag_alloc(int capacity)
146 {
147         struct magazine *mag;
148
149         mag = kmalloc(__offsetof(struct magazine, objects[capacity]),
150                         M_OBJMAG, M_INTWAIT | M_ZERO);
151         mag->capacity = capacity;
152         mag->rounds = 0;
153         return (mag);
154 }
155
156 /*
157  * Utility routine for objects that don't require any de-construction.
158  */
159
160 static void
161 null_dtor(void *obj, void *privdata)
162 {
163         /* do nothing */
164 }
165
166 static boolean_t
167 null_ctor(void *obj, void *privdata, int ocflags)
168 {
169         return TRUE;
170 }
171
172 /*
173  * Create an object cache.
174  */
175 struct objcache *
176 objcache_create(const char *name, int cluster_limit, int nom_cache,
177                 objcache_ctor_fn *ctor, objcache_dtor_fn *dtor, void *privdata,
178                 objcache_alloc_fn *alloc, objcache_free_fn *free,
179                 void *allocator_args)
180 {
181         struct objcache *oc;
182         struct magazinedepot *depot;
183         int cpuid;
184         int nmagdepot;
185         int mag_capacity;
186         int i;
187
188         /*
189          * Allocate object cache structure
190          */
191         oc = kmalloc(__offsetof(struct objcache, cache_percpu[ncpus]),
192                     M_OBJCACHE, M_WAITOK | M_ZERO);
193         oc->name = kstrdup(name, M_TEMP);
194         oc->ctor = ctor ? ctor : null_ctor;
195         oc->dtor = dtor ? dtor : null_dtor;
196         oc->privdata = privdata;
197         oc->alloc = alloc;
198         oc->free = free;
199         oc->allocator_args = allocator_args;
200
201         /*
202          * Initialize depot list(s).
203          */
204         depot = &oc->depot[0];
205
206         spin_init(&depot->spin);
207         SLIST_INIT(&depot->fullmagazines);
208         SLIST_INIT(&depot->emptymagazines);
209
210         /*
211          * Figure out the nominal number of free objects to cache and
212          * the magazine capacity.  By default we want to cache up to
213          * half the cluster_limit.  If there is no cluster_limit then
214          * we want to cache up to 128 objects.
215          */
216         if (nom_cache == 0)
217                 nom_cache = cluster_limit / 2;
218         if (cluster_limit && nom_cache > cluster_limit)
219                 nom_cache = cluster_limit;
220         if (nom_cache == 0)
221                 nom_cache = INITIAL_MAG_CAPACITY * 2;
222
223         /*
224          * Magazine capacity for 2 active magazines per cpu plus 2
225          * magazines in the depot.  Minimum capacity is 4 objects.
226          */
227         mag_capacity = nom_cache / (ncpus + 1) / 2 + 1;
228         if (mag_capacity > 128)
229                 mag_capacity = 128;
230         if (mag_capacity < 4)
231                 mag_capacity = 4;
232         depot->magcapacity = mag_capacity;
233
234         /*
235          * The cluster_limit must be sufficient to have two magazines per
236          * cpu plus at least two magazines in the depot.  However, because
237          * partial magazines can stay on the cpus what we really need here
238          * is to specify the number of extra magazines we allocate for the
239          * depot.
240          */
241         if (cluster_limit == 0) {
242                 depot->unallocated_objects = -1;
243         } else {
244                 depot->unallocated_objects = ncpus * mag_capacity * 2 +
245                                              cluster_limit;
246         }
247
248         /*
249          * Initialize per-cpu caches
250          */
251         for (cpuid = 0; cpuid < ncpus; cpuid++) {
252                 struct percpu_objcache *cache_percpu = &oc->cache_percpu[cpuid];
253
254                 cache_percpu->loaded_magazine = mag_alloc(mag_capacity);
255                 cache_percpu->previous_magazine = mag_alloc(mag_capacity);
256         }
257
258         /*
259          * Compute how many empty magazines to place in the depot.  This
260          * determines the retained cache size and is based on nom_cache.
261          *
262          * The actual cache size is larger because there are two magazines
263          * for each cpu as well but those can be in any fill state so we
264          * just can't count them.
265          *
266          * There is a minimum of two magazines in the depot.
267          */
268         nmagdepot = nom_cache / mag_capacity + 1;
269         if (nmagdepot < 2)
270                 nmagdepot = 2;
271         if (bootverbose) {
272                 kprintf("ndepotmags=%-3d x mag_cap=%-3d for %s\n",
273                         nmagdepot, mag_capacity, name);
274         }
275
276         /*
277          * Put empty magazines in depot
278          */
279         for (i = 0; i < nmagdepot; i++) {
280                 struct magazine *mag = mag_alloc(mag_capacity);
281                 SLIST_INSERT_HEAD(&depot->emptymagazines, mag, nextmagazine);
282         }
283
284         spin_lock(&objcachelist_spin);
285         LIST_INSERT_HEAD(&allobjcaches, oc, oc_next);
286         spin_unlock(&objcachelist_spin);
287
288         return (oc);
289 }
290
291 struct objcache *
292 objcache_create_simple(malloc_type_t mtype, size_t objsize)
293 {
294         struct objcache_malloc_args *margs;
295         struct objcache *oc;
296
297         margs = kmalloc(sizeof(*margs), M_OBJCACHE, M_WAITOK|M_ZERO);
298         margs->objsize = objsize;
299         margs->mtype = mtype;
300         oc = objcache_create(mtype->ks_shortdesc, 0, 0,
301                              NULL, NULL, NULL,
302                              objcache_malloc_alloc, objcache_malloc_free,
303                              margs);
304         return (oc);
305 }
306
307 struct objcache *
308 objcache_create_mbacked(malloc_type_t mtype, size_t objsize,
309                         int cluster_limit, int nom_cache,
310                         objcache_ctor_fn *ctor, objcache_dtor_fn *dtor,
311                         void *privdata)
312 {
313         struct objcache_malloc_args *margs;
314         struct objcache *oc;
315
316         margs = kmalloc(sizeof(*margs), M_OBJCACHE, M_WAITOK|M_ZERO);
317         margs->objsize = objsize;
318         margs->mtype = mtype;
319         oc = objcache_create(mtype->ks_shortdesc,
320                              cluster_limit, nom_cache,
321                              ctor, dtor, privdata,
322                              objcache_malloc_alloc, objcache_malloc_free,
323                              margs);
324         return(oc);
325 }
326
327
328 #define MAGAZINE_EMPTY(mag)     (mag->rounds == 0)
329 #define MAGAZINE_NOTEMPTY(mag)  (mag->rounds != 0)
330 #define MAGAZINE_FULL(mag)      (mag->rounds == mag->capacity)
331
332 #define swap(x, y)      ({ struct magazine *t = x; x = y; y = t; })
333
334 /*
335  * Get an object from the object cache.
336  *
337  * WARNING!  ocflags are only used when we have to go to the underlying
338  * allocator, so we cannot depend on flags such as M_ZERO.
339  */
340 void *
341 objcache_get(struct objcache *oc, int ocflags)
342 {
343         struct percpu_objcache *cpucache = &oc->cache_percpu[mycpuid];
344         struct magazine *loadedmag;
345         struct magazine *emptymag;
346         void *obj;
347         struct magazinedepot *depot;
348
349         KKASSERT((ocflags & M_ZERO) == 0);
350         crit_enter();
351         ++cpucache->gets_cumulative;
352
353 retry:
354         /*
355          * Loaded magazine has an object.  This is the hot path.
356          * It is lock-free and uses a critical section to block
357          * out interrupt handlers on the same processor.
358          */
359         loadedmag = cpucache->loaded_magazine;
360         if (MAGAZINE_NOTEMPTY(loadedmag)) {
361                 obj = loadedmag->objects[--loadedmag->rounds];
362                 crit_exit();
363                 return (obj);
364         }
365
366         /* Previous magazine has an object. */
367         if (MAGAZINE_NOTEMPTY(cpucache->previous_magazine)) {
368                 swap(cpucache->loaded_magazine, cpucache->previous_magazine);
369                 loadedmag = cpucache->loaded_magazine;
370                 obj = loadedmag->objects[--loadedmag->rounds];
371                 crit_exit();
372                 return (obj);
373         }
374
375         /*
376          * Both magazines empty.  Get a full magazine from the depot and
377          * move one of the empty ones to the depot.
378          *
379          * Obtain the depot spinlock.
380          *
381          * NOTE: Beyond this point, M_* flags are handled via oc->alloc()
382          */
383         depot = &oc->depot[myclusterid];
384         spin_lock(&depot->spin);
385
386         /*
387          * Recheck the cpucache after obtaining the depot spinlock.  This
388          * shouldn't be necessary now but don't take any chances.
389          */
390         if (MAGAZINE_NOTEMPTY(cpucache->loaded_magazine) ||
391             MAGAZINE_NOTEMPTY(cpucache->previous_magazine)
392         ) {
393                 spin_unlock(&depot->spin);
394                 goto retry;
395         }
396
397         /* Check if depot has a full magazine. */
398         if (!SLIST_EMPTY(&depot->fullmagazines)) {
399                 emptymag = cpucache->previous_magazine;
400                 cpucache->previous_magazine = cpucache->loaded_magazine;
401                 cpucache->loaded_magazine = SLIST_FIRST(&depot->fullmagazines);
402                 SLIST_REMOVE_HEAD(&depot->fullmagazines, nextmagazine);
403
404                 /*
405                  * Return emptymag to the depot.
406                  */
407                 KKASSERT(MAGAZINE_EMPTY(emptymag));
408                 SLIST_INSERT_HEAD(&depot->emptymagazines,
409                                   emptymag, nextmagazine);
410                 spin_unlock(&depot->spin);
411                 goto retry;
412         }
413
414         /*
415          * The depot does not have any non-empty magazines.  If we have
416          * not hit our object limit we can allocate a new object using
417          * the back-end allocator.
418          *
419          * note: unallocated_objects can be initialized to -1, which has
420          * the effect of removing any allocation limits.
421          */
422         if (depot->unallocated_objects) {
423                 --depot->unallocated_objects;
424                 spin_unlock(&depot->spin);
425                 crit_exit();
426
427                 obj = oc->alloc(oc->allocator_args, ocflags);
428                 if (obj) {
429                         if (oc->ctor(obj, oc->privdata, ocflags))
430                                 return (obj);
431                         oc->free(obj, oc->allocator_args);
432                         obj = NULL;
433                 }
434                 if (obj == NULL) {
435                         spin_lock(&depot->spin);
436                         ++depot->unallocated_objects;
437                         spin_unlock(&depot->spin);
438                         if (depot->waiting)
439                                 wakeup(depot);
440
441                         crit_enter();
442                         /*
443                          * makes debugging easier when gets_cumulative does
444                          * not include gets_null.
445                          */
446                         ++cpucache->gets_null;
447                         --cpucache->gets_cumulative;
448                         crit_exit();
449                 }
450                 return(obj);
451         }
452         if (oc->exhausted == 0) {
453                 kprintf("Warning, objcache(%s): Exhausted!\n", oc->name);
454                 oc->exhausted = 1;
455         }
456
457         /*
458          * Otherwise block if allowed to.
459          */
460         if ((ocflags & (M_WAITOK|M_NULLOK)) == M_WAITOK) {
461                 ++cpucache->waiting;
462                 ++depot->waiting;
463                 ssleep(depot, &depot->spin, 0, "objcache_get", 0);
464                 --cpucache->waiting;
465                 --depot->waiting;
466                 spin_unlock(&depot->spin);
467                 goto retry;
468         }
469
470         /*
471          * Otherwise fail
472          */
473         ++cpucache->gets_null;
474         --cpucache->gets_cumulative;
475         crit_exit();
476         spin_unlock(&depot->spin);
477         return (NULL);
478 }
479
480 /*
481  * Wrapper for malloc allocation routines.
482  */
483 void *
484 objcache_malloc_alloc(void *allocator_args, int ocflags)
485 {
486         struct objcache_malloc_args *alloc_args = allocator_args;
487
488         return (kmalloc(alloc_args->objsize, alloc_args->mtype,
489                        ocflags & OC_MFLAGS));
490 }
491
492 void
493 objcache_malloc_free(void *obj, void *allocator_args)
494 {
495         struct objcache_malloc_args *alloc_args = allocator_args;
496
497         kfree(obj, alloc_args->mtype);
498 }
499
500 /*
501  * Wrapper for allocation policies that pre-allocate at initialization time
502  * and don't do run-time allocation.
503  */
504 void *
505 objcache_nop_alloc(void *allocator_args, int ocflags)
506 {
507         return (NULL);
508 }
509
510 void
511 objcache_nop_free(void *obj, void *allocator_args)
512 {
513 }
514
515 /*
516  * Return an object to the object cache.
517  */
518 void
519 objcache_put(struct objcache *oc, void *obj)
520 {
521         struct percpu_objcache *cpucache = &oc->cache_percpu[mycpuid];
522         struct magazine *loadedmag;
523         struct magazinedepot *depot;
524
525         crit_enter();
526         ++cpucache->puts_cumulative;
527
528         if (CLUSTER_OF(obj) != myclusterid) {
529 #ifdef notyet
530                 /* use lazy IPI to send object to owning cluster XXX todo */
531                 ++cpucache->puts_othercluster;
532                 crit_exit();
533                 return;
534 #endif
535         }
536
537 retry:
538         /*
539          * Free slot available in loaded magazine.  This is the hot path.
540          * It is lock-free and uses a critical section to block out interrupt
541          * handlers on the same processor.
542          */
543         loadedmag = cpucache->loaded_magazine;
544         if (!MAGAZINE_FULL(loadedmag)) {
545                 loadedmag->objects[loadedmag->rounds++] = obj;
546                 if (cpucache->waiting)
547                         wakeup_mycpu(&oc->depot[myclusterid]);
548                 crit_exit();
549                 return;
550         }
551
552         /*
553          * Current magazine full, but previous magazine has room.  XXX
554          */
555         if (!MAGAZINE_FULL(cpucache->previous_magazine)) {
556                 swap(cpucache->loaded_magazine, cpucache->previous_magazine);
557                 loadedmag = cpucache->loaded_magazine;
558                 loadedmag->objects[loadedmag->rounds++] = obj;
559                 if (cpucache->waiting)
560                         wakeup_mycpu(&oc->depot[myclusterid]);
561                 crit_exit();
562                 return;
563         }
564
565         /*
566          * Both magazines full.  Get an empty magazine from the depot and
567          * move a full loaded magazine to the depot.  Even though the
568          * magazine may wind up with space available after we block on
569          * the spinlock, we still cycle it through to avoid the non-optimal
570          * corner-case.
571          *
572          * Obtain the depot spinlock.
573          */
574         depot = &oc->depot[myclusterid];
575         spin_lock(&depot->spin);
576
577         /*
578          * If an empty magazine is available in the depot, cycle it
579          * through and retry.
580          */
581         if (!SLIST_EMPTY(&depot->emptymagazines)) {
582                 loadedmag = cpucache->previous_magazine;
583                 cpucache->previous_magazine = cpucache->loaded_magazine;
584                 cpucache->loaded_magazine = SLIST_FIRST(&depot->emptymagazines);
585                 SLIST_REMOVE_HEAD(&depot->emptymagazines, nextmagazine);
586
587                 /*
588                  * Return loadedmag to the depot.  Due to blocking it may
589                  * not be entirely full and could even be empty.
590                  */
591                 if (MAGAZINE_EMPTY(loadedmag)) {
592                         SLIST_INSERT_HEAD(&depot->emptymagazines,
593                                           loadedmag, nextmagazine);
594                         spin_unlock(&depot->spin);
595                 } else {
596                         SLIST_INSERT_HEAD(&depot->fullmagazines,
597                                           loadedmag, nextmagazine);
598                         spin_unlock(&depot->spin);
599                         if (depot->waiting)
600                                 wakeup(depot);
601                 }
602                 goto retry;
603         }
604
605         /*
606          * An empty mag is not available.  This is a corner case which can
607          * occur due to cpus holding partially full magazines.  Do not try
608          * to allocate a mag, just free the object.
609          */
610         ++depot->unallocated_objects;
611         spin_unlock(&depot->spin);
612         if (depot->waiting)
613                 wakeup(depot);
614         crit_exit();
615         oc->dtor(obj, oc->privdata);
616         oc->free(obj, oc->allocator_args);
617 }
618
619 /*
620  * The object is being put back into the cache, but the caller has
621  * indicated that the object is not in any shape to be reused and should
622  * be dtor'd immediately.
623  */
624 void
625 objcache_dtor(struct objcache *oc, void *obj)
626 {
627         struct magazinedepot *depot;
628
629         depot = &oc->depot[myclusterid];
630         spin_lock(&depot->spin);
631         ++depot->unallocated_objects;
632         spin_unlock(&depot->spin);
633         if (depot->waiting)
634                 wakeup(depot);
635         oc->dtor(obj, oc->privdata);
636         oc->free(obj, oc->allocator_args);
637 }
638
639 /*
640  * Deallocate all objects in a magazine and free the magazine if requested.
641  * When freeit is TRUE the magazine must already be disassociated from the
642  * depot.
643  *
644  * Must be called with a critical section held when called with a per-cpu
645  * magazine.  The magazine may be indirectly modified during the loop.
646  *
647  * If the magazine moves during a dtor the operation is aborted.  This is
648  * only allowed when freeit is FALSE.
649  *
650  * The number of objects freed is returned.
651  */
652 static int
653 mag_purge(struct objcache *oc, struct magazine **magp, int freeit)
654 {
655         struct magazine *mag = *magp;
656         int count;
657         void *obj;
658
659         count = 0;
660         while (mag->rounds) {
661                 obj = mag->objects[--mag->rounds];
662                 oc->dtor(obj, oc->privdata);            /* MAY BLOCK */
663                 oc->free(obj, oc->allocator_args);      /* MAY BLOCK */
664                 ++count;
665
666                 /*
667                  * Cycle for interrupts.
668                  */
669                 if ((count & 15) == 0) {
670                         crit_exit();
671                         crit_enter();
672                 }
673
674                 /*
675                  * mag may have become invalid either due to dtor/free
676                  * blocking or interrupt cycling, do not derefernce it
677                  * until we check.
678                  */
679                 if (*magp != mag) {
680                         kprintf("mag_purge: mag ripped out\n");
681                         break;
682                 }
683         }
684         if (freeit) {
685                 KKASSERT(*magp == mag);
686                 *magp = NULL;
687                 kfree(mag, M_OBJMAG);
688         }
689         return(count);
690 }
691
692 /*
693  * Disassociate zero or more magazines from a magazine list associated with
694  * the depot, update the depot, and move the magazines to a temporary
695  * list.
696  *
697  * The caller must check the depot for waiters and wake it up, typically
698  * after disposing of the magazines this function loads onto the temporary
699  * list.
700  */
701 static void
702 maglist_disassociate(struct magazinedepot *depot, struct magazinelist *maglist,
703                      struct magazinelist *tmplist, boolean_t purgeall)
704 {
705         struct magazine *mag;
706
707         while ((mag = SLIST_FIRST(maglist)) != NULL) {
708                 SLIST_REMOVE_HEAD(maglist, nextmagazine);
709                 SLIST_INSERT_HEAD(tmplist, mag, nextmagazine);
710                 depot->unallocated_objects += mag->rounds;
711         }
712 }
713                         
714 /*
715  * Deallocate all magazines and their contents from the passed temporary
716  * list.  The magazines have already been accounted for by their depots.
717  *
718  * The total number of rounds freed is returned.  This number is typically
719  * only used to determine whether a wakeup on the depot is needed or not.
720  */
721 static int
722 maglist_purge(struct objcache *oc, struct magazinelist *maglist)
723 {
724         struct magazine *mag;
725         int count = 0;
726
727         /*
728          * can't use SLIST_FOREACH because blocking releases the depot
729          * spinlock 
730          */
731         crit_enter();
732         while ((mag = SLIST_FIRST(maglist)) != NULL) {
733                 SLIST_REMOVE_HEAD(maglist, nextmagazine);
734                 count += mag_purge(oc, &mag, TRUE);
735         }
736         crit_exit();
737         return(count);
738 }
739
740 /*
741  * De-allocates all magazines on the full and empty magazine lists.
742  *
743  * Because this routine is called with a spinlock held, the magazines
744  * can only be disassociated and moved to a temporary list, not freed.
745  *
746  * The caller is responsible for freeing the magazines.
747  */
748 static void
749 depot_disassociate(struct magazinedepot *depot, struct magazinelist *tmplist)
750 {
751         maglist_disassociate(depot, &depot->fullmagazines, tmplist, TRUE);
752         maglist_disassociate(depot, &depot->emptymagazines, tmplist, TRUE);
753 }
754
755 #ifdef notneeded
756 void
757 objcache_reclaim(struct objcache *oc)
758 {
759         struct percpu_objcache *cache_percpu = &oc->cache_percpu[myclusterid];
760         struct magazinedepot *depot = &oc->depot[myclusterid];
761         struct magazinelist tmplist;
762         int count;
763
764         SLIST_INIT(&tmplist);
765         crit_enter();
766         count = mag_purge(oc, &cache_percpu->loaded_magazine, FALSE);
767         count += mag_purge(oc, &cache_percpu->previous_magazine, FALSE);
768         crit_exit();
769
770         spin_lock(&depot->spin);
771         depot->unallocated_objects += count;
772         depot_disassociate(depot, &tmplist);
773         spin_unlock(&depot->spin);
774         count += maglist_purge(oc, &tmplist);
775         if (count && depot->waiting)
776                 wakeup(depot);
777 }
778 #endif
779
780 /*
781  * Try to free up some memory.  Return as soon as some free memory is found.
782  * For each object cache on the reclaim list, first try the current per-cpu
783  * cache, then the full magazine depot.
784  */
785 boolean_t
786 objcache_reclaimlist(struct objcache *oclist[], int nlist, int ocflags)
787 {
788         struct objcache *oc;
789         struct percpu_objcache *cpucache;
790         struct magazinedepot *depot;
791         struct magazinelist tmplist;
792         int i, count;
793
794         kprintf("objcache_reclaimlist\n");
795
796         SLIST_INIT(&tmplist);
797
798         for (i = 0; i < nlist; i++) {
799                 oc = oclist[i];
800                 cpucache = &oc->cache_percpu[mycpuid];
801                 depot = &oc->depot[myclusterid];
802
803                 crit_enter();
804                 count = mag_purge(oc, &cpucache->loaded_magazine, FALSE);
805                 if (count == 0)
806                         count += mag_purge(oc, &cpucache->previous_magazine, FALSE);
807                 crit_exit();
808                 if (count > 0) {
809                         spin_lock(&depot->spin);
810                         depot->unallocated_objects += count;
811                         spin_unlock(&depot->spin);
812                         if (depot->waiting)
813                                 wakeup(depot);
814                         return (TRUE);
815                 }
816                 spin_lock(&depot->spin);
817                 maglist_disassociate(depot, &depot->fullmagazines,
818                                      &tmplist, FALSE);
819                 spin_unlock(&depot->spin);
820                 count = maglist_purge(oc, &tmplist);
821                 if (count > 0) {
822                         if (depot->waiting)
823                                 wakeup(depot);
824                         return (TRUE);
825                 }
826         }
827         return (FALSE);
828 }
829
830 /*
831  * Destroy an object cache.  Must have no existing references.
832  */
833 void
834 objcache_destroy(struct objcache *oc)
835 {
836         struct percpu_objcache *cache_percpu;
837         struct magazinedepot *depot;
838         int clusterid, cpuid;
839         struct magazinelist tmplist;
840
841         spin_lock(&objcachelist_spin);
842         LIST_REMOVE(oc, oc_next);
843         spin_unlock(&objcachelist_spin);
844
845         SLIST_INIT(&tmplist);
846         for (clusterid = 0; clusterid < MAXCLUSTERS; clusterid++) {
847                 depot = &oc->depot[clusterid];
848                 spin_lock(&depot->spin);
849                 depot_disassociate(depot, &tmplist);
850                 spin_unlock(&depot->spin);
851         }
852         maglist_purge(oc, &tmplist);
853
854         for (cpuid = 0; cpuid < ncpus; cpuid++) {
855                 cache_percpu = &oc->cache_percpu[cpuid];
856
857                 crit_enter();
858                 mag_purge(oc, &cache_percpu->loaded_magazine, TRUE);
859                 mag_purge(oc, &cache_percpu->previous_magazine, TRUE);
860                 crit_exit();
861                 cache_percpu->loaded_magazine = NULL;
862                 cache_percpu->previous_magazine = NULL;
863                 /* don't bother adjusting depot->unallocated_objects */
864         }
865
866         kfree(oc->name, M_TEMP);
867         kfree(oc, M_OBJCACHE);
868 }
869
870 #if 0
871 /*
872  * Populate the per-cluster depot with elements from a linear block
873  * of memory.  Must be called for individually for each cluster.
874  * Populated depots should not be destroyed.
875  */
876 void
877 objcache_populate_linear(struct objcache *oc, void *base, int nelts, int size)
878 {
879         char *p = base;
880         char *end = (char *)base + (nelts * size);
881         struct magazinedepot *depot = &oc->depot[myclusterid];
882         struct magazine *emptymag = mag_alloc(depot->magcapcity);
883
884         while (p < end) {
885                 emptymag->objects[emptymag->rounds++] = p;
886                 if (MAGAZINE_FULL(emptymag)) {
887                         spin_lock_wr(&depot->spin);
888                         SLIST_INSERT_HEAD(&depot->fullmagazines, emptymag,
889                                           nextmagazine);
890                         depot->unallocated_objects += emptymag->rounds;
891                         spin_unlock_wr(&depot->spin);
892                         if (depot->waiting)
893                                 wakeup(depot);
894                         emptymag = mag_alloc(depot->magcapacity);
895                 }
896                 p += size;
897         }
898         if (MAGAZINE_EMPTY(emptymag)) {
899                 crit_enter();
900                 mag_purge(oc, &emptymag, TRUE);
901                 crit_exit();
902         } else {
903                 spin_lock_wr(&depot->spin);
904                 SLIST_INSERT_HEAD(&depot->fullmagazines, emptymag,
905                                   nextmagazine);
906                 depot->unallocated_objects += emptymag->rounds;
907                 spin_unlock_wr(&depot->spin);
908                 if (depot->waiting)
909                         wakeup(depot);
910                 emptymag = mag_alloc(depot->magcapacity);
911         }
912 }
913 #endif
914
915 #if 0
916 /*
917  * Check depot contention once a minute.
918  * 2 contested locks per second allowed.
919  */
920 static int objcache_rebalance_period;
921 static const int objcache_contention_rate = 120;
922 static struct callout objcache_callout;
923
924 #define MAXMAGSIZE 512
925
926 /*
927  * Check depot contention and increase magazine size if necessary.
928  */
929 static void
930 objcache_timer(void *dummy)
931 {
932         struct objcache *oc;
933         struct magazinedepot *depot;
934         struct magazinelist tmplist;
935
936         XXX we need to detect when an objcache is destroyed out from under
937             us XXX
938
939         SLIST_INIT(&tmplist);
940
941         spin_lock_wr(&objcachelist_spin);
942         LIST_FOREACH(oc, &allobjcaches, oc_next) {
943                 depot = &oc->depot[myclusterid];
944                 if (depot->magcapacity < MAXMAGSIZE) {
945                         if (depot->contested > objcache_contention_rate) {
946                                 spin_lock_wr(&depot->spin);
947                                 depot_disassociate(depot, &tmplist);
948                                 depot->magcapacity *= 2;
949                                 spin_unlock_wr(&depot->spin);
950                                 kprintf("objcache_timer: increasing cache %s"
951                                        " magsize to %d, contested %d times\n",
952                                     oc->name, depot->magcapacity,
953                                     depot->contested);
954                         }
955                         depot->contested = 0;
956                 }
957                 spin_unlock_wr(&objcachelist_spin);
958                 if (maglist_purge(oc, &tmplist) > 0 && depot->waiting)
959                         wakeup(depot);
960                 spin_lock_wr(&objcachelist_spin);
961         }
962         spin_unlock_wr(&objcachelist_spin);
963
964         callout_reset(&objcache_callout, objcache_rebalance_period,
965                       objcache_timer, NULL);
966 }
967
968 #endif
969
970 static void
971 objcache_init(void)
972 {
973         spin_init(&objcachelist_spin);
974 #if 0
975         callout_init_mp(&objcache_callout);
976         objcache_rebalance_period = 60 * hz;
977         callout_reset(&objcache_callout, objcache_rebalance_period,
978                       objcache_timer, NULL);
979 #endif
980 }
981 SYSINIT(objcache, SI_BOOT2_OBJCACHE, SI_ORDER_FIRST, objcache_init, 0);