Messages in this thread | | | Date | Fri, 4 Sep 1998 19:59:19 +0200 | Subject | Re:Kernel programming Q: new aligned memory | From | Inaky Perez Gonzalez <> |
| |
>>>>> "B" == B James Phillippe <bryan@terran.org> writes:
B> Hello Kernel Gurus, I'm wondering what is the best way to align a B> chunk of kernel memory (from kmalloc, say) on a particular byte B> boundary. 16 bytes, for instance.
I had the same problem; however, I noticed everything was using a power-of-two chunk allocation scheme, so I did a dirty function [__usb_kmalloc_align]:
#define MAX_LEVELS 16
void* __usb_kmalloc_align_r (size_t size, int alignment, int prio, int depth) { void *ptr, *rptr;
if (depth > MAX_LEVELS) return NULL; ptr = kmalloc (size < alignment? alignment : size, prio); if (((unsigned long)ptr & (alignment-1)) != 0) { rptr = __usb_kmalloc_align_r (size, alignment, prio, depth+1); usb_kfree (ptr); ptr = rptr; }
return ptr; }
void* __usb_kmalloc_align (size_t size, int alignment, int prio) { void* ptr; void* rptr; ptr = kmalloc (size < alignment? alignment : size, prio); if (((unsigned long)ptr & (alignment-1)) != 0) { rptr = __usb_kmalloc_align_r (size, alignment, prio, 0); usb_kfree (ptr); ptr = rptr; } return ptr; }
The point is, if the size of the object is smaller then the alignment, ask for a chunk sized as the alignment, else the size. The rounding to the next power of two will do the same when allocating.
I've successfully allocated _everyone_ of them, even under heavy load, but I am not sure it will always success. So I implemented a workaround for the case it failed.
If not aligned, it will recursively allocate more chunks, until one falls into the wanted alignment; then it will free them and let you with the aligned one. It's ugly, but it works. There's a depth limit, just in case ...
It's dirty, could be optimized, etc, etc ... but hey, I did it in five minutes :)
Linux-USB! http://peloncho.fis.ucm.es/~inaky/USB.html - - Inaky Perez Gonzalez -- PGP pubkey fingerprint - inaky@peloncho.fis.ucm.es -- 8E 34 3A 62 64 99 E2 44 - http://peloncho.fis.ucm.es/~inaky -- AD 7B 30 D9 DD FF 3E 4C - --------------------------------- -- ----------------------- - The loneliness of the long distance runner .....
- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/faq.html
| |