Memory Protection Keys Support Finished Up In Linux 4.9

Written by Michael Larabel in Linux Kernel on 8 October 2016 at 11:17 AM EDT. 1 Comment
This morning the protection keys syscall interface was submitted for the Linux 4.9 merge window, the last step of adding Protection Keys support to the Linux kernel.

The added interface allows user-space to allocate keys and protect memory areas with said keys. This Memory Protection Keys (MPK) support has been a long-time coming and is supported by future Intel CPUs. Details on this Intel memory protection feature are described in this earlier article. There's also been related protection key changes to the GCC and LLVM/Clang compilers.

Simply put, the protection keys is about enforcing page-based memory protections. There are new RDPKRU and WRPKRU instructions coming to future Intel CPUs for reading/writing to the new thread-local PKRU register for access disable and write disable bits for each key.

The new system calls with Linux 4.9 are pkey_alloc(), pkey_free(), and pkey_mprotect(). Here's a very basic example from the documentation about making use of the memory protection keys in a basic C program:
Before a pkey can be used, it must first be allocated with pkey_alloc(). An application calls the WRPKRU instruction directly in order to change access permissions to memory covered with a key. In this example WRPKRU is wrapped by a C function called pkey_set().

int real_prot = PROT_READ|PROT_WRITE;
pkey = pkey_alloc(0, PKEY_DENY_WRITE);
ret = pkey_mprotect(ptr, PAGE_SIZE, real_prot, pkey);
... application runs here

Now, if the application needs to update the data at 'ptr', it can gain access, do the update, then remove its write access:

pkey_set(pkey, 0); // clear PKEY_DENY_WRITE
*ptr = foo; // assign something
pkey_set(pkey, PKEY_DENY_WRITE); // set PKEY_DENY_WRITE again

Now when it frees the memory, it will also free the pkey since it is no longer in use:
This isn't about Intel MPX (Memory Protection Extensions) but relies upon the RDPKRU/WRPKRU instruction set extensions. I don't believe I've seen any confirmation anywhere about which generation of Intel CPUs will premiere this support.

The code for Linux 4.9 is queued via this pull request.
Related News
About The Author
Michael Larabel

Michael Larabel is the principal author of and founded the site in 2004 with a focus on enriching the Linux hardware experience. Michael has written more than 20,000 articles covering the state of Linux hardware support, Linux performance, graphics drivers, and other topics. Michael is also the lead developer of the Phoronix Test Suite, Phoromatic, and automated benchmarking software. He can be followed via Twitter, LinkedIn, or contacted via

Popular News This Week