Thursday, September 1, 2022

[SOLVED] How to implement MAP_HUGETLB in a character device driver?

Issue

I have a character driver exposing a character device file under /dev. I'd like to use the huge pages when I map some menory.

MAP_HUGETLB seems to be only available when grouped with MAP_ANONYMOUS or with transparent huge-page but am not interested in it.

mmap(...,MAP_HUGETLB|MAP_ANONYMOUS,..., -1, 0);

How can we implement the huge-pages feature for a character device? Is it already done somewhere?

I didn't find an example the kernel's tree.


Solution

This isn't possible. You can only mmap files with MAP_HUGETLB if they reside in a hugetlbfs filesystem. Since /proc is a procfs filesystem, you have no way of mapping those files through huge pages.

You can also see this from the checks performed in mmap by the kernel:

    /* ... */

    if (!(flags & MAP_ANONYMOUS)) { // <== File-backed mapping?
        audit_mmap_fd(fd, flags);
        file = fget(fd);
        if (!file)
            return -EBADF;
        if (is_file_hugepages(file)) { // <== Check that FS is hugetlbfs
            len = ALIGN(len, huge_page_size(hstate_file(file)));
        } else if (unlikely(flags & MAP_HUGETLB)) { // <== If not, MAP_HUGETLB isn't allowed
            retval = -EINVAL;
            goto out_fput;
        }
    } else if (flags & MAP_HUGETLB) { // <== Anonymous MAP_HUGETLB mapping?

    /* ... */

See also:



Answered By - Marco Bonelli
Answer Checked By - Clifford M. (WPSolving Volunteer)