Fast Path, Mid Path and Slow Path in Mutex

When the Kernel code is invoked to gain control of a Mutex lock, the kernel attempts it in three ways one after the other. They are

  1. Fast Path
  2. Mid Path
  3. Slow Path

In Order to understand the above mechanisms, it is necessary to look at the mutex structure and a few other mutex related structures in the Linux kernel (Linux Kernel 5.11). 

Earlier kernel versions had a “count” which would track mutex state. In current Kernels, the “owner” variable is used to track mutex state. If the “owner” variable is NULL, then the mutex is not owned by anyone.

The spinlock_t “wait_lock” structure member is used to protect the list of processes/threads waiting on the release of the mutex maintained in the structure member “wait_list”. 

The “CONFIG_MUTEX_SPIN_ON_OWNER” allows optimistic spinning (Mid path) using a spinner Lock mechanism (refer Article for Mutex). 

 The other two parameters are used only in debug configuration.

Fast Path:

When a mutex needs to be acquired, the Linux kernel first attempts Fast path – which is to check if mutex is already acquired and has on owner or not. If the Owner is NULL, then the mutex is acquired.

Mid Path:

If the Owner member is not “NULL”, then the mutex is acquired by another process/thread. The kernel checks if the owner of the mutex is presently running and if it is running, the kernel attempts to optimistically spin wait for the lock to be released. This path is only executed in case no higher priority process/thread is ready to run. The Mid path by spin waiting does not sleep and hence the current process does not go down to sleep and need to be rescheduled later. The spin wait avoids a “context switch” operation which is a very expensive operation. The structure “optimistic_spin_queue” is provided below:

 

Slow Path:

The Slow path is chosen when the Fast path and Mid Path execution is not possible. In this case, the process which desires the mutex is placed in a wait queue given by name “mutex_waiter” and the process is set to sleep.

Mutex API List and Sample API code

  • References:
    • https://0xax.gitbooks.io/linux-insides/content/SyncPrim/linux-sync-4.html
    • https://elixir.bootlin.com/linux/latest/source/include/linux/mutex.h#L57

Comments

  1. Pingback: Mutex API | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *