← Back to C-Kernel-Engine Docs Doxygen Source Documentation
ckernel_alloc.h File Reference
#include <stddef.h>

Go to the source code of this file.

Functions

void * ck_huge_alloc (size_t bytes)
 
void ck_huge_free (void *ptr, size_t bytes)
 

Function Documentation

◆ ck_huge_alloc()

void* ck_huge_alloc ( size_t  bytes)

Allocate a large, contiguous memory region for model weights/activations.

Implementation strategy:

  • Try to allocate 2MB-aligned memory backed by huge pages where possible.
  • Fall back to aligned_alloc + madvise(MADV_HUGEPAGE) when explicit huge pages are not available.

Returns NULL on failure.

Definition at line 67 of file ckernel_alloc.c.

68 {
69  size_t len = align_up_bytes(bytes, HUGE_PAGE_SIZE);
70 
71  /* First, try explicit huge pages via mmap + MAP_HUGETLB. */
72  void *p = mmap(NULL, len,
73  PROT_READ | PROT_WRITE,
74  MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB,
75  -1, 0);
76  if (p != MAP_FAILED) {
77  if (!record_allocation(p, len, 1)) {
78  munmap(p, len);
79  return NULL;
80  }
81  return p;
82  }
83 
84  /* Fallback: aligned_alloc with transparent hugepage hint. */
85  void *q = aligned_alloc(HUGE_PAGE_SIZE, len);
86  if (!q) {
87  fprintf(stderr, "ck_huge_alloc: aligned_alloc failed for %zu bytes: %s\n",
88  len, strerror(errno));
89  return NULL;
90  }
91 
92  /* Best-effort hint; ignore errors. */
93  (void)madvise(q, len, MADV_HUGEPAGE);
94  if (!record_allocation(q, len, 0)) {
95  free(q);
96  return NULL;
97  }
98  return q;
99 }
static size_t align_up_bytes(size_t n, size_t align)
Definition: ckernel_alloc.c:28
static int record_allocation(void *ptr, size_t len, int was_mmap)
Definition: ckernel_alloc.c:34
#define HUGE_PAGE_SIZE
Definition: ckernel_alloc.c:15

References align_up_bytes(), HUGE_PAGE_SIZE, and record_allocation().

◆ ck_huge_free()

void ck_huge_free ( void *  ptr,
size_t  bytes 
)

Free memory allocated by ck_huge_alloc.

The bytes parameter should be the same size passed to ck_huge_alloc.

Definition at line 101 of file ckernel_alloc.c.

102 {
103  if (!ptr || bytes == 0) {
104  return;
105  }
106 
107  ck_huge_alloc_entry_t *entry = detach_allocation(ptr);
108  if (!entry) {
109  /* Fall back to malloc/free if the allocation wasn't tracked. */
110  free(ptr);
111  return;
112  }
113 
114  if (entry->was_mmap) {
115  munmap(ptr, entry->len);
116  } else {
117  free(ptr);
118  }
119 
120  free(entry);
121 }
static ck_huge_alloc_entry_t * detach_allocation(void *ptr)
Definition: ckernel_alloc.c:50

References detach_allocation().