• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022, sakumisu
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #ifndef USB_MEM_H
7 #define USB_MEM_H
8 
9 #define USB_MEM_ALIGNX __attribute__((aligned(CONFIG_USB_ALIGN_SIZE)))
10 
11 #if (CONFIG_USB_ALIGN_SIZE > 4)
usb_iomalloc(size_t size)12 static inline void *usb_iomalloc(size_t size)
13 {
14     void *ptr;
15     void *align_ptr;
16     int uintptr_size;
17     size_t align_size;
18     uint32_t align = CONFIG_USB_ALIGN_SIZE;
19 
20     /* sizeof pointer */
21     uintptr_size = sizeof(void *);
22     uintptr_size -= 1;
23 
24     /* align the alignment size to uintptr size byte */
25     align = ((align + uintptr_size) & ~uintptr_size);
26 
27     /* get total aligned size */
28     align_size = ((size + uintptr_size) & ~uintptr_size) + align;
29     /* allocate memory block from heap */
30     ptr = usb_malloc(align_size);
31     if (ptr != NULL) {
32         /* the allocated memory block is aligned */
33         if (((unsigned long)ptr & (align - 1)) == 0) {
34             align_ptr = (void *)((unsigned long)ptr + align);
35         } else {
36             align_ptr = (void *)(((unsigned long)ptr + (align - 1)) & ~(align - 1));
37         }
38 
39         /* set the pointer before alignment pointer to the real pointer */
40         *((unsigned long *)((unsigned long)align_ptr - sizeof(void *))) = (unsigned long)ptr;
41 
42         ptr = align_ptr;
43     }
44 
45     return ptr;
46 }
47 
usb_iofree(void * ptr)48 static inline void usb_iofree(void *ptr)
49 {
50     void *real_ptr;
51 
52     real_ptr = (void *)*(unsigned long *)((unsigned long)ptr - sizeof(void *));
53     usb_free(real_ptr);
54 }
55 #else
56 #define usb_iomalloc(size) usb_malloc(size)
57 #define usb_iofree(ptr)    usb_free(ptr)
58 #endif
59 
60 #endif /* USB_MEM_H */
61