1 /*
2 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 #include "hardware/claim.h"
8
hw_claim_lock()9 uint32_t hw_claim_lock() {
10 return spin_lock_blocking(spin_lock_instance(PICO_SPINLOCK_ID_HARDWARE_CLAIM));
11 }
12
hw_claim_unlock(uint32_t save)13 void hw_claim_unlock(uint32_t save) {
14 spin_unlock(spin_lock_instance(PICO_SPINLOCK_ID_HARDWARE_CLAIM), save);
15 }
16
hw_is_claimed(const uint8_t * bits,uint bit_index)17 inline bool hw_is_claimed(const uint8_t *bits, uint bit_index) {
18 return (bits[bit_index >> 3u] & (1u << (bit_index & 7u)));
19 }
20
hw_claim_or_assert(uint8_t * bits,uint bit_index,const char * message)21 void hw_claim_or_assert(uint8_t *bits, uint bit_index, const char *message) {
22 uint32_t save = hw_claim_lock();
23 if (hw_is_claimed(bits, bit_index)) {
24 panic(message, bit_index);
25 } else {
26 bits[bit_index >> 3u] |= (uint8_t)(1u << (bit_index & 7u));
27 }
28 hw_claim_unlock(save);
29 }
30
hw_claim_unused_from_range(uint8_t * bits,bool required,uint bit_lsb,uint bit_msb,const char * message)31 int hw_claim_unused_from_range(uint8_t *bits, bool required, uint bit_lsb, uint bit_msb, const char *message) {
32 // don't bother check lsb / msb order as if wrong, then it'll fail anyway
33 uint32_t save = hw_claim_lock();
34 int found_bit = -1;
35 for(uint bit=bit_lsb; bit <= bit_msb; bit++) {
36 if (!hw_is_claimed(bits, bit)) {
37 bits[bit >> 3u] |= (uint8_t)(1u << (bit & 7u));
38 found_bit = (int)bit;
39 break;
40 }
41 }
42 hw_claim_unlock(save);
43 if (found_bit < 0 && required) {
44 panic(message);
45 }
46 return found_bit;
47 }
48
hw_claim_clear(uint8_t * bits,uint bit_index)49 void hw_claim_clear(uint8_t *bits, uint bit_index) {
50 uint32_t save = hw_claim_lock();
51 assert(hw_is_claimed(bits, bit_index));
52 bits[bit_index >> 3u] &= (uint8_t) ~(1u << (bit_index & 7u));
53 hw_claim_unlock(save);
54 }
55
56
57