Yes, HSEM is Hardware Semaphore.
Think about an "atomic action" needed: this "read-check-write" to a register (SW based, memory based) semaphore is NOT safe. It is NOT an "atomic action". It should not be possible to be interrupted, interleaved, intercepted.
Two masters (cores) doing these instructions (more then one code line or processor code) can intercept each other. Both can see "it is free" and use the resource at the same time. They are not in sync.
core 1 core 2
read
read
check
check
free
free
write
write
Core 2 will read before Core 1 could write to it. Both will see "free".
A HW Semaphore (HSEM) is there to make it "atomic": the access to this HSEM (a register on the bus) is handled by the bus fabric: only one core is allowed to access. And if it is accessed, e.g. just via an atomic read command - as a single instruction (not C-code, a real processor instruction) can automatically allocate the HSEM if it is free (done in HW). This can never be interrupted by another master (core).
If you would keep going with a SW based semaphore, I would suggest to check it twice, to have a means to check if the other core has kicked in and has also grabbed the semaphore "at the same time".
Example:
//Core 1 Core 2
if (semaphore == 0) if (semaphore == 0)
semaphore = 1; semaphore = 2;
if (semaphore == 1) if (semaphore == 2)
{ {
//... I got the semaphore
When the other core "wins" - you might see the other value there.
But just doing "if (semaphore == 0)" is not safe!
And even this "double-check" is not safe!
What if Core2 sees also a 0 there (free), but the write of Core2 to allocate is done right after
Core1 has done the check for "if (semaphore == 1)" (a tiny bit later)?:
Core1 progresses. But Core will still do the check for "if (semaphore == 2)" and it will also see its own value is there. It has overwritten Core1 value which is a bit ahead.
There is a race condition which you cannot really solve in software. You need HW support for it.
Therefore the HSEM is there.
BTW: such HW Semaphores HSEM are always on a system with two masters, with two and more cores. The bus matrix allows "concurrent access" to memory by two parallel cores running. A C-code "instruction" (code line) is a sequence of several processor instructions. And those can be "scheduled" in any way, by intercepting each other (core1, core2 firing their instructions in a random way on the bus).
The processor does not have instructions to say: "let me do SOME instructions but do not interrupt me" (on the bus fabric, not related to an interrupt). Instructions on the bus fabric are arbitrated by the bus access logic, not by the software.