|
| 1 | +/* |
| 2 | + * Copyright (c) 2015-2016, ARM Limited, All Rights Reserved |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | + * not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | + |
| 19 | +#include <stdint.h> |
| 20 | +#include <stddef.h> |
| 21 | +#include "cmsis.h" |
| 22 | +#include <assert.h> |
| 23 | + |
| 24 | +// Module include |
| 25 | +#include "critical.h" |
| 26 | + |
| 27 | +static volatile uint32_t interrupt_enable_counter = 0; |
| 28 | +static volatile uint32_t critical_primask = 0; |
| 29 | + |
| 30 | +void core_util_critical_section_enter() |
| 31 | +{ |
| 32 | + uint32_t primask = __get_PRIMASK(); /* get the current interrupt enabled state */ |
| 33 | + __disable_irq(); |
| 34 | + |
| 35 | + /* Save the interrupt enabled state as it was prior to any nested critical section lock use */ |
| 36 | + if (!interrupt_enable_counter) { |
| 37 | + critical_primask = primask & 0x1; |
| 38 | + } |
| 39 | + |
| 40 | + /* If the interrupt_enable_counter overflows or we are in a nested critical section and interrupts |
| 41 | + are enabled, then something has gone badly wrong thus assert an error. |
| 42 | + */ |
| 43 | + assert(interrupt_enable_counter < UINT32_MAX); |
| 44 | + if (interrupt_enable_counter > 0) { |
| 45 | + assert(primask & 0x1); |
| 46 | + } |
| 47 | + interrupt_enable_counter++; |
| 48 | +} |
| 49 | + |
| 50 | +void core_util_critical_section_exit() |
| 51 | +{ |
| 52 | + /* If critical_section_enter has not previously been called, do nothing */ |
| 53 | + if (interrupt_enable_counter) { |
| 54 | + |
| 55 | + uint32_t primask = __get_PRIMASK(); /* get the current interrupt enabled state */ |
| 56 | + |
| 57 | + assert(primask & 0x1); /* Interrupts must be disabled on invoking an exit from a critical section */ |
| 58 | + |
| 59 | + interrupt_enable_counter--; |
| 60 | + |
| 61 | + /* Only re-enable interrupts if we are exiting the last of the nested critical sections and |
| 62 | + interrupts were enabled on entry to the first critical section. |
| 63 | + */ |
| 64 | + if (!interrupt_enable_counter && !critical_primask) { |
| 65 | + __enable_irq(); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments