1 #include <lunaix/mm/mmap.h>
2 #include <lunaix/mm/pmm.h>
3 #include <lunaix/mm/region.h>
4 #include <lunaix/mm/valloc.h>
5 #include <lunaix/mm/vmm.h>
6 #include <lunaix/spike.h>
8 #include <lunaix/syscall.h>
12 struct llist_header* regions,
19 if (!length || (length & (PG_SIZE - 1)) || (offset & (PG_SIZE - 1))) {
20 __current->k_status = EINVAL;
24 // read_page is not supported
25 if (!file->ops->read_page) {
26 __current->k_status = ENODEV;
30 ptr_t last_end = USER_START;
31 struct mm_region *pos, *n;
32 llist_for_each(pos, n, regions, head)
34 if (pos->start - last_end >= length && last_end >= addr) {
40 __current->k_status = ENOMEM;
45 ptr_t end = addr + length;
47 struct mm_region* region = region_add(regions, addr, end, proct);
49 region->offset = offset;
51 u32_t attr = PG_ALLOW_USER;
52 if ((proct & REGION_WRITE)) {
56 for (u32_t i = 0; i < length; i += PG_SIZE) {
57 vmm_set_mapping(mnt, addr + i, 0, attr, 0);
64 mem_unmap(ptr_t mnt, struct llist_header* regions, void* addr, size_t length)
66 length = ROUNDUP(length, PG_SIZE);
67 ptr_t cur_addr = ROUNDDOWN((ptr_t)addr, PG_SIZE);
68 struct mm_region *pos, *n;
70 llist_for_each(pos, n, regions, head)
72 if (pos->start >= cur_addr) {
77 while (&pos->head != regions && cur_addr > pos->start) {
78 u32_t l = pos->end - cur_addr;
82 // unmap cause discontinunity in a memory region - do split
83 struct mm_region* region = valloc(sizeof(struct mm_region));
85 region->start = cur_addr + length;
86 llist_insert_after(&pos->head, ®ion->head);
90 for (size_t i = 0; i < l; i += PG_SIZE) {
91 ptr_t pa = vmm_del_mapping(mnt, cur_addr + i);
93 pmm_free_page(__current->pid, pa);
97 n = container_of(pos->head.next, typeof(*pos), head);
98 if (pos->end == pos->start) {
99 llist_delete(&pos->head);
109 __DEFINE_LXSYSCALL5(void*,
124 if ((errno = vfs_getfd(fd, &vfd))) {
125 __current->k_status = errno;
129 return mem_map(PD_REFERENCED,
130 &__current->mm.regions,
138 __DEFINE_LXSYSCALL2(void, munmap, void*, addr, size_t, length)
140 return mem_unmap(PD_REFERENCED, &__current->mm.regions, addr, length);