Merge from vendor branch FILE:
[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.13 2006/12/02 22:17:22 dillon 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    256
52
53 struct magazine {
54         int                      rounds;
55         int                      capacity;
56         int                      cleaning;
57         SLIST_ENTRY(magazine)    nextmagazine;
58         void                    *objects[];
59 };
60
61 SLIST_HEAD(magazinelist, magazine);
62
63 /*
64  * per-cluster cache of magazines
65  *
66  * All fields in this structure are protected by the spinlock.
67  */
68 struct magazinedepot {
69         /*
70          * The per-cpu object caches only exchanges completely full or
71          * completely empty magazines with the depot layer, so only have
72          * to cache these two types of magazines.
73          */
74         struct magazinelist     fullmagazines;
75         struct magazinelist     emptymagazines;
76         int                     magcapacity;
77
78         /* protect this structure */
79         struct spinlock         spin;
80
81         /* magazines not yet allocated towards limit */
82         int                     unallocated_objects;
83
84         /* infrequently used fields */
85         int                     waiting;        /* waiting for another cpu to
86                                                  * return a full magazine to
87                                                  * the depot */
88         int                     contested;      /* depot contention count */
89 };
90
91 /*
92  * per-cpu object cache
93  * All fields in this structure are protected by crit_enter().
94  */
95 struct percpu_objcache {
96         struct magazine *loaded_magazine;       /* active magazine */
97         struct magazine *previous_magazine;     /* backup magazine */
98
99         /* statistics */
100         int             gets_cumulative;        /* total calls to get */
101         int             gets_null;              /* objcache_get returned NULL */
102         int             puts_cumulative;        /* total calls to put */
103         int             puts_othercluster;      /* returned to other cluster */
104
105         /* infrequently used fields */
106         int             waiting;        /* waiting for a thread on this cpu to
107                                          * return an obj to the per-cpu cache */
108 };
109
110 /* only until we have NUMA cluster topology information XXX */
111 #define MAXCLUSTERS 1
112 #define myclusterid 0
113 #define CLUSTER_OF(obj) 0
114
115 /*
116  * Two-level object cache consisting of NUMA cluster-level depots of
117  * fully loaded or completely empty magazines and cpu-level caches of
118  * individual objects.
119  */
120 struct objcache {
121         char                    *name;
122
123         /* object constructor and destructor from blank storage */
124         objcache_ctor_fn        *ctor;
125         objcache_dtor_fn        *dtor;
126         void                    *private;
127
128         /* interface to underlying allocator */
129         objcache_alloc_fn       *alloc;
130         objcache_free_fn        *free;
131         void                    *allocator_args;
132         size_t                  simple_objsize;
133
134         SLIST_ENTRY(objcache)   oc_next;
135
136         /* NUMA-cluster level caches */
137         struct magazinedepot    depot[MAXCLUSTERS];
138
139         struct percpu_objcache  cache_percpu[];         /* per-cpu caches */
140 };
141
142 static struct spinlock objcachelist_spin;
143 static SLIST_HEAD(objcachelist, objcache) allobjcaches;
144
145 static struct magazine *
146 mag_alloc(int capacity)
147 {
148         struct magazine *mag;
149
150         mag = kmalloc(__offsetof(struct magazine, objects[capacity]),
151                         M_OBJMAG, M_INTWAIT | M_ZERO);
152         mag->capacity = capacity;
153         mag->rounds = 0;
154         mag->cleaning = 0;
155         return (mag);
156 }
157
158 /*
159  * Create an object cache.
160  */
161 struct objcache *
162 objcache_create(const char *name, int cluster_limit, int mag_capacity,
163                 objcache_ctor_fn *ctor, objcache_dtor_fn *dtor, void *private,
164                 objcache_alloc_fn *alloc, objcache_free_fn *free,
165                 void *allocator_args)
166 {
167         struct objcache *oc;
168         struct magazinedepot *depot;
169         int cpuid;
170
171         /* allocate object cache structure */
172         oc = kmalloc(__offsetof(struct objcache, cache_percpu[ncpus]),
173                     M_OBJCACHE, M_WAITOK | M_ZERO);
174         oc->name = kstrdup(name, M_TEMP);
175         oc->ctor = ctor;
176         oc->dtor = dtor;
177         oc->private = private;
178         oc->free = free;
179         oc->allocator_args = allocator_args;
180
181         /* initialize depots */
182         depot = &oc->depot[0];
183
184         spin_init(&depot->spin);
185         SLIST_INIT(&depot->fullmagazines);
186         SLIST_INIT(&depot->emptymagazines);
187
188         if (mag_capacity == 0)
189                 mag_capacity = INITIAL_MAG_CAPACITY;
190         depot->magcapacity = mag_capacity;
191
192         /*
193          * The cluster_limit must be sufficient to have three magazines per
194          * cpu.
195          */
196         if (cluster_limit == 0) {
197                 depot->unallocated_objects = -1;
198         } else {
199                 if (cluster_limit < mag_capacity * ncpus * 3)
200                         cluster_limit = mag_capacity * ncpus * 3;
201                 depot->unallocated_objects = cluster_limit;
202         }
203         oc->alloc = alloc;
204
205         /* initialize per-cpu caches */
206         for (cpuid = 0; cpuid < ncpus; cpuid++) {
207                 struct percpu_objcache *cache_percpu = &oc->cache_percpu[cpuid];
208
209                 cache_percpu->loaded_magazine = mag_alloc(mag_capacity);
210                 cache_percpu->previous_magazine = mag_alloc(mag_capacity);
211         }
212         spin_lock_wr(&objcachelist_spin);
213         SLIST_INSERT_HEAD(&allobjcaches, oc, oc_next);
214         spin_unlock_wr(&objcachelist_spin);
215
216         return (oc);
217 }
218
219 struct objcache *
220 objcache_create_simple(malloc_type_t mtype, size_t objsize)
221 {
222         struct objcache_malloc_args *margs;
223         struct objcache *oc;
224
225         margs = kmalloc(sizeof(*margs), M_OBJCACHE, M_WAITOK|M_ZERO);
226         margs->objsize = objsize;
227         margs->mtype = mtype;
228         oc = objcache_create(mtype->ks_shortdesc, 0, 0,
229                              null_ctor, null_dtor, NULL,
230                              objcache_malloc_alloc, objcache_malloc_free,
231                              margs);
232
233         /*
234          * This indicates that we are a simple objcache and allows
235          * objcache_get() calls with M_ZERO.
236          */
237         oc->simple_objsize = objsize;
238         return (oc);
239 }
240
241 #define MAGAZINE_EMPTY(mag)     (mag->rounds == 0)
242 #define MAGAZINE_NOTEMPTY(mag)  (mag->rounds != 0)
243 #define MAGAZINE_FULL(mag)      (mag->rounds == mag->capacity)
244
245 #define swap(x, y)      ({ struct magazine *t = x; x = y; y = t; })
246
247 /*
248  * Get an object from the object cache.
249  *
250  * WARNING!  ocflags are only used when we have to go to the underlying
251  * allocator, so we cannot depend on flags such as M_ZERO.
252  */
253 void *
254 objcache_get(struct objcache *oc, int ocflags)
255 {
256         struct percpu_objcache *cpucache = &oc->cache_percpu[mycpuid];
257         struct magazine *loadedmag;
258         struct magazine *emptymag;
259         void *obj;
260         struct magazinedepot *depot;
261
262         crit_enter();
263         ++cpucache->gets_cumulative;
264
265 retry:
266         /*
267          * Loaded magazine has an object.  This is the hot path.
268          * It is lock-free and uses a critical section to block
269          * out interrupt handlers on the same processor.
270          */
271         loadedmag = cpucache->loaded_magazine;
272         if (MAGAZINE_NOTEMPTY(loadedmag)) {
273                 obj = loadedmag->objects[--loadedmag->rounds];
274 done:
275                 crit_exit();
276                 if (ocflags & M_ZERO) {
277                         if (oc->simple_objsize)
278                                 bzero(obj, oc->simple_objsize);
279                         else
280                                 panic("objcache_get(): M_ZERO illegal here");
281                 }
282                 return (obj);
283         }
284
285         /* Previous magazine has an object. */
286         if (MAGAZINE_NOTEMPTY(cpucache->previous_magazine)) {
287                 KKASSERT(cpucache->previous_magazine->cleaning +
288                          cpucache->loaded_magazine->cleaning == 0);
289                 swap(cpucache->loaded_magazine, cpucache->previous_magazine);
290                 loadedmag = cpucache->loaded_magazine;
291                 obj = loadedmag->objects[--loadedmag->rounds];
292                 goto done;
293         }
294
295         /*
296          * Both magazines empty.  Get a full magazine from the depot and
297          * move one of the empty ones to the depot.
298          *
299          * Obtain the depot spinlock.
300          *
301          * NOTE: Beyond this point, M_ZERO is handled via oc->alloc()
302          */
303         depot = &oc->depot[myclusterid];
304         spin_lock_wr(&depot->spin);
305
306         /*
307          * Recheck the cpucache after obtaining the depot spinlock.  This
308          * shouldn't be necessary now but don't take any chances.
309          */
310         if (MAGAZINE_NOTEMPTY(cpucache->loaded_magazine) ||
311             MAGAZINE_NOTEMPTY(cpucache->previous_magazine)
312         ) {
313                 spin_unlock_wr(&depot->spin);
314                 goto retry;
315         }
316
317         /* Check if depot has a full magazine. */
318         if (!SLIST_EMPTY(&depot->fullmagazines)) {
319                 emptymag = cpucache->previous_magazine;
320                 cpucache->previous_magazine = cpucache->loaded_magazine;
321                 cpucache->loaded_magazine = SLIST_FIRST(&depot->fullmagazines);
322                 SLIST_REMOVE_HEAD(&depot->fullmagazines, nextmagazine);
323
324                 /*
325                  * Return emptymag to the depot.
326                  */
327                 KKASSERT(MAGAZINE_EMPTY(emptymag));
328                 SLIST_INSERT_HEAD(&depot->emptymagazines,
329                                   emptymag, nextmagazine);
330                 spin_unlock_wr(&depot->spin);
331                 goto retry;
332         }
333
334         /*
335          * The depot does not have any non-empty magazines.  If we have
336          * not hit our object limit we can allocate a new object using
337          * the back-end allocator.
338          *
339          * note: unallocated_objects can be initialized to -1, which has
340          * the effect of removing any allocation limits.
341          */
342         if (depot->unallocated_objects) {
343                 --depot->unallocated_objects;
344                 spin_unlock_wr(&depot->spin);
345                 crit_exit();
346
347                 obj = oc->alloc(oc->allocator_args, ocflags);
348                 if (obj) {
349                         if (oc->ctor(obj, oc->private, ocflags))
350                                 return (obj);
351                         oc->free(obj, oc->allocator_args);
352                         spin_lock_wr(&depot->spin);
353                         ++depot->unallocated_objects;
354                         spin_unlock_wr(&depot->spin);
355                         if (depot->waiting)
356                                 wakeup(depot);
357                         obj = NULL;
358                 }
359                 if (obj == NULL) {
360                         crit_enter();
361                         /*
362                          * makes debugging easier when gets_cumulative does
363                          * not include gets_null.
364                          */
365                         ++cpucache->gets_null;
366                         --cpucache->gets_cumulative;
367                         crit_exit();
368                 }
369                 return(obj);
370         }
371
372         /*
373          * Otherwise block if allowed to.
374          */
375         if ((ocflags & (M_WAITOK|M_NULLOK)) == M_WAITOK) {
376                 ++cpucache->waiting;
377                 ++depot->waiting;
378                 msleep(depot, &depot->spin, 0, "objcache_get", 0);
379                 --cpucache->waiting;
380                 --depot->waiting;
381                 spin_unlock_wr(&depot->spin);
382                 goto retry;
383         }
384
385         /*
386          * Otherwise fail
387          */
388         ++cpucache->gets_null;
389         --cpucache->gets_cumulative;
390         crit_exit();
391         spin_unlock_wr(&depot->spin);
392         return (NULL);
393 }
394
395 /*
396  * Wrapper for malloc allocation routines.
397  */
398 void *
399 objcache_malloc_alloc(void *allocator_args, int ocflags)
400 {
401         struct objcache_malloc_args *alloc_args = allocator_args;
402
403         return (kmalloc(alloc_args->objsize, alloc_args->mtype,
404                        ocflags & OC_MFLAGS));
405 }
406
407 void
408 objcache_malloc_free(void *obj, void *allocator_args)
409 {
410         struct objcache_malloc_args *alloc_args = allocator_args;
411
412         kfree(obj, alloc_args->mtype);
413 }
414
415 /*
416  * Wrapper for allocation policies that pre-allocate at initialization time
417  * and don't do run-time allocation.
418  */
419 void *
420 objcache_nop_alloc(void *allocator_args, int ocflags)
421 {
422         return (NULL);
423 }
424
425 void
426 objcache_nop_free(void *obj, void *allocator_args)
427 {
428 }
429
430 /*
431  * Return an object to the object cache.
432  */
433 void
434 objcache_put(struct objcache *oc, void *obj)
435 {
436         struct percpu_objcache *cpucache = &oc->cache_percpu[mycpuid];
437         struct magazine *loadedmag;
438         struct magazinedepot *depot;
439
440         crit_enter();
441         ++cpucache->puts_cumulative;
442
443         if (CLUSTER_OF(obj) != myclusterid) {
444 #ifdef notyet
445                 /* use lazy IPI to send object to owning cluster XXX todo */
446                 ++cpucache->puts_othercluster;
447                 crit_exit();
448                 return;
449 #endif
450         }
451
452 retry:
453         /*
454          * Free slot available in loaded magazine.  This is the hot path.
455          * It is lock-free and uses a critical section to block out interrupt
456          * handlers on the same processor.
457          */
458         loadedmag = cpucache->loaded_magazine;
459         if (!MAGAZINE_FULL(loadedmag)) {
460                 loadedmag->objects[loadedmag->rounds++] = obj;
461                 if (cpucache->waiting)
462                         wakeup_mycpu(&oc->depot[myclusterid]);
463                 crit_exit();
464                 return;
465         }
466
467         /*
468          * Current magazine full, but previous magazine has room.  XXX
469          */
470         if (!MAGAZINE_FULL(cpucache->previous_magazine)) {
471                 KKASSERT(cpucache->previous_magazine->cleaning +
472                          cpucache->loaded_magazine->cleaning == 0);
473                 swap(cpucache->loaded_magazine, cpucache->previous_magazine);
474                 loadedmag = cpucache->loaded_magazine;
475                 loadedmag->objects[loadedmag->rounds++] = obj;
476                 if (cpucache->waiting)
477                         wakeup_mycpu(&oc->depot[myclusterid]);
478                 crit_exit();
479                 return;
480         }
481
482         /*
483          * Both magazines full.  Get an empty magazine from the depot and
484          * move a full loaded magazine to the depot.  Even though the
485          * magazine may wind up with space available after we block on
486          * the spinlock, we still cycle it through to avoid the non-optimal
487          * corner-case.
488          *
489          * Obtain the depot spinlock.
490          */
491         depot = &oc->depot[myclusterid];
492         spin_lock_wr(&depot->spin);
493
494         /*
495          * If an empty magazine is available in the depot, cycle it
496          * through and retry.
497          */
498         if (!SLIST_EMPTY(&depot->emptymagazines)) {
499                 KKASSERT(cpucache->previous_magazine->cleaning +
500                          cpucache->loaded_magazine->cleaning == 0);
501                 loadedmag = cpucache->previous_magazine;
502                 cpucache->previous_magazine = cpucache->loaded_magazine;
503                 cpucache->loaded_magazine = SLIST_FIRST(&depot->emptymagazines);
504                 SLIST_REMOVE_HEAD(&depot->emptymagazines, nextmagazine);
505
506                 /*
507                  * Return loadedmag to the depot.  Due to blocking it may
508                  * not be entirely full and could even be empty.
509                  */
510                 if (MAGAZINE_EMPTY(loadedmag)) {
511                         SLIST_INSERT_HEAD(&depot->emptymagazines,
512                                           loadedmag, nextmagazine);
513                         spin_unlock_wr(&depot->spin);
514                 } else {
515                         SLIST_INSERT_HEAD(&depot->fullmagazines,
516                                           loadedmag, nextmagazine);
517                         spin_unlock_wr(&depot->spin);
518                         if (depot->waiting)
519                                 wakeup(depot);
520                 }
521                 goto retry;
522         }
523
524         /*
525          * An empty mag is not available.  This is a corner case which can
526          * occur due to cpus holding partially full magazines.  Do not try
527          * to allocate a mag, just free the object.
528          */
529         ++depot->unallocated_objects;
530         spin_unlock_wr(&depot->spin);
531         if (depot->waiting)
532                 wakeup(depot);
533         crit_exit();
534         oc->dtor(obj, oc->private);
535         oc->free(obj, oc->allocator_args);
536 }
537
538 /*
539  * The object is being put back into the cache, but the caller has
540  * indicated that the object is not in any shape to be reused and should
541  * be dtor'd immediately.
542  */
543 void
544 objcache_dtor(struct objcache *oc, void *obj)
545 {
546         struct magazinedepot *depot;
547
548         depot = &oc->depot[myclusterid];
549         spin_lock_wr(&depot->spin);
550         ++depot->unallocated_objects;
551         spin_unlock_wr(&depot->spin);
552         if (depot->waiting)
553                 wakeup(depot);
554         oc->dtor(obj, oc->private);
555         oc->free(obj, oc->allocator_args);
556 }
557
558 /*
559  * Utility routine for objects that don't require any de-construction.
560  */
561 void
562 null_dtor(void *obj, void *private)
563 {
564         /* do nothing */
565 }
566
567 boolean_t
568 null_ctor(void *obj, void *private, int ocflags)
569 {
570         return TRUE;
571 }
572
573 /*
574  * Deallocate all objects in a magazine and free the magazine if requested.
575  * The magazine must already be disassociated from the depot.
576  *
577  * Must be called with a critical section held when called with a per-cpu
578  * magazine.  The magazine may be indirectly modified during the loop.
579  *
580  * The number of objects freed is returned.
581  */
582 static int
583 mag_purge(struct objcache *oc, struct magazine *mag, int freeit)
584 {
585         int count;
586         void *obj;
587
588         count = 0;
589         ++mag->cleaning;
590         while (mag->rounds) {
591                 obj = mag->objects[--mag->rounds];
592                 oc->dtor(obj, oc->private);             /* MAY BLOCK */
593                 oc->free(obj, oc->allocator_args);      /* MAY BLOCK */
594                 ++count;
595
596                 /*
597                  * Cycle for interrupts
598                  */
599                 if ((count & 15) == 0) {
600                         crit_exit();
601                         crit_enter();
602                 }
603         }
604         --mag->cleaning;
605         if (freeit)
606                 kfree(mag, M_OBJMAG);
607         return(count);
608 }
609
610 /*
611  * Disassociate zero or more magazines from a magazine list associated with
612  * the depot, update the depot, and move the magazines to a temporary
613  * list.
614  *
615  * The caller must check the depot for waiters and wake it up, typically
616  * after disposing of the magazines this function loads onto the temporary
617  * list.
618  */
619 static void
620 maglist_disassociate(struct magazinedepot *depot, struct magazinelist *maglist,
621                      struct magazinelist *tmplist, boolean_t purgeall)
622 {
623         struct magazine *mag;
624
625         while ((mag = SLIST_FIRST(maglist)) != NULL) {
626                 SLIST_REMOVE_HEAD(maglist, nextmagazine);
627                 SLIST_INSERT_HEAD(tmplist, mag, nextmagazine);
628                 depot->unallocated_objects += mag->rounds;
629         }
630 }
631                         
632 /*
633  * Deallocate all magazines and their contents from the passed temporary
634  * list.  The magazines have already been accounted for by their depots.
635  *
636  * The total number of rounds freed is returned.  This number is typically
637  * only used to determine whether a wakeup on the depot is needed or not.
638  */
639 static int
640 maglist_purge(struct objcache *oc, struct magazinelist *maglist)
641 {
642         struct magazine *mag;
643         int count = 0;
644
645         /*
646          * can't use SLIST_FOREACH because blocking releases the depot
647          * spinlock 
648          */
649         while ((mag = SLIST_FIRST(maglist)) != NULL) {
650                 SLIST_REMOVE_HEAD(maglist, nextmagazine);
651                 count += mag_purge(oc, mag, TRUE);
652         }
653         return(count);
654 }
655
656 /*
657  * De-allocates all magazines on the full and empty magazine lists.
658  *
659  * Because this routine is called with a spinlock held, the magazines
660  * can only be disassociated and moved to a temporary list, not freed.
661  *
662  * The caller is responsible for freeing the magazines.
663  */
664 static void
665 depot_disassociate(struct magazinedepot *depot, struct magazinelist *tmplist)
666 {
667         maglist_disassociate(depot, &depot->fullmagazines, tmplist, TRUE);
668         maglist_disassociate(depot, &depot->emptymagazines, tmplist, TRUE);
669 }
670
671 #ifdef notneeded
672 void
673 objcache_reclaim(struct objcache *oc)
674 {
675         struct percpu_objcache *cache_percpu = &oc->cache_percpu[myclusterid];
676         struct magazinedepot *depot = &oc->depot[myclusterid];
677         struct magazinelist tmplist;
678         int count;
679
680         SLIST_INIT(&tmplist);
681         crit_enter();
682         count = mag_purge(oc, cache_percpu->loaded_magazine, FALSE);
683         count += mag_purge(oc, cache_percpu->previous_magazine, FALSE);
684         crit_exit();
685
686         spin_lock_wr(&depot->spin);
687         depot->unallocated_objects += count;
688         depot_disassociate(depot, &tmplist);
689         spin_unlock_wr(&depot->spin);
690         count += maglist_purge(oc, &tmplist);
691         if (count && depot->waiting)
692                 wakeup(depot);
693 }
694 #endif
695
696 /*
697  * Try to free up some memory.  Return as soon as some free memory is found.
698  * For each object cache on the reclaim list, first try the current per-cpu
699  * cache, then the full magazine depot.
700  */
701 boolean_t
702 objcache_reclaimlist(struct objcache *oclist[], int nlist, int ocflags)
703 {
704         struct objcache *oc;
705         struct percpu_objcache *cpucache;
706         struct magazinedepot *depot;
707         struct magazinelist tmplist;
708         int i, count;
709
710         SLIST_INIT(&tmplist);
711
712         for (i = 0; i < nlist; i++) {
713                 oc = oclist[i];
714                 cpucache = &oc->cache_percpu[mycpuid];
715                 depot = &oc->depot[myclusterid];
716
717                 crit_enter();
718                 count = mag_purge(oc, cpucache->loaded_magazine, FALSE);
719                 if (count == 0)
720                         count += mag_purge(oc, cpucache->previous_magazine, FALSE);
721                 crit_exit();
722                 if (count > 0) {
723                         spin_lock_wr(&depot->spin);
724                         depot->unallocated_objects += count;
725                         spin_unlock_wr(&depot->spin);
726                         if (depot->waiting)
727                                 wakeup(depot);
728                         return (TRUE);
729                 }
730                 crit_exit();
731                 spin_lock_wr(&depot->spin);
732                 maglist_disassociate(depot, &depot->fullmagazines,
733                                      &tmplist, FALSE);
734                 spin_unlock_wr(&depot->spin);
735                 count = maglist_purge(oc, &tmplist);
736                 if (count > 0) {
737                         if (depot->waiting)
738                                 wakeup(depot);
739                         return (TRUE);
740                 }
741         }
742         return (FALSE);
743 }
744
745 /*
746  * Destroy an object cache.  Must have no existing references.
747  */
748 void
749 objcache_destroy(struct objcache *oc)
750 {
751         struct percpu_objcache *cache_percpu;
752         struct magazinedepot *depot;
753         int clusterid, cpuid;
754         struct magazinelist tmplist;
755
756         SLIST_INIT(&tmplist);
757         for (clusterid = 0; clusterid < MAXCLUSTERS; clusterid++) {
758                 depot = &oc->depot[clusterid];
759                 spin_lock_wr(&depot->spin);
760                 depot_disassociate(depot, &tmplist);
761                 spin_unlock_wr(&depot->spin);
762         }
763         maglist_purge(oc, &tmplist);
764
765         for (cpuid = 0; cpuid < ncpus; cpuid++) {
766                 cache_percpu = &oc->cache_percpu[cpuid];
767
768                 mag_purge(oc, cache_percpu->loaded_magazine, TRUE);
769                 mag_purge(oc, cache_percpu->previous_magazine, TRUE);
770                 cache_percpu->loaded_magazine = NULL;
771                 cache_percpu->previous_magazine = NULL;
772                 /* don't bother adjusting depot->unallocated_objects */
773         }
774
775         kfree(oc->name, M_TEMP);
776         kfree(oc, M_OBJCACHE);
777 }
778
779 #if 0
780 /*
781  * Populate the per-cluster depot with elements from a linear block
782  * of memory.  Must be called for individually for each cluster.
783  * Populated depots should not be destroyed.
784  */
785 void
786 objcache_populate_linear(struct objcache *oc, void *base, int nelts, int size)
787 {
788         char *p = base;
789         char *end = (char *)base + (nelts * size);
790         struct magazinedepot *depot = &oc->depot[myclusterid];
791         struct magazine *emptymag = mag_alloc(depot->magcapcity);
792
793         while (p < end) {
794                 emptymag->objects[emptymag->rounds++] = p;
795                 if (MAGAZINE_FULL(emptymag)) {
796                         spin_lock_wr(&depot->spin);
797                         SLIST_INSERT_HEAD(&depot->fullmagazines, emptymag,
798                                           nextmagazine);
799                         depot->unallocated_objects += emptymag->rounds;
800                         spin_unlock_wr(&depot->spin);
801                         if (depot->waiting)
802                                 wakeup(depot);
803                         emptymag = mag_alloc(depot->magcapacity);
804                 }
805                 p += size;
806         }
807         if (MAGAZINE_EMPTY(emptymag)) {
808                 mag_purge(oc, emptymag, TRUE);
809         } else {
810                 spin_lock_wr(&depot->spin);
811                 SLIST_INSERT_HEAD(&depot->fullmagazines, emptymag,
812                                   nextmagazine);
813                 depot->unallocated_objects += emptymag->rounds;
814                 spin_unlock_wr(&depot->spin);
815                 if (depot->waiting)
816                         wakeup(depot);
817                 emptymag = mag_alloc(depot->magcapacity);
818         }
819 }
820 #endif
821
822 #if 0
823 /*
824  * Check depot contention once a minute.
825  * 2 contested locks per second allowed.
826  */
827 static int objcache_rebalance_period;
828 static const int objcache_contention_rate = 120;
829 static struct callout objcache_callout;
830
831 #define MAXMAGSIZE 512
832
833 /*
834  * Check depot contention and increase magazine size if necessary.
835  */
836 static void
837 objcache_timer(void *dummy)
838 {
839         struct objcache *oc;
840         struct magazinedepot *depot;
841         struct magazinelist tmplist;
842
843         XXX we need to detect when an objcache is destroyed out from under
844             us XXX
845
846         SLIST_INIT(&tmplist);
847
848         spin_lock_wr(&objcachelist_spin);
849         SLIST_FOREACH(oc, &allobjcaches, oc_next) {
850                 depot = &oc->depot[myclusterid];
851                 if (depot->magcapacity < MAXMAGSIZE) {
852                         if (depot->contested > objcache_contention_rate) {
853                                 spin_lock_wr(&depot->spin);
854                                 depot_disassociate(depot, &tmplist);
855                                 depot->magcapacity *= 2;
856                                 spin_unlock_wr(&depot->spin);
857                                 printf("objcache_timer: increasing cache %s"
858                                        " magsize to %d, contested %d times\n",
859                                     oc->name, depot->magcapacity,
860                                     depot->contested);
861                         }
862                         depot->contested = 0;
863                 }
864                 spin_unlock_wr(&objcachelist_spin);
865                 if (maglist_purge(oc, &tmplist) > 0 && depot->waiting)
866                         wakeup(depot);
867                 spin_lock_wr(&objcachelist_spin);
868         }
869         spin_unlock_wr(&objcachelist_spin);
870
871         callout_reset(&objcache_callout, objcache_rebalance_period,
872                       objcache_timer, NULL);
873 }
874
875 #endif
876
877 static void
878 objcache_init(void)
879 {
880         spin_init(&objcachelist_spin);
881 #if 0
882         callout_init(&objcache_callout);
883         objcache_rebalance_period = 60 * hz;
884         callout_reset(&objcache_callout, objcache_rebalance_period,
885                       objcache_timer, NULL);
886 #endif
887 }
888 SYSINIT(objcache, SI_SUB_CPU, SI_ORDER_ANY, objcache_init, 0);