1/*
2 * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7#pragma once
8
9#include <config.h>
10#include <model/smp.h>
11#include <kernel/stack.h>
12
13#ifdef ENABLE_SMP_SUPPORT
14
15typedef struct core_map {
16    word_t map[CONFIG_MAX_NUM_NODES];
17} core_map_t;
18
19extern char kernel_stack_alloc[CONFIG_MAX_NUM_NODES][BIT(CONFIG_KERNEL_STACK_BITS)];
20compile_assert(kernel_stack_4k_aligned, KERNEL_STACK_ALIGNMENT == 4096)
21extern core_map_t coreMap;
22
23static inline cpu_id_t cpuIndexToID(word_t index)
24{
25    assert(index < CONFIG_MAX_NUM_NODES);
26    return coreMap.map[index];
27}
28
29static inline word_t hartIDToCoreID(word_t hart_id)
30{
31    word_t i = 0;
32    for (i = 0; i < CONFIG_MAX_NUM_NODES; i++) {
33        if (coreMap.map[i] == hart_id) {
34            break;
35        }
36    }
37    return i;
38}
39
40static inline void add_hart_to_core_map(word_t hart_id, word_t core_id)
41{
42    assert(core_id < CONFIG_MAX_NUM_NODES);
43    coreMap.map[core_id] = hart_id;
44}
45
46static inline bool_t try_arch_atomic_exchange_rlx(void *ptr, void *new_val, void **prev)
47{
48    *prev = __atomic_exchange_n((void **)ptr, new_val, __ATOMIC_RELAXED);
49    return true;
50}
51
52static inline CONST cpu_id_t getCurrentCPUIndex(void)
53{
54    word_t sp;
55    asm volatile("csrr %0, sscratch" : "=r"(sp));
56    sp -= (word_t)kernel_stack_alloc;
57    sp -= 8;
58    return (sp >> CONFIG_KERNEL_STACK_BITS);
59}
60
61#endif /* ENABLE_SMP_SUPPORT */
62
63
64