Andrew Gable


Finding the Semaphore Source Code

20 October, 2014

Finding the Semaphore source code in the kernel was quite easy, I found it by running the command find . -name semaphore.c. You can find the semaphore code in linux/kernel/locking/semaphore.c and the header files in linux\include\kernel\semaphore.h.

The main semaphore struct is located in semaphore.h

struct semaphore {
    raw_spinlock_t      lock;
    unsigned int        count;
    struct list_head    wait_list;

The function to lock acquire the semaphore is the down(struct semaphore *sem) function. The function to release the function is up(struct semaphore *sem).

The down() function is depreciated for these other functions:

  • down_interruptible(struct semaphore *sem) - acquire the semaphore unless interrupted
  • down_killable(struct semaphore *sem) - acquire the semaphore unless killed
  • down_trylock(struct semaphore *sem) - try to acquire the semaphore, without waiting
  • down_timeout(struct semaphore *sem, long jiffies) - acquire the semaphore within a specified time

These additional functions will give the kernel engineers more functionality and control. Overall the semaphore source code was simple to find, but is a very important piece of code for the Linux kernel.

© 2024 Andrew Gable