/*
 * Copyright 2008-2020 NXP
 * This software is owned or controlled by NXP and may only be used strictly
 * in accordance with the applicable license terms.  By expressly accepting
 * such terms or by downloading, installing, activating and/or otherwise using
 * the software, you are agreeing that you have read, and that you agree to
 * comply with and are bound by, such license terms.  If you do not agree to
 * be bound by the applicable license terms, then you may not retain, install,
 * activate or otherwise use the software.
 */

#include <stdint.h>

#include "critical.h"

static uint32_t g_irq_nesting_level;

#if defined(UNIT_TEST)
    #define _ENABLE_IRQ()
    #define _DISABLE_IRQ()
#elif defined(__CC_ARM)
    #define _ENABLE_IRQ()   __enable_irq()
    #define _DISABLE_IRQ()  __disable_irq()
#else
    #define _ENABLE_IRQ()   __ASM("CPSIE i")
    #define _DISABLE_IRQ()  __ASM("CPSID i")
#endif

void critical_Enter(void)
{
    if (!g_irq_nesting_level) {
        _DISABLE_IRQ();
    }

    g_irq_nesting_level++;
}

void critical_Exit(void)
{
    if (g_irq_nesting_level > 0) {
        g_irq_nesting_level--;
    }

    if (g_irq_nesting_level) {
        return;
    }

    _ENABLE_IRQ();
}
