简体   繁体   中英

What is zeroed page in Linux kernel?

In Linux kernel, what does 'zeroed page' actually mean? I have tried corelate it with free pages but it does not make a lot of sense.

Zeroed pages are pages where all bits in the page are set to 0. Not all zeroed pages are free, nor are all free pages necessarily zeroed (implementation specific):

A free page doesn't necessarily mean it is zeroed. It could be a page that is set to invalid (not in use by any process), but has old data from when it was last used. For security reasons, the OS should zero out pages before giving it to another program.

A zeroed page also doesn't mean it's a free page. When a process uses malloc() and then does a read (tested in Ubuntu 20.04), the memory that is allocated is all zeros, but, of course, at this point the page is not free. I wrote this C program to verify:

#include <stdio.h>
#include <stdlib.h>

#define PAGE_SIZE 4096
int num_pages = 32;

int main(){
    int i; 
    int bytes = num_pages * PAGE_SIZE;
    char * test = (char *)malloc(bytes);
    if (test == NULL){
        printf("Malloc failed.\n");
        return -1;
    }
 
    for(i =0; i < bytes; i++){
        // A zeroed page will have all (char) zeros in it
        if (test[i] != (char) 0)
            printf("Not (char) 0: %c\n", test[i]);
    }
    return 0;
}

As pointed out in the comments by @0andriy, my original example using calloc is implemented using the "Zero page", a single page filled with zeroes that all callocs can return using the copy-on-write optimization described here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM