简体   繁体   English

Linux kernel 中的零页是什么?

[英]What is zeroed page in Linux kernel?

In Linux kernel, what does 'zeroed page' actually mean?在 Linux kernel 中,“归零页面”实际上是什么意思? 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):归零页面是页面中的所有位都设置为 0 的页面。并非所有归零页面都是空闲的,也不是所有空闲页面都必须归零(特定于实现):

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.当进程使用malloc()然后执行读取(在 Ubuntu 20.04 中测试)时,分配的 memory 全部为零,但是,当然,此时页面不是空闲的。 I wrote this C program to verify:我写了这个 C 程序来验证:

#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 .正如@0andriy 在评论中所指出的,我使用calloc的原始示例是使用“零页面”实现的,一个充满零的页面,所有 calloc 都可以使用此处描述的写时复制优化返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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