0 Replies Latest reply on Jul 28, 2009 12:34 PM by 807567

    mmap MAP_ANON allocation algorithm

    807567
      Hi all,

      I tried to run 'mmap' in cycle until the address space is exhausted by requesting 512k of anonymous memory each time. The program is as follows:
      #include <stdio.h>
      #include <stdlib.h>
      #include <sys/types.h>
      #include <sys/mman.h>
      #include <fcntl.h>
      #include <unistd.h>
      
      #define BLOCK_SIZE 524288
      
      int main(int argc, char *argv[])
      {
              unsigned int            i;
              unsigned long int       s;
              int                     *ptr;
      
              for (i = 0; 1; i++)
              {
                      ptr = (void*)mmap((caddr_t) 0,
                                       BLOCK_SIZE,
                                       (PROT_READ | PROT_WRITE),
                                       MAP_PRIVATE|MAP_ANON,
                                       -1,
                                       (off_t)0);
                      if (ptr == MAP_FAILED)
                      {
                              perror("mmap");
                              printf ("Allocated %d Mb\n", (BLOCK_SIZE * i) / (1024*1024));
                              exit(-1);
                      }
                      else
                              printf("%08x\n", ptr);
              }
              return 0;
      }
      I have the following result:
      $./a.out
      ff180000
      ff080000
      fef80000
       ....
      00380000
      00280000
      00180000
      00080000
      mmap: Not enough space
      Allocated 2041 Mb
      The distance between each virtual memory address returned is 1048576b (=1Mb) while my pagesize is configured at 8kb.

      Would you know why the delta between addresses is not 524288? What am I missing?
      I ran it in a 32bit program using solaris 64bit kernel.The same test with Linux 32bit showed the results I expected (allocations of 512Kb whe requesting 512Kb).

      I also did some tests with different values. The best value to allocate the most memory seems to be something like 112k. (3571 Mb allocated in total).      

      Thanks,
      Christian Bodt