]> git.saurik.com Git - apple/xnu.git/blob - osfmk/kern/ltable.c
fb4f482cc7e94166ad15f0490e0e76b37582354f
[apple/xnu.git] / osfmk / kern / ltable.c
1 /*
2 * Copyright (c) 2016-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 #include <kern/cpu_data.h>
29 #include <kern/kern_types.h>
30 #include <kern/clock.h>
31 #include <kern/locks.h>
32 #include <kern/ltable.h>
33 #include <kern/zalloc.h>
34 #include <libkern/OSAtomic.h>
35 #include <pexpert/pexpert.h>
36 #include <vm/vm_kern.h>
37
38
39 #define P2ROUNDUP(x, align) (-(-((uintptr_t)(x)) & -((uintptr_t)align)))
40 #define ROUNDDOWN(x, y) (((x)/(y))*(y))
41
42 /* ----------------------------------------------------------------------
43 *
44 * Lockless Link Table Interface
45 *
46 * ---------------------------------------------------------------------- */
47
48 /* default VA space for link tables (zone allocated) */
49 #define DEFAULT_MAX_TABLE_SIZE P2ROUNDUP(8 * 1024 * 1024, PAGE_SIZE)
50
51 TUNABLE(vm_size_t, g_lt_max_tbl_size, "lt_tbl_size", 0);
52 LCK_GRP_DECLARE(g_lt_lck_grp, "link_table_locks");
53
54 #if DEVELOPMENT || DEBUG
55 /* global for lldb macros */
56 uint64_t g_lt_idx_max = LT_IDX_MAX;
57 #endif
58
59 __startup_func
60 static void
61 ltable_startup_tunables_init(void)
62 {
63 // make sure that if a boot-arg was passed, g_lt_max_tbl_size
64 // is a PAGE_SIZE multiple.
65 //
66 // Also set the default for platforms where PAGE_SIZE
67 // isn't a compile time constant.
68 if (g_lt_max_tbl_size == 0) {
69 g_lt_max_tbl_size = (typeof(g_lt_max_tbl_size))DEFAULT_MAX_TABLE_SIZE;
70 } else {
71 g_lt_max_tbl_size = round_page(g_lt_max_tbl_size);
72 }
73 }
74 STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, ltable_startup_tunables_init);
75
76
77 /* construct a link table element from an offset and mask into a slab */
78 #define lt_elem_ofst_slab(slab, slab_msk, ofst) \
79 /* cast through 'void *' to avoid compiler alignment warning messages */ \
80 ((struct lt_elem *)((void *)((uintptr_t)(slab) + ((ofst) & (slab_msk)))))
81
82 #if CONFIG_LTABLE_STATS
83 /* version that makes no assumption on waste within a slab */
84 static inline struct lt_elem *
85 lt_elem_idx(struct link_table *table, uint32_t idx)
86 {
87 int slab_idx = idx / table->slab_elem;
88 struct lt_elem *slab = table->table[slab_idx];
89 if (!slab) {
90 panic("Invalid index:%d slab:%d (NULL) for table:%p\n",
91 idx, slab_idx, table);
92 }
93 assert(slab->lt_id.idx <= idx && (slab->lt_id.idx + table->slab_elem) > idx);
94 return lt_elem_ofst_slab(slab, table->slab_msk, (idx - slab->lt_id.idx) * table->elem_sz);
95 }
96 #else /* !CONFIG_LTABLE_STATS */
97 /* verion that assumes 100% ultilization of slabs (no waste) */
98 static inline struct lt_elem *
99 lt_elem_idx(struct link_table *table, uint32_t idx)
100 {
101 uint32_t ofst = idx * table->elem_sz;
102 struct lt_elem *slab = table->table[ofst >> table->slab_shift];
103 if (!slab) {
104 panic("Invalid index:%d slab:%d (NULL) for table:%p\n",
105 idx, (ofst >> table->slab_shift), table);
106 }
107 assert(slab->lt_id.idx <= idx && (slab->lt_id.idx + table->slab_elem) > idx);
108 return lt_elem_ofst_slab(slab, table->slab_msk, ofst);
109 }
110 #endif /* CONFIG_LTABLE_STATS */
111
112 static int __assert_only
113 lt_elem_in_range(struct lt_elem *elem, struct link_table *table)
114 {
115 struct lt_elem **base = table->table;
116 uintptr_t e = (uintptr_t)elem;
117 assert(base != NULL);
118 while (*base != NULL) {
119 uintptr_t b = (uintptr_t)(*base);
120 if (e >= b && e < b + table->slab_sz) {
121 return 1;
122 }
123 base++;
124 if ((uintptr_t)base >= (uintptr_t)table->table + PAGE_SIZE) {
125 return 0;
126 }
127 }
128 return 0;
129 }
130
131
132 /**
133 * lt_elem_invalidate: mark 'elem' as invalid
134 *
135 * NOTE: this does _not_ get or put a reference on 'elem'
136 */
137 void
138 lt_elem_invalidate(struct lt_elem *elem)
139 {
140 uint32_t __assert_only old = OSBitAndAtomic(~LT_BITS_VALID, &elem->lt_bits);
141 OSMemoryBarrier();
142 assert(((lt_bits_type(old) != LT_RESERVED) && (old & LT_BITS_VALID)) ||
143 ((lt_bits_type(old) == LT_RESERVED) && !(old & LT_BITS_VALID)));
144 }
145
146 /**
147 * lt_elem_mkvalid: mark 'elem' as valid
148 *
149 * NOTE: this does _not_ get or put a reference on 'elem'
150 */
151 void
152 lt_elem_mkvalid(struct lt_elem *elem)
153 {
154 uint32_t __assert_only old = OSBitOrAtomic(LT_BITS_VALID, &elem->lt_bits);
155 OSMemoryBarrier();
156 assert(!(old & LT_BITS_VALID));
157 }
158
159 static void
160 lt_elem_set_type(struct lt_elem *elem, int type)
161 {
162 uint32_t old_bits, new_bits;
163 do {
164 old_bits = elem->lt_bits;
165 new_bits = (old_bits & ~LT_BITS_TYPE) |
166 ((type & LT_BITS_TYPE_MASK) << LT_BITS_TYPE_SHIFT);
167 } while (OSCompareAndSwap(old_bits, new_bits, &elem->lt_bits) == FALSE);
168 OSMemoryBarrier();
169 }
170
171
172 /**
173 * ltable_init: initialize a link table with given parameters
174 *
175 */
176 void
177 ltable_init(struct link_table *table, const char *name,
178 uint32_t max_tbl_elem, uint32_t elem_sz,
179 ltable_poison_func poison)
180 {
181 kern_return_t kr;
182 uint32_t slab_sz, slab_shift, slab_msk, slab_elem;
183 zone_t slab_zone;
184 size_t max_tbl_sz;
185 struct lt_elem *e, **base;
186
187 #ifndef CONFIG_LTABLE_STATS
188 /* the element size _must_ be a power of two! */
189 if ((elem_sz & (elem_sz - 1)) != 0) {
190 panic("elem_sz:%d for table:'%s' must be a power of two!",
191 elem_sz, name);
192 }
193 #endif
194
195 /*
196 * First, allocate a single page of memory to act as the base
197 * for the table's element slabs
198 */
199 kr = kernel_memory_allocate(kernel_map, (vm_offset_t *)&base,
200 PAGE_SIZE, 0, KMA_NOPAGEWAIT, VM_KERN_MEMORY_LTABLE);
201 if (kr != KERN_SUCCESS) {
202 panic("Cannot initialize %s table: "
203 "kernel_memory_allocate failed:%d\n", name, kr);
204 }
205 memset(base, 0, PAGE_SIZE);
206
207 /*
208 * Based on the maximum table size, calculate the slab size:
209 * we allocate 1 page of slab pointers for the table, and we need to
210 * index elements of 'elem_sz', this gives us the slab size based on
211 * the maximum size the table should grow.
212 */
213 max_tbl_sz = (max_tbl_elem * elem_sz);
214 max_tbl_sz = P2ROUNDUP(max_tbl_sz, PAGE_SIZE);
215
216 /* system maximum table size divided by number of slots in a page */
217 slab_sz = (uint32_t)(max_tbl_sz / (PAGE_SIZE / (sizeof(void *))));
218 if (slab_sz < PAGE_SIZE) {
219 slab_sz = PAGE_SIZE;
220 }
221
222 /* make sure the slab size is a power of two */
223 slab_shift = 0;
224 slab_msk = ~0;
225 for (uint32_t i = 0; i < 31; i++) {
226 uint32_t bit = (1 << i);
227 if ((slab_sz & bit) == slab_sz) {
228 slab_shift = i;
229 slab_msk = 0;
230 for (uint32_t j = 0; j < i; j++) {
231 slab_msk |= (1 << j);
232 }
233 break;
234 }
235 slab_sz &= ~bit;
236 }
237 slab_elem = slab_sz / elem_sz;
238
239 /* initialize the table's slab zone (for table growth) */
240 ltdbg("Initializing %s zone: slab:%d (%d,0x%x) max:%ld",
241 name, slab_sz, slab_shift, slab_msk, max_tbl_sz);
242 slab_zone = zone_create(name, slab_sz, ZC_NONE);
243 assert(slab_zone != ZONE_NULL);
244
245 /* allocate the first slab and populate it */
246 base[0] = (struct lt_elem *)zalloc(slab_zone);
247 if (base[0] == NULL) {
248 panic("Can't allocate a %s table slab from zone:%p",
249 name, slab_zone);
250 }
251
252 memset(base[0], 0, slab_sz);
253
254 /* setup the initial freelist */
255 ltdbg("initializing %d links (%d bytes each)...", slab_elem, elem_sz);
256 for (unsigned l = 0; l < slab_elem; l++) {
257 e = lt_elem_ofst_slab(base[0], slab_msk, l * elem_sz);
258 e->lt_id.idx = l;
259 /*
260 * setting generation to 0 ensures that a setid of 0 is
261 * invalid because the generation will be incremented before
262 * each element's allocation.
263 */
264 e->lt_id.generation = 0;
265 e->lt_next_idx = l + 1;
266 }
267
268 /* make sure the last free element points to a never-valid idx */
269 e = lt_elem_ofst_slab(base[0], slab_msk, (slab_elem - 1) * elem_sz);
270 e->lt_next_idx = LT_IDX_MAX;
271
272 lck_mtx_init(&table->lock, &g_lt_lck_grp, LCK_ATTR_NULL);
273
274 table->slab_sz = slab_sz;
275 table->slab_shift = slab_shift;
276 table->slab_msk = slab_msk;
277 table->slab_elem = slab_elem;
278 table->slab_zone = slab_zone;
279
280 table->elem_sz = elem_sz;
281 table->nelem = slab_elem;
282 table->used_elem = 0;
283 table->elem_sz = elem_sz;
284 table->poison = poison;
285
286 table->table = base;
287 table->next_free_slab = &base[1];
288 table->free_list.id = base[0]->lt_id.id;
289
290 #if CONFIG_LTABLE_STATS
291 table->nslabs = 1;
292 table->nallocs = 0;
293 table->nreallocs = 0;
294 table->npreposts = 0;
295 table->nreservations = 0;
296 table->nreserved_releases = 0;
297
298 table->max_used = 0;
299 table->avg_used = 0;
300 table->max_reservations = 0;
301 table->avg_reservations = 0;
302 #endif
303 }
304
305
306 /**
307 * ltable_grow: grow a link table by adding another 'slab' of table elements
308 *
309 * Conditions:
310 * table mutex is unlocked
311 * calling thread can block
312 */
313 void
314 ltable_grow(struct link_table *table, uint32_t min_free)
315 {
316 struct lt_elem *slab, **slot;
317 struct lt_elem *e = NULL, *first_new_elem, *last_new_elem;
318 struct ltable_id free_id;
319 uint32_t free_elem;
320
321 assert(get_preemption_level() == 0);
322 assert(table && table->slab_zone);
323
324 lck_mtx_lock(&table->lock);
325
326 free_elem = table->nelem - table->used_elem;
327
328 /*
329 * If the caller just wanted to ensure a minimum number of elements,
330 * do that (and don't just blindly grow the table). Also, don't grow
331 * the table unnecessarily - we could have been beaten by a higher
332 * priority thread who acquired the lock and grew the table before we
333 * got here.
334 */
335 if (free_elem > min_free) {
336 lck_mtx_unlock(&table->lock);
337 return;
338 }
339
340 /* we are now committed to table growth */
341 ltdbg_v("BEGIN");
342
343 if (table->next_free_slab == NULL) {
344 /*
345 * before we panic, check one more time to see if any other
346 * threads have free'd from space in the table.
347 */
348 if ((table->nelem - table->used_elem) > 0) {
349 /* there's at least 1 free element: don't panic yet */
350 lck_mtx_unlock(&table->lock);
351 return;
352 }
353 panic("No more room to grow table: %p (nelem: %d, used: %d)",
354 table, table->nelem, table->used_elem);
355 }
356 slot = table->next_free_slab;
357 table->next_free_slab++;
358 if ((uintptr_t)table->next_free_slab >= (uintptr_t)table->table + PAGE_SIZE) {
359 table->next_free_slab = NULL;
360 }
361
362 assert(*slot == NULL);
363
364 /* allocate another slab */
365 slab = (struct lt_elem *)zalloc(table->slab_zone);
366 if (slab == NULL) {
367 panic("Can't allocate a %s%s table (%p) slab from zone:%p",
368 zone_heap_name(table->slab_zone), zone_name(table->slab_zone),
369 table, table->slab_zone);
370 }
371
372 memset(slab, 0, table->slab_sz);
373
374 /* put the new elements into a freelist */
375 ltdbg_v(" init %d new links...", table->slab_elem);
376 for (unsigned l = 0; l < table->slab_elem; l++) {
377 uint32_t idx = l + table->nelem;
378 if (idx >= (LT_IDX_MAX - 1)) {
379 break; /* the last element of the last slab */
380 }
381 e = lt_elem_ofst_slab(slab, table->slab_msk, l * table->elem_sz);
382 e->lt_id.idx = idx;
383 e->lt_next_idx = idx + 1;
384 }
385 last_new_elem = e;
386 assert(last_new_elem != NULL);
387
388 first_new_elem = lt_elem_ofst_slab(slab, table->slab_msk, 0);
389
390 /* update table book keeping, and atomically swap the freelist head */
391 *slot = slab;
392 if (table->nelem + table->slab_elem >= LT_IDX_MAX) {
393 table->nelem = LT_IDX_MAX - 1;
394 } else {
395 table->nelem += table->slab_elem;
396 }
397
398 #if CONFIG_LTABLE_STATS
399 table->nslabs += 1;
400 #endif
401
402 /*
403 * The atomic swap of the free list head marks the end of table
404 * growth. Incoming requests may now use the newly allocated slab
405 * of table elements
406 */
407 free_id = table->free_list;
408 /* connect the existing free list to the end of the new free list */
409 last_new_elem->lt_next_idx = free_id.idx;
410 while (OSCompareAndSwap64(free_id.id, first_new_elem->lt_id.id,
411 &table->free_list.id) == FALSE) {
412 OSMemoryBarrier();
413 free_id = table->free_list;
414 last_new_elem->lt_next_idx = free_id.idx;
415 }
416 OSMemoryBarrier();
417
418 lck_mtx_unlock(&table->lock);
419
420 return;
421 }
422
423 #if DEVELOPMENT || DEBUG
424
425 int
426 ltable_nelem(struct link_table *table)
427 {
428 int nelem = 0;
429
430 lck_mtx_lock(&table->lock);
431
432 nelem = table->used_elem;
433
434 lck_mtx_unlock(&table->lock);
435
436 return nelem;
437 }
438 #endif
439
440 /**
441 * ltable_alloc_elem: allocate one or more elements from a given table
442 *
443 * The returned element(s) will be of type 'type', but will remain invalid.
444 *
445 * If the caller has disabled preemption, then this function may (rarely) spin
446 * waiting either for another thread to either release 'nelem' table elements,
447 * or grow the table.
448 *
449 * If the caller can block, then this function may (rarely) block while
450 * the table grows to meet the demand for 'nelem' element(s).
451 */
452 __attribute__((noinline))
453 struct lt_elem *
454 ltable_alloc_elem(struct link_table *table, int type,
455 int nelem, int nattempts)
456 {
457 int nspins = 0, ntries = 0, nalloc = 0;
458 uint32_t table_size;
459 struct lt_elem *elem = NULL;
460 struct ltable_id free_id, next_id;
461
462 static const int max_retries = 500;
463
464 if (type != LT_ELEM && type != LT_LINK && type != LT_RESERVED) {
465 panic("link_table_aloc of invalid elem type:%d from table @%p",
466 type, table);
467 }
468
469 assert(nelem > 0);
470
471 /*
472 * If the callers only wants to try a certain number of times, make it
473 * look like we've already made (MAX - nattempts) tries at allocation
474 */
475 if (nattempts > 0 && nattempts <= max_retries) {
476 ntries = max_retries - nattempts;
477 }
478
479 try_again:
480 elem = NULL;
481 if (ntries++ > max_retries) {
482 struct lt_elem *tmp;
483 if (nattempts > 0) {
484 /*
485 * The caller specified a particular number of
486 * attempts before failure, so it's expected that
487 * they're prepared to handle a NULL return.
488 */
489 return NULL;
490 }
491
492 if (table->used_elem + nelem >= table_size) {
493 panic("No more room to grow table: 0x%p size:%d, used:%d, requested elem:%d",
494 table, table_size, table->used_elem, nelem);
495 }
496 if (nelem == 1) {
497 panic("Too many alloc retries: %d, table:%p, type:%d, nelem:%d",
498 ntries, table, type, nelem);
499 }
500 /* don't panic: try allocating one-at-a-time */
501 while (nelem > 0) {
502 tmp = ltable_alloc_elem(table, type, 1, nattempts);
503 if (elem) {
504 lt_elem_list_link(table, tmp, elem);
505 }
506 elem = tmp;
507 --nelem;
508 }
509 assert(elem != NULL);
510 return elem;
511 }
512
513 nalloc = 0;
514 table_size = table->nelem;
515
516 if (table->used_elem + nelem >= table_size) {
517 if (get_preemption_level() != 0) {
518 #if CONFIG_LTABLE_STATS
519 table->nspins += 1;
520 #endif
521 /*
522 * We may have just raced with table growth: check
523 * again to make sure there really isn't any space.
524 */
525 if (++nspins > 4) {
526 panic("Can't grow table %p with preemption"
527 " disabled!", table);
528 }
529 delay(1);
530 goto try_again;
531 }
532 ltable_grow(table, nelem);
533 goto try_again;
534 }
535
536 /* read this value only once before the CAS */
537 free_id = table->free_list;
538 if (free_id.idx >= table_size) {
539 goto try_again;
540 }
541
542 /*
543 * Find the item on the free list which will become the new free list
544 * head, but be careful not to modify any memory (read only)! Other
545 * threads can alter table state at any time up until the CAS. We
546 * don't modify any memory until we've successfully swapped out the
547 * free list head with the one we've investigated.
548 */
549 for (struct lt_elem *next_elem = lt_elem_idx(table, free_id.idx);
550 nalloc < nelem;
551 nalloc++) {
552 elem = next_elem;
553 next_id.generation = 0;
554 next_id.idx = next_elem->lt_next_idx;
555 if (next_id.idx < table->nelem) {
556 next_elem = lt_elem_idx(table, next_id.idx);
557 next_id.id = next_elem->lt_id.id;
558 } else {
559 goto try_again;
560 }
561 }
562 /* 'elem' points to the last element being allocated */
563
564 if (OSCompareAndSwap64(free_id.id, next_id.id,
565 &table->free_list.id) == FALSE) {
566 goto try_again;
567 }
568
569 /* load barrier */
570 OSMemoryBarrier();
571
572 /*
573 * After the CAS, we know that we own free_id, and it points to a
574 * valid table entry (checked above). Grab the table pointer and
575 * reset some values.
576 */
577 OSAddAtomic(nelem, &table->used_elem);
578
579 /* end the list of allocated elements */
580 elem->lt_next_idx = LT_IDX_MAX;
581 /* reset 'elem' to point to the first allocated element */
582 elem = lt_elem_idx(table, free_id.idx);
583
584 /*
585 * Update the generation count, and return the element(s)
586 * with a single reference (and no valid bit). If the
587 * caller immediately calls _put() on any element, then
588 * it will be released back to the free list. If the caller
589 * subsequently marks the element as valid, then the put
590 * will simply drop the reference.
591 */
592 for (struct lt_elem *tmp = elem;;) {
593 assert(!lt_bits_valid(tmp->lt_bits) &&
594 (lt_bits_refcnt(tmp->lt_bits) == 0));
595 --nalloc;
596 tmp->lt_id.generation += 1;
597 tmp->lt_bits = 1;
598 lt_elem_set_type(tmp, type);
599 if (tmp->lt_next_idx == LT_IDX_MAX) {
600 break;
601 }
602 assert(tmp->lt_next_idx != LT_IDX_MAX);
603 tmp = lt_elem_idx(table, tmp->lt_next_idx);
604 }
605 assert(nalloc == 0);
606
607 #if CONFIG_LTABLE_STATS
608 uint64_t nreservations;
609 table->nallocs += nelem;
610 if (type == LT_RESERVED) {
611 OSIncrementAtomic64(&table->nreservations);
612 }
613 nreservations = table->nreservations;
614 if (table->used_elem > table->max_used) {
615 table->max_used = table->used_elem;
616 }
617 if (nreservations > table->max_reservations) {
618 table->max_reservations = nreservations;
619 }
620 table->avg_used = (table->avg_used + table->used_elem) / 2;
621 table->avg_reservations = (table->avg_reservations + nreservations) / 2;
622 #endif
623
624 return elem;
625 }
626
627
628 /**
629 * ltable_realloc_elem: convert a reserved element to a particular type
630 *
631 * This funciton is used to convert reserved elements (not yet marked valid)
632 * to the given 'type'. The generation of 'elem' is incremented, the element
633 * is disconnected from any list to which it belongs, and its type is set to
634 * 'type'.
635 */
636 void
637 ltable_realloc_elem(struct link_table *table, struct lt_elem *elem, int type)
638 {
639 (void)table;
640 assert(lt_elem_in_range(elem, table) &&
641 !lt_bits_valid(elem->lt_bits));
642
643 #if CONFIG_LTABLE_STATS
644 table->nreallocs += 1;
645 if (lt_bits_type(elem->lt_bits) == LT_RESERVED && type != LT_RESERVED) {
646 /*
647 * This isn't under any lock, so we'll clamp it.
648 * the stats are meant to be informative, not perfectly
649 * accurate
650 */
651 OSDecrementAtomic64(&table->nreservations);
652 }
653 table->avg_reservations = (table->avg_reservations + table->nreservations) / 2;
654 #endif
655
656 /*
657 * Return the same element with a new generation count, and a
658 * (potentially) new type. Don't touch the refcount: the caller
659 * is responsible for getting that (and the valid bit) correct.
660 */
661 elem->lt_id.generation += 1;
662 elem->lt_next_idx = LT_IDX_MAX;
663 lt_elem_set_type(elem, type);
664
665 return;
666 }
667
668
669 /**
670 * ltable_free_elem: release an element back to a link table
671 *
672 * Do not call this function directly: use ltable_[get|put]_elem!
673 *
674 * Conditions:
675 * 'elem' was originally allocated from 'table'
676 * 'elem' is _not_ marked valid
677 * 'elem' has a reference count of 0
678 */
679 static void
680 ltable_free_elem(struct link_table *table, struct lt_elem *elem)
681 {
682 struct ltable_id next_id;
683
684 assert(lt_elem_in_range(elem, table) &&
685 !lt_bits_valid(elem->lt_bits) &&
686 (lt_bits_refcnt(elem->lt_bits) == 0));
687
688 OSDecrementAtomic(&table->used_elem);
689
690 #if CONFIG_LTABLE_STATS
691 table->avg_used = (table->avg_used + table->used_elem) / 2;
692 if (lt_bits_type(elem->lt_bits) == LT_RESERVED) {
693 OSDecrementAtomic64(&table->nreservations);
694 }
695 table->avg_reservations = (table->avg_reservations + table->nreservations) / 2;
696 #endif
697
698 elem->lt_bits = 0;
699
700 if (table->poison) {
701 (table->poison)(table, elem);
702 }
703
704 again:
705 next_id = table->free_list;
706 if (next_id.idx >= table->nelem) {
707 elem->lt_next_idx = LT_IDX_MAX;
708 } else {
709 elem->lt_next_idx = next_id.idx;
710 }
711
712 /* store barrier */
713 OSMemoryBarrier();
714 if (OSCompareAndSwap64(next_id.id, elem->lt_id.id,
715 &table->free_list.id) == FALSE) {
716 goto again;
717 }
718 }
719
720
721 /**
722 * ltable_get_elem: get a reference to a table element identified by 'id'
723 *
724 * Returns a reference to the table element associated with the given 'id', or
725 * NULL if the 'id' was invalid or does not exist in 'table'. The caller is
726 * responsible to release the reference using ltable_put_elem().
727 *
728 * NOTE: if the table element pointed to by 'id' is marked as invalid,
729 * this function will return NULL.
730 */
731 struct lt_elem *
732 ltable_get_elem(struct link_table *table, uint64_t id)
733 {
734 struct lt_elem *elem;
735 uint32_t idx, bits, new_bits;
736
737 /*
738 * Here we have a reference to the table which is guaranteed to remain
739 * valid until we drop the reference
740 */
741
742 idx = ((struct ltable_id *)&id)->idx;
743
744 if (idx >= table->nelem) {
745 panic("id:0x%llx : idx:%d > %d", id, idx, table->nelem);
746 }
747
748 elem = lt_elem_idx(table, idx);
749
750 /* verify the validity by taking a reference on the table object */
751 bits = elem->lt_bits;
752 if (!lt_bits_valid(bits)) {
753 return NULL;
754 }
755
756 /*
757 * do a pre-verify on the element ID to potentially
758 * avoid 2 compare-and-swaps
759 */
760 if (elem->lt_id.id != id) {
761 return NULL;
762 }
763
764 new_bits = bits + 1;
765
766 /* check for overflow */
767 assert(lt_bits_refcnt(new_bits) > 0);
768
769 while (OSCompareAndSwap(bits, new_bits, &elem->lt_bits) == FALSE) {
770 /*
771 * either the element became invalid,
772 * or someone else grabbed/removed a reference.
773 */
774 bits = elem->lt_bits;
775 if (!lt_bits_valid(bits)) {
776 /* don't return invalid elements */
777 return NULL;
778 }
779 new_bits = bits + 1;
780 assert(lt_bits_refcnt(new_bits) > 0);
781 }
782
783 /* load barrier */
784 OSMemoryBarrier();
785
786 /* check to see that our reference is to the same generation! */
787 if (elem->lt_id.id != id) {
788 /*
789 * ltdbg("ID:0x%llx table generation (%d) != %d",
790 * id, elem->lt_id.generation,
791 * ((struct ltable_id *)&id)->generation);
792 */
793 ltable_put_elem(table, elem);
794 return NULL;
795 }
796
797 /* We now have a reference on a valid object */
798 return elem;
799 }
800
801 /**
802 * ltable_put_elem: release a reference to table element
803 *
804 * This function releases a reference taken on a table element via
805 * ltable_get_elem(). This function will release the element back to 'table'
806 * when the reference count goes to 0 AND the element has been marked as
807 * invalid.
808 */
809 void
810 ltable_put_elem(struct link_table *table, struct lt_elem *elem)
811 {
812 uint32_t bits, new_bits;
813
814 assert(lt_elem_in_range(elem, table));
815
816 bits = elem->lt_bits;
817 new_bits = bits - 1;
818
819 /* check for underflow */
820 assert(lt_bits_refcnt(new_bits) < LT_BITS_REFCNT_MASK);
821
822 while (OSCompareAndSwap(bits, new_bits, &elem->lt_bits) == FALSE) {
823 bits = elem->lt_bits;
824 new_bits = bits - 1;
825 /* catch underflow */
826 assert(lt_bits_refcnt(new_bits) < LT_BITS_REFCNT_MASK);
827 }
828
829 /* load barrier */
830 OSMemoryBarrier();
831
832 /*
833 * if this was the last reference, and it was marked as invalid,
834 * then we can add this link object back to the free list
835 */
836 if (!lt_bits_valid(new_bits) && (lt_bits_refcnt(new_bits) == 0)) {
837 ltable_free_elem(table, elem);
838 }
839
840 return;
841 }
842
843
844 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
845 *
846 * API: lt_elem_list_...
847 *
848 * Reuse the free list linkage member, 'lt_next_idx' of a table element
849 * in a slightly more generic singly-linked list. All members of this
850 * list have been allocated from a table, but have not been made valid.
851 *
852 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
853
854 /**
855 * lt_elem_list_link: link a child onto a parent
856 *
857 * Note that if 'parent' is the head of a list, this function will follow that
858 * list and attach 'child' to the end of it. In the simplest case, this
859 * results in: parent->child
860 * however this could also result in: parent->...->child
861 */
862 int
863 lt_elem_list_link(struct link_table *table, struct lt_elem *parent, struct lt_elem *child)
864 {
865 int nelem = 1;
866
867 assert(lt_elem_in_range(parent, table));
868
869 /* find the end of the parent's list */
870 while (parent->lt_next_idx != LT_IDX_MAX) {
871 assert(parent->lt_next_idx < table->nelem);
872 parent = lt_elem_idx(table, parent->lt_next_idx);
873 nelem++;
874 }
875
876 if (child) {
877 assert(lt_elem_in_range(child, table));
878 parent->lt_next_idx = child->lt_id.idx;
879 }
880
881 return nelem;
882 }
883
884
885 /**
886 * lt_elem_list_first: obtain a pointer to the first element of a list.
887 *
888 * This function converts the head of a singly-linked list, 'id', into a real
889 * lt_elem object and returns a pointer to the object.
890 *
891 * It does _not_ take an extra reference on the object: the list implicitly
892 * holds that reference.
893 */
894 struct lt_elem *
895 lt_elem_list_first(struct link_table *table, uint64_t id)
896 {
897 uint32_t idx;
898 struct lt_elem *elem = NULL;
899
900 if (id == 0) {
901 return NULL;
902 }
903
904 idx = ((struct ltable_id *)&id)->idx;
905
906 if (idx > table->nelem) {
907 panic("Invalid element for id:0x%llx", id);
908 }
909 elem = lt_elem_idx(table, idx);
910
911 /* invalid element: reserved ID was probably already reallocated */
912 if (elem->lt_id.id != id) {
913 return NULL;
914 }
915
916 /* the returned element should _not_ be marked valid! */
917 if (lt_bits_valid(elem->lt_bits) ||
918 lt_bits_type(elem->lt_bits) != LT_RESERVED ||
919 lt_bits_refcnt(elem->lt_bits) != 1) {
920 panic("Valid/unreserved element %p (0x%x) in reserved list",
921 elem, elem->lt_bits);
922 }
923
924 return elem;
925 }
926
927
928 /**
929 * lt_elem_list_next: return the item subsequent to 'elem' in a list
930 *
931 * Note that this will return NULL if 'elem' is actually the end of the list.
932 */
933 struct lt_elem *
934 lt_elem_list_next(struct link_table *table, struct lt_elem *head)
935 {
936 struct lt_elem *elem;
937
938 if (!head) {
939 return NULL;
940 }
941 if (head->lt_next_idx >= table->nelem) {
942 return NULL;
943 }
944
945 elem = lt_elem_idx(table, head->lt_next_idx);
946 assert(lt_elem_in_range(elem, table));
947
948 return elem;
949 }
950
951
952 /**
953 * lt_elem_list_break: break a list in two around 'elem'
954 *
955 * This function will reset the next_idx field of 'elem' (making it the end of
956 * the list), and return the element subsequent to 'elem' in the list
957 * (which could be NULL)
958 */
959 struct lt_elem *
960 lt_elem_list_break(struct link_table *table, struct lt_elem *elem)
961 {
962 struct lt_elem *next;
963
964 if (!elem) {
965 return NULL;
966 }
967 next = lt_elem_list_next(table, elem);
968 elem->lt_next_idx = LT_IDX_MAX;
969
970 return next;
971 }
972
973
974 /**
975 * lt_elem_list_pop: pop an item off the head of a list
976 *
977 * The list head is pointed to by '*id', the element corresponding to '*id' is
978 * returned by this function, and the new list head is returned in the in/out
979 * parameter, '*id'. The caller is responsible for the reference on the
980 * returned object. A realloc is done to reset the type of the object, but it
981 * is still left invalid.
982 */
983 struct lt_elem *
984 lt_elem_list_pop(struct link_table *table, uint64_t *id, int type)
985 {
986 struct lt_elem *first, *next;
987
988 if (!id || *id == 0) {
989 return NULL;
990 }
991
992 /* pop an item off the reserved stack */
993
994 first = lt_elem_list_first(table, *id);
995 if (!first) {
996 *id = 0;
997 return NULL;
998 }
999
1000 next = lt_elem_list_next(table, first);
1001 if (next) {
1002 *id = next->lt_id.id;
1003 } else {
1004 *id = 0;
1005 }
1006
1007 ltable_realloc_elem(table, first, type);
1008
1009 return first;
1010 }
1011
1012 /**
1013 * lt_elem_list_release: free an entire list of reserved elements
1014 *
1015 * All elements in the list whose first member is 'head' will be released back
1016 * to 'table' as free elements. The 'type' parameter is used in development
1017 * kernels to assert that all elements on the list are of the given type.
1018 */
1019 int
1020 lt_elem_list_release(struct link_table *table, struct lt_elem *head,
1021 int __assert_only type)
1022 {
1023 struct lt_elem *elem;
1024 struct ltable_id free_id;
1025 int nelem = 0;
1026
1027 if (!head) {
1028 return 0;
1029 }
1030
1031 for (elem = head;;) {
1032 assert(lt_elem_in_range(elem, table));
1033 assert(!lt_bits_valid(elem->lt_bits) && (lt_bits_refcnt(elem->lt_bits) == 1));
1034 assert(lt_bits_type(elem->lt_bits) == type);
1035
1036 nelem++;
1037 elem->lt_bits = 0;
1038 if (table->poison) {
1039 (table->poison)(table, elem);
1040 }
1041
1042 if (elem->lt_next_idx == LT_IDX_MAX) {
1043 break;
1044 }
1045 assert(elem->lt_next_idx < table->nelem);
1046 elem = lt_elem_idx(table, elem->lt_next_idx);
1047 }
1048
1049 /*
1050 * 'elem' now points to the end of our list, and 'head' points to the
1051 * beginning. We want to atomically swap the free list pointer with
1052 * the 'head' and ensure that 'elem' points to the previous free list
1053 * head.
1054 */
1055
1056 again:
1057 free_id = table->free_list;
1058 if (free_id.idx >= table->nelem) {
1059 elem->lt_next_idx = LT_IDX_MAX;
1060 } else {
1061 elem->lt_next_idx = free_id.idx;
1062 }
1063
1064 /* store barrier */
1065 OSMemoryBarrier();
1066 if (OSCompareAndSwap64(free_id.id, head->lt_id.id,
1067 &table->free_list.id) == FALSE) {
1068 goto again;
1069 }
1070
1071 OSAddAtomic(-nelem, &table->used_elem);
1072 return nelem;
1073 }