CRITICAL_ENTER(9)

okay so this is CRITICAL_ENTER(9), from the Kernel Developer's Manual, and it's all about critical_enter and critical_exit β€” enter and exit a critical region. If you're a kernel dev bestie, this is your lowkey anti-preemption duo. πŸ’…

✨ NAME ✨

critical_enter, critical_exit β€” enter and exit a critical region.

No cap, that's the whole name section. Two functions, one job: get in and get out of a critical region. πŸŽ€

🌸 SYNOPSIS 🌸

The includes and signatures, exactly as they are:

#include <sys/param.h>
#include <sys/systm.h>

void
critical_enter(void);

void
critical_exit(void);

πŸ’– DESCRIPTION πŸ’–

So these functions are used to prevent preemption in a critical region of code. That's the main character energy here. The only guarantee β€” all that is guaranteed β€” is that the thread currently executing on a CPU will not be preempted. Specifically, a thread in a critical region will not migrate to another CPU while it is in a critical region. So it stays put on its CPU. Periodt. πŸ’…

The current CPU may still trigger faults and exceptions during a critical section; however, these faults are usually fatal. So like, don't be dramatic if you see a fault, because bestie... it's usually fatal. 😭

The critical_enter() and critical_exit() functions manage a per-thread counter to handle nested critical sections. That's how they keep track of how deep you are. If a thread is made runnable that would normally preempt the current thread while the current thread is in a critical section, then the preemption will be deferred until the current thread exits the outermost critical section. So the preemption isn't cancelled, it's just queued up like "not now, I'm busy". ✨

Note that these functions are not required to provide any inter-CPU synchronization, data protection, or memory ordering guarantees and thus should not be used to protect shared data structures. So do NOT use them as a lock. They are not giving lock. They are giving preemption control. πŸ™ˆ

These functions should be used with care as an infinite loop within a critical region will deadlock the CPU. That's a big yikes. Also, they should not be interlocked with operations on mutexes, sx locks, semaphores, or other synchronization primitives. One exception to this is that spin mutexes include a critical section, so in certain cases critical sections may be interlocked with spin mutexes. So spin mutexes are the exception bestie, iykyk. πŸ”₯

πŸ¦‹ HISTORY πŸ¦‹

These functions were introduced in FreeBSD 5.0. So they've been iconic since FreeBSD 5.0, no cap. πŸ‘‘


This page came from Debian, dated October 5, 2005, and its title is CRITICAL_ENTER(9). Bye bestie, go forth and protect your critical regions responsibly πŸ«ΆπŸ’–

πŸ“¦ where this page comes from