/* Performs an atomic compare exchange operation to get semaphore. The compare exchange operation must be performed using MP safe mechanisms. */
STATIC UINT32 InternalWaitForSemaphore(IN OUT volatile UINT32 *Sem)
/* Performs an atomic compare exchange operation to get semaphore. The compare exchange operation must be performed using MP safe mechanisms. */
STATIC UINT32 InternalWaitForSemaphore(IN OUT volatile UINT32 *Sem)
{
  UINT32  Value;
  for ( ; ;) {
    Value = *Sem;
    if (Value == MAX_UINT32) {
      return Value;
    }
    if ((Value != 0) &&
        (InterlockedCompareExchange32 (
           (UINT32 *)Sem,
           Value,
           Value - 1
           ) == Value))
    {
      break;
    }
    CpuPause ();
  }
  return Value - 1;
}