Austin Schuh | 208337d | 2022-01-01 14:29:11 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. |
| 3 | * |
| 4 | * SPDX-License-Identifier: BSD-3-Clause |
| 5 | */ |
| 6 | |
| 7 | #include "hardware/exception.h" |
| 8 | #include "hardware/regs/m0plus.h" |
| 9 | #include "hardware/platform_defs.h" |
| 10 | #include "hardware/structs/scb.h" |
| 11 | |
| 12 | #include "pico/mutex.h" |
| 13 | #include "pico/assert.h" |
| 14 | |
| 15 | #ifndef exception_is_compile_time_default |
| 16 | static bool exception_is_compile_time_default(exception_handler_t handler) { |
| 17 | extern char __default_isrs_start; |
| 18 | extern char __default_isrs_end; |
| 19 | return ((uintptr_t)handler) >= (uintptr_t)&__default_isrs_start && |
| 20 | ((uintptr_t)handler) < (uintptr_t)&__default_isrs_end; |
| 21 | } |
| 22 | #endif |
| 23 | |
| 24 | static inline exception_handler_t *get_vtable(void) { |
| 25 | return (exception_handler_t *) scb_hw->vtor; |
| 26 | } |
| 27 | |
| 28 | static void set_raw_exception_handler_and_restore_interrupts(enum exception_number num, exception_handler_t handler, uint32_t save) { |
| 29 | // update vtable (vtable_handler may be same or updated depending on cases, but we do it anyway for compactness) |
| 30 | get_vtable()[16 + num] = handler; |
| 31 | __dmb(); |
| 32 | restore_interrupts(save); |
| 33 | } |
| 34 | |
| 35 | static inline void check_exception_param(__unused enum exception_number num) { |
| 36 | invalid_params_if(EXCEPTION, num < NMI_EXCEPTION || num >=0); |
| 37 | } |
| 38 | |
| 39 | exception_handler_t exception_get_vtable_handler(enum exception_number num) { |
| 40 | check_exception_param(num); |
| 41 | return get_vtable()[16 + num]; |
| 42 | } |
| 43 | |
| 44 | exception_handler_t exception_set_exclusive_handler(enum exception_number num, exception_handler_t handler) { |
| 45 | check_exception_param(num); |
| 46 | #if !PICO_NO_RAM_VECTOR_TABLE |
| 47 | uint32_t save = save_and_disable_interrupts(); |
| 48 | exception_handler_t current = exception_get_vtable_handler(num); |
| 49 | hard_assert(handler == current || exception_is_compile_time_default(current)); |
| 50 | set_raw_exception_handler_and_restore_interrupts(num, handler, save); |
| 51 | #else |
| 52 | panic_unsupported(); |
| 53 | #endif |
| 54 | return current; |
| 55 | } |
| 56 | |
| 57 | void exception_restore_handler(enum exception_number num, exception_handler_t original_handler) { |
| 58 | hard_assert(exception_is_compile_time_default(original_handler)); |
| 59 | #if !PICO_NO_RAM_VECTOR_TABLE |
| 60 | uint32_t save = save_and_disable_interrupts(); |
| 61 | set_raw_exception_handler_and_restore_interrupts(num, original_handler, save); |
| 62 | #else |
| 63 | panic_unsupported(); |
| 64 | #endif |
| 65 | } |