Locking all pages

mlock basically allows us to tell the OS to lock a certain range of memory into RAM. In some real-world cases, though, we cannot predict exactly which pages of memory we will require resident in advance (a real-time application might require various, or all, memory pages to always be resident).

To solve this tricky issue, another system call  mlockall(2) exists; as you can guess, it allows you to lock all process memory pages:

 int mlockall(int flags);

If successful (remember, the same privilege restrictions apply to mlockall as to mlock), all the process's memory pages  such as text, data segments, library pages, stack, and shared memory segments  are guaranteed to remain resident in RAM until unlocked.

The flags argument provides further control to the application developer; it can be bitwise OR of the following:

  • MCL_CURRENT
  • MCL_FUTURE
  • MCL_ONFAULT (Linux 4.4 onward)

Using MCL_CURRENT asks the OS to lock all current pages within the calling process's VAS into memory.

But what if you issue the mlockall(2) system call at initialization time, but the real-time process is going to perform an malloc of say, 200 kilobytes, 5 minutes from now? We need to guarantee that those 200 KB of memory (which is 50 pages, given a 4 KB page size) is always resident in RAM (otherwise, the real-time application will suffer too great a latency from possible future page faulting). That is the purpose of the MCL_FUTURE flag: it guarantees the memory pages that become part of the calling process's VAS in the future will remain resident in memory until unlocked.

We learned in the Demand-paging section that performing malloc does nothing more than reserve virtual memory, not physical. As an example, if an (non-real-time) application performs a rather large allocation of a megabyte (that's 512 pages), we understand that only 512 virtual pages are reserved and the physical page frames are not actually allocated  they will get faulted in on-demand. A typical realtime application will therefore need to somehow guarantee that, once faulted in, these 512 pages will remain locked (resident) in RAM. Use the MCL_ONFAULT flag to achieve this.

This flag must be used in conjunction with either the MCL_CURRENT or  MCL_FUTURE flag, or both. The idea is that physical memory consumption remains extremely efficient (as no physical allocation is done at the time of malloc), and yet, once the application starts to touch the virtual pages (that is, read, write, or execute data or code within the page), the physical page frames get faulted in and they will then be locked. In other words, we do not pre-fault the memory, thus we get the best of both worlds.

The other side of the coin is that, when done, the application can unlock all memory pages by issuing the counterpart API: munlockall(2).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset