]> git.saurik.com Git - apple/xnu.git/blame - osfmk/kern/ltable.c
xnu-7195.101.1.tar.gz
[apple/xnu.git] / osfmk / kern / ltable.c
CommitLineData
39037602 1/*
f427ee49 2 * Copyright (c) 2016-2020 Apple Inc. All rights reserved.
39037602
A
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>
f427ee49 30#include <kern/clock.h>
39037602
A
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
f427ee49 39#define P2ROUNDUP(x, align) (-(-((uintptr_t)(x)) & -((uintptr_t)align)))
0a7de745 40#define ROUNDDOWN(x, y) (((x)/(y))*(y))
39037602
A
41
42/* ----------------------------------------------------------------------
43 *
44 * Lockless Link Table Interface
45 *
46 * ---------------------------------------------------------------------- */
47
39037602
A
48/* default VA space for link tables (zone allocated) */
49#define DEFAULT_MAX_TABLE_SIZE P2ROUNDUP(8 * 1024 * 1024, PAGE_SIZE)
50
f427ee49
A
51TUNABLE(vm_size_t, g_lt_max_tbl_size, "lt_tbl_size", 0);
52LCK_GRP_DECLARE(g_lt_lck_grp, "link_table_locks");
53
5ba3f43e 54#if DEVELOPMENT || DEBUG
39037602
A
55/* global for lldb macros */
56uint64_t g_lt_idx_max = LT_IDX_MAX;
57#endif
58
f427ee49
A
59__startup_func
60static void
61ltable_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}
74STARTUP(TUNABLES, STARTUP_RANK_MIDDLE, ltable_startup_tunables_init);
75
39037602
A
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
5ba3f43e 82#if CONFIG_LTABLE_STATS
39037602
A
83/* version that makes no assumption on waste within a slab */
84static inline struct lt_elem *
85lt_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];
0a7de745 89 if (!slab) {
39037602 90 panic("Invalid index:%d slab:%d (NULL) for table:%p\n",
0a7de745
A
91 idx, slab_idx, table);
92 }
39037602
A
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) */
98static inline struct lt_elem *
99lt_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];
0a7de745 103 if (!slab) {
39037602 104 panic("Invalid index:%d slab:%d (NULL) for table:%p\n",
0a7de745
A
105 idx, (ofst >> table->slab_shift), table);
106 }
39037602
A
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}
5ba3f43e 110#endif /* CONFIG_LTABLE_STATS */
39037602
A
111
112static int __assert_only
113lt_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);
0a7de745 120 if (e >= b && e < b + table->slab_sz) {
39037602 121 return 1;
0a7de745 122 }
39037602 123 base++;
0a7de745 124 if ((uintptr_t)base >= (uintptr_t)table->table + PAGE_SIZE) {
39037602 125 return 0;
0a7de745 126 }
39037602
A
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 */
0a7de745
A
137void
138lt_elem_invalidate(struct lt_elem *elem)
39037602
A
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)) ||
0a7de745 143 ((lt_bits_type(old) == LT_RESERVED) && !(old & LT_BITS_VALID)));
39037602
A
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 */
0a7de745
A
151void
152lt_elem_mkvalid(struct lt_elem *elem)
39037602
A
153{
154 uint32_t __assert_only old = OSBitOrAtomic(LT_BITS_VALID, &elem->lt_bits);
155 OSMemoryBarrier();
156 assert(!(old & LT_BITS_VALID));
157}
158
0a7de745
A
159static void
160lt_elem_set_type(struct lt_elem *elem, int type)
39037602
A
161{
162 uint32_t old_bits, new_bits;
163 do {
164 old_bits = elem->lt_bits;
165 new_bits = (old_bits & ~LT_BITS_TYPE) |
0a7de745 166 ((type & LT_BITS_TYPE_MASK) << LT_BITS_TYPE_SHIFT);
39037602
A
167 } while (OSCompareAndSwap(old_bits, new_bits, &elem->lt_bits) == FALSE);
168 OSMemoryBarrier();
169}
170
171
39037602
A
172/**
173 * ltable_init: initialize a link table with given parameters
174 *
175 */
0a7de745
A
176void
177ltable_init(struct link_table *table, const char *name,
178 uint32_t max_tbl_elem, uint32_t elem_sz,
179 ltable_poison_func poison)
39037602
A
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! */
0a7de745 189 if ((elem_sz & (elem_sz - 1)) != 0) {
39037602 190 panic("elem_sz:%d for table:'%s' must be a power of two!",
0a7de745
A
191 elem_sz, name);
192 }
39037602
A
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,
0a7de745
A
200 PAGE_SIZE, 0, KMA_NOPAGEWAIT, VM_KERN_MEMORY_LTABLE);
201 if (kr != KERN_SUCCESS) {
39037602 202 panic("Cannot initialize %s table: "
0a7de745
A
203 "kernel_memory_allocate failed:%d\n", name, kr);
204 }
39037602
A
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 *))));
0a7de745 218 if (slab_sz < PAGE_SIZE) {
39037602 219 slab_sz = PAGE_SIZE;
0a7de745 220 }
39037602
A
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;
0a7de745 230 for (uint32_t j = 0; j < i; j++) {
39037602 231 slab_msk |= (1 << j);
0a7de745 232 }
39037602
A
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",
0a7de745 241 name, slab_sz, slab_shift, slab_msk, max_tbl_sz);
f427ee49 242 slab_zone = zone_create(name, slab_sz, ZC_NONE);
39037602
A
243 assert(slab_zone != ZONE_NULL);
244
245 /* allocate the first slab and populate it */
246 base[0] = (struct lt_elem *)zalloc(slab_zone);
0a7de745 247 if (base[0] == NULL) {
39037602 248 panic("Can't allocate a %s table slab from zone:%p",
0a7de745
A
249 name, slab_zone);
250 }
39037602
A
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 */
0a7de745
A
313void
314ltable_grow(struct link_table *table, uint32_t min_free)
39037602
A
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)",
0a7de745 354 table, table->nelem, table->used_elem);
39037602
A
355 }
356 slot = table->next_free_slab;
357 table->next_free_slab++;
0a7de745 358 if ((uintptr_t)table->next_free_slab >= (uintptr_t)table->table + PAGE_SIZE) {
39037602 359 table->next_free_slab = NULL;
0a7de745 360 }
39037602
A
361
362 assert(*slot == NULL);
363
364 /* allocate another slab */
365 slab = (struct lt_elem *)zalloc(table->slab_zone);
0a7de745 366 if (slab == NULL) {
f427ee49
A
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);
0a7de745 370 }
39037602
A
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;
0a7de745 378 if (idx >= (LT_IDX_MAX - 1)) {
39037602 379 break; /* the last element of the last slab */
0a7de745 380 }
39037602
A
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;
0a7de745 392 if (table->nelem + table->slab_elem >= LT_IDX_MAX) {
39037602 393 table->nelem = LT_IDX_MAX - 1;
0a7de745 394 } else {
39037602 395 table->nelem += table->slab_elem;
0a7de745 396 }
39037602
A
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,
0a7de745 411 &table->free_list.id) == FALSE) {
39037602
A
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
d9a64523
A
423#if DEVELOPMENT || DEBUG
424
425int
426ltable_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
39037602
A
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))
0a7de745
A
453struct lt_elem *
454ltable_alloc_elem(struct link_table *table, int type,
455 int nelem, int nattempts)
39037602
A
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
0a7de745 464 if (type != LT_ELEM && type != LT_LINK && type != LT_RESERVED) {
39037602 465 panic("link_table_aloc of invalid elem type:%d from table @%p",
0a7de745
A
466 type, table);
467 }
39037602
A
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
479try_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
0a7de745 492 if (table->used_elem + nelem >= table_size) {
39037602 493 panic("No more room to grow table: 0x%p size:%d, used:%d, requested elem:%d",
0a7de745
A
494 table, table_size, table->used_elem, nelem);
495 }
496 if (nelem == 1) {
39037602 497 panic("Too many alloc retries: %d, table:%p, type:%d, nelem:%d",
0a7de745
A
498 ntries, table, type, nelem);
499 }
39037602
A
500 /* don't panic: try allocating one-at-a-time */
501 while (nelem > 0) {
502 tmp = ltable_alloc_elem(table, type, 1, nattempts);
0a7de745 503 if (elem) {
39037602 504 lt_elem_list_link(table, tmp, elem);
0a7de745 505 }
39037602
A
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 */
0a7de745 525 if (++nspins > 4) {
39037602 526 panic("Can't grow table %p with preemption"
0a7de745
A
527 " disabled!", table);
528 }
39037602
A
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;
0a7de745 538 if (free_id.idx >= table_size) {
39037602 539 goto try_again;
0a7de745 540 }
39037602
A
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);
0a7de745
A
550 nalloc < nelem;
551 nalloc++) {
39037602
A
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,
0a7de745 565 &table->free_list.id) == FALSE) {
39037602 566 goto try_again;
0a7de745 567 }
39037602
A
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 */
0a7de745 592 for (struct lt_elem *tmp = elem;;) {
39037602 593 assert(!lt_bits_valid(tmp->lt_bits) &&
0a7de745 594 (lt_bits_refcnt(tmp->lt_bits) == 0));
39037602
A
595 --nalloc;
596 tmp->lt_id.generation += 1;
597 tmp->lt_bits = 1;
598 lt_elem_set_type(tmp, type);
0a7de745 599 if (tmp->lt_next_idx == LT_IDX_MAX) {
39037602 600 break;
0a7de745 601 }
39037602
A
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;
0a7de745 610 if (type == LT_RESERVED) {
39037602 611 OSIncrementAtomic64(&table->nreservations);
0a7de745 612 }
39037602 613 nreservations = table->nreservations;
0a7de745 614 if (table->used_elem > table->max_used) {
39037602 615 table->max_used = table->used_elem;
0a7de745
A
616 }
617 if (nreservations > table->max_reservations) {
39037602 618 table->max_reservations = nreservations;
0a7de745 619 }
39037602
A
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 */
0a7de745
A
636void
637ltable_realloc_elem(struct link_table *table, struct lt_elem *elem, int type)
39037602
A
638{
639 (void)table;
640 assert(lt_elem_in_range(elem, table) &&
0a7de745 641 !lt_bits_valid(elem->lt_bits));
39037602
A
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 */
0a7de745
A
679static void
680ltable_free_elem(struct link_table *table, struct lt_elem *elem)
39037602
A
681{
682 struct ltable_id next_id;
683
684 assert(lt_elem_in_range(elem, table) &&
0a7de745
A
685 !lt_bits_valid(elem->lt_bits) &&
686 (lt_bits_refcnt(elem->lt_bits) == 0));
39037602
A
687
688 OSDecrementAtomic(&table->used_elem);
689
690#if CONFIG_LTABLE_STATS
691 table->avg_used = (table->avg_used + table->used_elem) / 2;
0a7de745 692 if (lt_bits_type(elem->lt_bits) == LT_RESERVED) {
39037602 693 OSDecrementAtomic64(&table->nreservations);
0a7de745 694 }
39037602
A
695 table->avg_reservations = (table->avg_reservations + table->nreservations) / 2;
696#endif
697
698 elem->lt_bits = 0;
699
0a7de745 700 if (table->poison) {
39037602 701 (table->poison)(table, elem);
0a7de745 702 }
39037602
A
703
704again:
705 next_id = table->free_list;
0a7de745 706 if (next_id.idx >= table->nelem) {
39037602 707 elem->lt_next_idx = LT_IDX_MAX;
0a7de745 708 } else {
39037602 709 elem->lt_next_idx = next_id.idx;
0a7de745 710 }
39037602
A
711
712 /* store barrier */
713 OSMemoryBarrier();
714 if (OSCompareAndSwap64(next_id.id, elem->lt_id.id,
0a7de745 715 &table->free_list.id) == FALSE) {
39037602 716 goto again;
0a7de745 717 }
39037602
A
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 */
0a7de745
A
731struct lt_elem *
732ltable_get_elem(struct link_table *table, uint64_t id)
39037602
A
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
0a7de745 744 if (idx >= table->nelem) {
39037602 745 panic("id:0x%llx : idx:%d > %d", id, idx, table->nelem);
0a7de745 746 }
39037602
A
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;
0a7de745 752 if (!lt_bits_valid(bits)) {
39037602 753 return NULL;
0a7de745 754 }
39037602
A
755
756 /*
757 * do a pre-verify on the element ID to potentially
758 * avoid 2 compare-and-swaps
759 */
0a7de745 760 if (elem->lt_id.id != id) {
39037602 761 return NULL;
0a7de745 762 }
39037602
A
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 /*
0a7de745
A
789 * ltdbg("ID:0x%llx table generation (%d) != %d",
790 * id, elem->lt_id.generation,
791 * ((struct ltable_id *)&id)->generation);
39037602
A
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 */
0a7de745
A
809void
810ltable_put_elem(struct link_table *table, struct lt_elem *elem)
39037602
A
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 */
0a7de745 836 if (!lt_bits_valid(new_bits) && (lt_bits_refcnt(new_bits) == 0)) {
39037602 837 ltable_free_elem(table, elem);
0a7de745 838 }
39037602
A
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 */
0a7de745
A
862int
863lt_elem_list_link(struct link_table *table, struct lt_elem *parent, struct lt_elem *child)
39037602
A
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 */
0a7de745
A
894struct lt_elem *
895lt_elem_list_first(struct link_table *table, uint64_t id)
39037602
A
896{
897 uint32_t idx;
898 struct lt_elem *elem = NULL;
899
0a7de745 900 if (id == 0) {
39037602 901 return NULL;
0a7de745 902 }
39037602
A
903
904 idx = ((struct ltable_id *)&id)->idx;
905
0a7de745 906 if (idx > table->nelem) {
39037602 907 panic("Invalid element for id:0x%llx", id);
0a7de745 908 }
39037602
A
909 elem = lt_elem_idx(table, idx);
910
911 /* invalid element: reserved ID was probably already reallocated */
0a7de745 912 if (elem->lt_id.id != id) {
39037602 913 return NULL;
0a7de745 914 }
39037602
A
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",
0a7de745 921 elem, elem->lt_bits);
39037602
A
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 */
0a7de745
A
933struct lt_elem *
934lt_elem_list_next(struct link_table *table, struct lt_elem *head)
39037602
A
935{
936 struct lt_elem *elem;
937
0a7de745 938 if (!head) {
39037602 939 return NULL;
0a7de745
A
940 }
941 if (head->lt_next_idx >= table->nelem) {
39037602 942 return NULL;
0a7de745 943 }
39037602
A
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 */
0a7de745
A
959struct lt_elem *
960lt_elem_list_break(struct link_table *table, struct lt_elem *elem)
39037602
A
961{
962 struct lt_elem *next;
963
0a7de745 964 if (!elem) {
39037602 965 return NULL;
0a7de745 966 }
39037602
A
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 */
0a7de745
A
983struct lt_elem *
984lt_elem_list_pop(struct link_table *table, uint64_t *id, int type)
39037602
A
985{
986 struct lt_elem *first, *next;
987
0a7de745 988 if (!id || *id == 0) {
39037602 989 return NULL;
0a7de745 990 }
39037602
A
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);
0a7de745 1001 if (next) {
39037602 1002 *id = next->lt_id.id;
0a7de745 1003 } else {
39037602 1004 *id = 0;
0a7de745 1005 }
39037602
A
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 */
0a7de745
A
1019int
1020lt_elem_list_release(struct link_table *table, struct lt_elem *head,
1021 int __assert_only type)
39037602
A
1022{
1023 struct lt_elem *elem;
1024 struct ltable_id free_id;
1025 int nelem = 0;
1026
0a7de745 1027 if (!head) {
39037602 1028 return 0;
0a7de745 1029 }
39037602 1030
0a7de745 1031 for (elem = head;;) {
39037602
A
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;
0a7de745 1038 if (table->poison) {
39037602 1039 (table->poison)(table, elem);
0a7de745 1040 }
39037602 1041
0a7de745 1042 if (elem->lt_next_idx == LT_IDX_MAX) {
39037602 1043 break;
0a7de745 1044 }
39037602
A
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
1056again:
1057 free_id = table->free_list;
0a7de745 1058 if (free_id.idx >= table->nelem) {
39037602 1059 elem->lt_next_idx = LT_IDX_MAX;
0a7de745 1060 } else {
39037602 1061 elem->lt_next_idx = free_id.idx;
0a7de745 1062 }
39037602
A
1063
1064 /* store barrier */
1065 OSMemoryBarrier();
1066 if (OSCompareAndSwap64(free_id.id, head->lt_id.id,
0a7de745 1067 &table->free_list.id) == FALSE) {
39037602 1068 goto again;
0a7de745 1069 }
39037602
A
1070
1071 OSAddAtomic(-nelem, &table->used_elem);
1072 return nelem;
1073}