Page 1 of 1

[SOLVED] Implementing mmap() and munmap()

Posted: Tue Aug 20, 2013 9:05 pm
by narke
Hi,

I'm in the process of porting of dlmalloc to my kernel.
dlmalloc needs that one provide sbrk() function or mmap() and munmap() to operate correctly.

I decided to implement mmap() and munmap() but I want to be sure that I correctly understood how they work.
So, I think that it's like:
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
1. Allocate number of physical pages corresponding to length / PAGE_SIZE.
2. Find a suitable memory range in the virtual memory (heap)
3. Map each physical page address to a virtual address accordingly to provided protection flags (read, write, exec)

Am I right or did I forgot some steps?

Re: Implementing mmap() and munmap()

Posted: Wed Aug 21, 2013 4:43 am
by sortie
How about the step where you memory map the requested map if not MAP_ANONYMOUS? Or when you zero out the newly allocated memory?

Re: Implementing mmap() and munmap()

Posted: Wed Aug 21, 2013 5:08 am
by bluemoon
The POSIX mmap is a high level function. It's quite common to have several lower level API, for example:
1. to map a specific physical address onto logical address
2. to some physical memory onto virtual address, so it can be accessed.
3. heap management, to allocate some virtual address out of heap zones.

for sbrk, the easiest way is maintain a tail pointer from the heap, and expand by invoke mmap to map memory on the following address. ie. a combined usage of 2 and 3.

For example, my heap function (serve as sbrk for kernel):

Code: Select all

void* heap_alloc ( HEAP* heap, size_t size ) {
    size_t from, to;
    void* mem;
    if ( heap->ptr + size >= heap->size ) return 0;
    if (( heap->flag & HEAP_ADDRESSONLY ) == 0 ) {
        from = ((heap->start + heap->ptr)>>12)<<12;
        to   = ((heap->start + heap->ptr + size + 4095)>>12)<<12;
        if ( to > from ) {
	    // int MMU_mmap (void* mem, MMU_PADDR paddr, size_t size, unsigned int flag);
            MMU_mmap ( (void*)from, 0, (to-from), heap->flag & 0xFFFF );
        }
    }
    mem = (void*) (heap->start + heap->ptr);
    heap->ptr += size;
    return mem;    
}

Re: Implementing mmap() and munmap()

Posted: Wed Aug 21, 2013 2:07 pm
by narke
Thank you guys.
I did it, at least at a minimal level, it's not fully tested but shouldn't be too bad.

Main source tree: https://github.com/narke/Roentgenium
Most of the stuff is here: https://github.com/narke/Roentgenium/tr ... ry_manager