KMEM(9) | Kernel Developer's Manual | KMEM(9) |
void *
kmem_alloc(size_t size, km_flag_t kmflags);
void *
kmem_zalloc(size_t size, km_flag_t kmflags);
void
kmem_free(void *p, size_t size);
char *
kmem_asprintf(const char *fmt, ...);
options DEBUG
In situations where it is not possible to sleep, for example because locks are held by the caller, the code path should be restructured to allow the allocation to be made in another place.
The contents of allocated memory are uninitialized.
Unlike Solaris, kmem_alloc(0, flags) is illegal.
kmem_zalloc() is the equivalent of kmem_alloc(), except that it initializes the memory to zero.
kmem_asprintf() functions as the well known asprintf() function, but allocates memory using kmem_alloc(). This routine can sleep during allocation. The size of the allocated area is the length of the returned character string, plus one (for the NUL terminator). This must be taken into consideration when freeing the returned area with kmem_free().
kmem_free() frees kernel wired memory allocated by kmem_alloc() or kmem_zalloc() so that it can be used for other purposes. It takes the following arguments.
Freeing NULL is illegal.
For some locks this is permissible or even unavoidable. For others, particularly locks that may be taken from soft interrupt context, it is a serious problem. As a general rule it is better not to allow this type of situation to develop. One way to circumvent the problem is to make allocations speculative and part of a retryable sequence. For example:
retry: /* speculative unlocked check */ if (need to allocate) { new_item = kmem_alloc(sizeof(*new_item), KM_SLEEP); } else { new_item = NULL; } mutex_enter(lock); /* check while holding lock for true status */ if (need to allocate) { if (new_item == NULL) { mutex_exit(lock); goto retry; } consume(new_item); new_item = NULL; } mutex_exit(lock); if (new_item != NULL) { /* did not use it after all */ kmem_free(new_item, sizeof(*new_item)); }
kmguard adds additional, very high overhead runtime verification to kmem operations. To enable it, boot the system with the -d option, which causes the debugger to be entered early during the kernel boot process. Issue commands such as the following:
db> w kmem_guard_depth 0t30000 db> c
This instructs kmguard to queue up to 60000 (30000*2) pages of unmapped KVA to catch use-after-free type errors. When kmem_free() is called, memory backing a freed item is unmapped and the kernel VA space pushed onto a FIFO. The VA space will not be reused until another 30k items have been freed. Until reused the kernel will catch invalid accesses and panic with a page fault. Limitations:
kmguard tries to catch the following types of bugs:
June 14, 2011 | NetBSD 6.1 |