Search code examples
linuxmemory-managementprocesslinux-kernelvirtual-address-space

When a user process swaps out a page, is the virtual address of the page in user space or kernel space?


I am a beginner in Linux and have always been confused about the difference between kernel space and user space. I am currently researching memory management and would like to know if the virtual address of a page of a user process belongs to user space or kernel space when swapping in or out?

(as in 64 bit Linux

User state virtual address range: 0x0000000 000000-0x00007FFFFFFFFFFFFF

Kernel state virtual address range: 0xFFFF8000000000-0xFFFFFFFFFFFFFFFFFFFF)

linux-6.5.1/mm/memory.c

mm_account_fault()
    if (major) {
        struct major_page_fault_hash_entry *temp = NULL;
        unsigned long pfn = virt_to_pfn(address);
        printk("[%lu][i][%lu]", pfn, address);
        perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
    }

linux-6.5.1/mm/swap_state.c

bool add_to_swap(struct folio *folio)
    long pages_number = folio_nr_pages(folio);
    unsigned long start_pfn = folio_pfn(folio);

    for (int i = 0; i < pages_number; i++) {
        struct page *current_page = pfn_to_page(start_pfn + i);
        unsigned long current_virt_addr = (unsigned long)page_to_virt(current_page);
        printk("[%lu][o][%lu]\n",start_pfn + i, current_virt_addr);
    }

Solution

  • You are printing a user virtual address (and the PFN it is pointing to) on fault, and a kernel virtual address (and the PFN it is pointing to) on add_to_swap(). It doesn't make much sense to compare the two things.

    A physical memory page can have any number of virtual addresses pointing to it, both in kernel and in user space, at any moment. Furthermore, a page can be moved around in physical memory and its PFN can change over time. A page being swapped out only means that the bits of its page table entry will be updated to indicate that the page is swapped, so that it can be correctly swapped in on the next page fault. No change of existing user virtual addresses will occur or can occur.


    My purpose in collecting these data is to check if the same page has been swapped in and out multiple times during a user process

    You should be able to do this from userspace through /proc/[pid]/pagemap. See the documentation here. In particular, bit 62 tells you whether the page is swapped or not, so if you can query that bit often enough you can get the information you want.