/* * nzmalloc-test by Davide Libenzi (test program for MAP_NOZERO) * Copyright (C) 2007 Davide Libenzi * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Davide Libenzi * */ #include #include #include #include #include #define DEFAULT_SIZE (sysconf(_SC_PAGESIZE) * 64) static int page_is_zero(void *page, unsigned int pgsize) { unsigned long *p, *top; p = page; top = page + pgsize; /* * Write-fault the page before, otherwise you get ZERO_PAGE plus * copy_page() behaviour ... */ *p++ = 1; for (; p < top; p++) if (*p) return 0; ((unsigned long *) page)[1] = 2; return 1; } static int test_malloc(unsigned int size) { unsigned int pgsize, nzcount; char *addr, *p, *top; pgsize = sysconf(_SC_PAGESIZE); size = ((size + pgsize - 1) / pgsize) * pgsize; if ((addr = malloc(size)) == NULL) { perror("malloc"); return -1; } for (p = addr, top = addr + size, nzcount = 0; p < top; p += pgsize) { if (!page_is_zero(p, pgsize)) nzcount++; } free(addr); fprintf(stdout, "mapping had %u non-zero pages\n", nzcount); return 0; } int main(int ac, char **av) { int i; unsigned int size = DEFAULT_SIZE; while ((i = getopt(ac, av, "s:h")) != -1) { switch (i) { case 's': size = atoi(optarg); break; case 'h': break; } } test_malloc(size); return 0; }