/***************************************************************************
 * Copyright (C) 2026 Eclipse ThreadX contributors
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which is available at
 * https://opensource.org/licenses/MIT.
 *
 * AI Disclosure: This file was largely AI-generated by Copilot (Sonnet 4.6).
 * The AI-generated portions may be considered public domain (CC0-1.0)
 * and not subject to the project's licence. The human contributor has
 * reviewed and verified that the code is correct.
 *
 * SPDX-License-Identifier: MIT and CC0-1.0
 **************************************************************************/

    .section .data
    .global __tx_free_memory_start
__tx_free_memory_start:

    .section .text.trap_entry
    .align 4
    .global tx_trap_entry
    .extern _tx_thread_context_save
    .extern _tx_thread_context_restore
    .extern tx_trap_handler

tx_trap_entry:
    addi sp, sp, -128
    sw   ra, 112(sp)
    call _tx_thread_context_save
    csrr a0, mcause
    csrr a1, mepc
    csrr a2, mtval
    addi sp, sp, -4
    sw   ra, 0(sp)
    call tx_trap_handler
    lw   ra, 0(sp)
    addi sp, sp, 4
    call _tx_thread_context_restore
1:
    wfi
    j    1b

    .section .text
    .global _tx_initialize_low_level
    .weak   _tx_initialize_low_level
    .extern _tx_thread_system_stack_ptr
    .extern _tx_initialize_unused_memory
    .extern __vector_start

_tx_initialize_low_level:
    la   t0, _tx_thread_system_stack_ptr
    sw   sp, 0(t0)

    la   t0, __tx_free_memory_start
    la   t1, _tx_initialize_unused_memory
    sw   t0, 0(t1)

    la   t0, __vector_start
    ori  t0, t0, 1
    csrw mtvec, t0

    ret
