mbed_critical_section_api.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* mbed Microcontroller Library
  2. * Copyright (c) 2017 ARM Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "cmsis.h"
  17. #include "hal/critical_section_api.h"
  18. #include "platform/mbed_assert.h"
  19. #include "platform/mbed_toolchain.h"
  20. #include <stdbool.h>
  21. static volatile bool critical_interrupts_enabled = false;
  22. static volatile bool state_saved = false;
  23. static bool are_interrupts_enabled(void)
  24. {
  25. #if defined(__CORTEX_A9)
  26. return ((__get_CPSR() & 0x80) == 0);
  27. #else
  28. return ((__get_PRIMASK() & 0x1) == 0);
  29. #endif
  30. }
  31. MBED_WEAK void hal_critical_section_enter(void)
  32. {
  33. const bool interrupt_state = are_interrupts_enabled();
  34. __disable_irq();
  35. if (state_saved == true) {
  36. return;
  37. }
  38. critical_interrupts_enabled = interrupt_state;
  39. state_saved = true;
  40. }
  41. MBED_WEAK void hal_critical_section_exit(void)
  42. {
  43. #ifndef FEATURE_UVISOR
  44. // Interrupts must be disabled on invoking an exit from a critical section
  45. MBED_ASSERT(!are_interrupts_enabled());
  46. #endif
  47. state_saved = false;
  48. // Restore the IRQs to their state prior to entering the critical section
  49. if (critical_interrupts_enabled == true) {
  50. __enable_irq();
  51. }
  52. }
  53. MBED_WEAK bool hal_in_critical_section(void)
  54. {
  55. return (state_saved == true);
  56. }