Search code examples
coperating-systemriscvxv6

What does madvise() do in virtual memory?


Following code was excuted in xv6(risc-v). I'm little confused. WHy we need to madvise() after malloc()? Is it for page table entry swaping in/out?

PS. vmprint() print the page table.

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/vm.h"

#define PG_SIZE 4096
#define NR_PG 16

int main(int argc, char *argv[]) {
  vmprint();
  char *ptr = malloc(NR_PG * PG_SIZE);
  vmprint();
  madvise((uint64) ptr + 10*PG_SIZE, 2*PG_SIZE , MADV_NORMAL);
  vmprint();
  madvise((uint64) ptr + 10*PG_SIZE, 2*PG_SIZE , MADV_DONTNEED);
  vmprint();
  madvise((uint64) ptr + 10*PG_SIZE, 2*PG_SIZE , MADV_WILLNEED);
  vmprint();
  exit(0);
}

Solution

  • After allocating this memory block by malloc() function, the madvise() function is used to advise the kernel about the usage of specific memory regions.

    • The first madvise() call advises the kernel that the memory region starting at ptr + 10*PG_SIZE and extending for 2*PG_SIZE bytes should be treated as MADV_NORMAL, indicating normal memory access patterns. This call doesn't cause any immediate change to memory allocation.

    • The second indicated that the specified memory range can be discarded if it's not in use.

    • And the third, indicated that the specified memory range will be accessed soon, so the kernel can proactively bring the pages into memory to minimize latency when accessing them.