Skip to main content

Two questions about copy_pte_range() in kernel [Resolved]

I've been trying to understand how fork() works and finally arrived at copy_pte_range(). Most of the functions are understandable but few are quite questionable.

Kernel: 4.14.84

static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
           pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
           unsigned long addr, unsigned long end)
    pte_t *orig_src_pte, *orig_dst_pte;
    pte_t *src_pte, *dst_pte;
    spinlock_t *src_ptl, *dst_ptl;
    int progress = 0;
    int rss[NR_MM_COUNTERS];
    swp_entry_t entry = (swp_entry_t){0};


    dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
    if (!dst_pte)
        return -ENOMEM;
    src_pte = pte_offset_map(src_pmd, addr);
    src_ptl = pte_lockptr(src_mm, src_pmd);
    spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
    orig_src_pte = src_pte;
    orig_dst_pte = dst_pte;

    do {
         * We are holding two locks at this point - either of them
         * could generate latencies in another task on another CPU.
        if (progress >= 32) {
            progress = 0;
            if (need_resched() ||
                spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
        if (pte_none(*src_pte)) {
        entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
                            vma, addr, rss);
        if (entry.val)
        progress += 8;
    } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);

    add_mm_rss_vec(dst_mm, rss);
    pte_unmap_unlock(orig_dst_pte, dst_ptl);

    if (entry.val) {
        if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
            return -ENOMEM;
        progress = 0;
    if (addr != end)
        goto again;
    return 0;

1. In the do {} while(), what is the purpose of progress variable?
2. After do {} while(), there is pte_unmap(orig_src_pte); Why is it needed? This is the process of fork(). Based on my knowledge, the parent pte(orig_src_pte) should still be mapped because the process is based on Copy-on-Write so I guess it doesn't have to be unmapped.

Question Credit: Mr.Nobody
Question Reference
Asked March 23, 2019
Tags: linux, kernel
Posted Under: Unix Linux
1 Answers

  1. The progress variable measures the cost of the operations performed under locks, and avoids holding those locks for too long. At most every 32 calls to pte_none, or 4 calls to copy_one_pte (which is expensive), or a combination thereof, the function checks whether a reschedule is needed, or if the locks are requested elsewhere; if so, it releases the locks and allows a reschedule. The function continues where it left off, thanks to the jump to again.

  2. The unmap call doesn’t unmap the original PTE in the source process, it undoes the effects of the src_pte = pte_offset_map(src_pmd, addr); line at the start of the function.

credit: Stephen Kitt
Answered March 23, 2019
Your Answer