kmem_alloc(9) - NetBSD Manual Pages

KMEM_ALLOC(9)          NetBSD Kernel Developer's Manual          KMEM_ALLOC(9)


NAME
kmem_alloc -- allocate kernel wired memory
SYNOPSIS
#include <sys/kmem.h> void * kmem_alloc(size_t size, km_flag_t kmflags);
DESCRIPTION
kmem_alloc() allocates kernel wired memory. It takes the following argu- ments. size Specify the size of allocation in bytes. kmflags Either of the following: KM_SLEEP If the allocation cannot be satisfied immediatley, sleep until enough memory is available. KM_NOSLEEP Don't sleep. Immediately return NULL if there is not enough memory available. It should only be used when failure to allocate will not have harmful, user-visible effects. Use of KM_NOSLEEP is strongly discouraged as it can create transient, hard to debug failures that occur when the system is under memory pressure. 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 allo- cation to be made in another place. The contents of allocated memory are uninitialized. Unlike Solaris, kmem_alloc(0, flags) is illegal. Making KM_SLEEP allocations while holding mutexes or reader/writer locks is discouraged, as the caller can sleep for an unbounded amount of time in order to satisfy the allocation. This can in turn block other threads that wish to acquire locks held by the caller. For some locks this is permissible or even unavoidable. For others, par- ticularly 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)); }
RETURN VALUES
On success, kmem_alloc() returns a pointer to allocated memory. Other- wise, it returns NULL.
SEE ALSO
intro(9), kmem_free(9), kmem_zalloc(9), malloc(9), memoryallocators(9)
CAVEATS
kmem_alloc() cannot be used from interrupt context, from a soft inter- rupt, or from a callout. Use pool_cache(9) in these situations.
SECURITY CONSIDERATION
As the allocated memory is uninitialized, it can contain security-sensi- tive data left by its previous user. It's the caller's responsibility not to expose it to the world. NetBSD 5.2 December 29, 2008 NetBSD 5.2

Powered by man-cgi (2024-08-26). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.