Полезная информация

next up previous contents
Next: Character vs. block devices Up: Device Driver Basics Previous: Namespace

Allocating memory

Memory allocation in the kernel is a little different from memory allocation in normal user-level programs. Instead of having a malloc() capable of delivering almost unlimited amounts of memory, there is a kmalloc() function that is a bit different:

To free memory allocated with kmalloc(), use one of two functions: kfree() or kfree_s(). These differ from free() in a few ways as well: See section gif for more information on kmalloc(), kfree(), and other useful functions.

The other way to acquire memory is to allocate it at initialization time. Your initialization function, foo_init(), takes one argument, a pointer to the current end of memory. It can take as much memory as it wants to, save a pointer or pointers to that memory, and return a pointer to the new end of memory. The advantage of this over statically allocating large buffers (char bar[20000]) is that if the foo driver detects that the foo device is not attached to the computer, the memory is not wasted. The init() function is discussed in Section gif.

Be gentle when you use kmalloc. Use only what you have to. Remember that kernel memory is unswappable, and thus allocating extra memory in the kernel is a far worse thing to do in the kernel than in a user-level program. Take only what you need, and free it when you are done, unless you are going to use it right away again.

[I believe that it is possible to allocate swappable memory with the vmalloc function, but that will be documented in the VMM section when it gets written. In the meantime, enterprising hackers are encouraged to look it up themselves.]


next up previous contents
Next: Character vs. block devices Up: Device Driver Basics Previous: Namespace

Converted on:
Mon Apr 1 10:20:16 EST 1996