|
| 1 | +/* |
| 2 | + * Copyright (c) 2015-2017, 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 | +#include "cmsis.h" |
| 18 | +#include "nrf_error.h" |
| 19 | +#include "nrf_sdm.h" |
| 20 | +#include "nrf_soc.h" |
| 21 | + |
| 22 | +#include <stdbool.h> |
| 23 | +#include <stdint.h> |
| 24 | + |
| 25 | +static union { |
| 26 | + uint32_t _PRIMASK_state; |
| 27 | + uint8_t _sd_state; |
| 28 | +} _state = {0}; |
| 29 | + |
| 30 | +static bool _use_softdevice_routine = false; |
| 31 | + |
| 32 | +void hal_critical_section_enter(void) |
| 33 | +{ |
| 34 | + // Fetch the current state of interrupts |
| 35 | + uint32_t primask = __get_PRIMASK(); |
| 36 | + |
| 37 | + // If interrupts are enabled, try to use the soft device |
| 38 | + uint8_t sd_enabled; |
| 39 | + if ((primask == 0) && |
| 40 | + (sd_softdevice_is_enabled(&sd_enabled) == NRF_SUCCESS) && |
| 41 | + (sd_enabled == 1)) { |
| 42 | + // If the softdevice can be used, use it. |
| 43 | + sd_nvic_critical_region_enter(&_state._sd_state); |
| 44 | + _use_softdevice_routine = true; |
| 45 | + } else { |
| 46 | + // If interrupts are enabled, disable them. |
| 47 | + if (primask == 0) { |
| 48 | + __disable_irq(); |
| 49 | + } |
| 50 | + |
| 51 | + // Store PRIMASK state, it will be restored when exiting critical |
| 52 | + // section. |
| 53 | + _state._PRIMASK_state = primask; |
| 54 | + _use_softdevice_routine = false; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +void hal_critical_section_exit(void) |
| 59 | +{ |
| 60 | + // Restore the state as it was prior to entering the critical section. |
| 61 | + if (_use_softdevice_routine) { |
| 62 | + sd_nvic_critical_region_exit(_state._sd_state) |
| 63 | + } else { |
| 64 | + __set_PRIMASK(_state._PRIMASK_state); |
| 65 | + } |
| 66 | +} |
0 commit comments