12 #include <psp2/kernel/sysmem.h>
16 #define FOUR_KB_ALIGN(x) align(x, 12)
17 #define MB_ALIGN(x) align(x, 20)
23 static inline int align(int x, int n)
25 return (((x >> n) + 1) << n);
28 static thread_local unsigned long co_active_buffer[64];
29 static thread_local cothread_t co_active_handle = 0;
30 static void(*co_swap)(cothread_t, cothread_t) = 0;
32 static uint32_t co_swap_function[] = {
33 0xe8a16ff0, /* stmia r1!, {r4-r11,sp,lr} */
34 0xe8b0aff0, /* ldmia r0!, {r4-r11,sp,pc} */
35 0xe12fff1e, /* bx lr */
38 static void co_init(void)
43 block = sceKernelAllocMemBlockForVM("libco",
44 MB_ALIGN(FOUR_KB_ALIGN(sizeof co_swap_function)));
48 /* Get base address */
49 if ((ret = sceKernelGetMemBlockBase(block, &base)) < 0)
52 /* Set domain to be writable by user */
53 if ((ret = sceKernelOpenVMDomain()) < 0)
56 memcpy(base, co_swap_function, sizeof co_swap_function);
58 /* Set domain back to read-only */
59 if ((ret = sceKernelCloseVMDomain()) < 0)
63 ret = sceKernelSyncVMDomain(block, base,
64 MB_ALIGN(FOUR_KB_ALIGN(sizeof co_swap_function)));
68 co_swap = (void(*)(cothread_t, cothread_t))base;
71 cothread_t co_active(void)
73 if (!co_active_handle)
74 co_active_handle = &co_active_buffer;
75 return co_active_handle;
78 cothread_t co_create(unsigned int size, void(*entrypoint)(void))
80 unsigned long* handle = 0;
83 if (!co_active_handle)
84 co_active_handle = &co_active_buffer;
88 if ((handle = (unsigned long*)malloc(size)))
90 unsigned long *p = (unsigned long*)((unsigned char*)handle + size);
91 handle[8] = (unsigned long)p;
92 handle[9] = (unsigned long)entrypoint;
98 void co_delete(cothread_t handle)
101 sceKernelFreeMemBlock(block);
104 void co_switch(cothread_t handle)
106 cothread_t co_previous_handle = co_active_handle;
107 co_swap(co_active_handle = handle, co_previous_handle);