# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Western Digital Corporation or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
// startup code to support HLL programs

#include "defines.h"

.section .text.init
.global _start
_start:

// enable caching, except region 0xd
        li t0, 0x59555555
        csrw 0x7c0, t0
        la  t0, handlers
        csrw    mtvec, t0

        csrr t0, mhartid
        bnez t0, setup_stack1
        csrwi 0x7fc,3 // enable hart1
        la sp, STACK

        call main


.global _finish
_finish:
        la t0, tohost
        li t1, 0xff
        sb t1, 0(t0) // DemoTB test termination
        li t1, 1
        sw t1, 0(t0) // Whisper test termination
        beq x0, x0, _finish
        .rept 10
        nop
        .endr

setup_stack1:
        la sp, STACK-0x1000
        call    main
        j       _finish

// simplified handler to support 'write' system call of GCC
.balign 16
handlers:
        csrr    a0, mepc
        addi    a0,a0,4
        csrw    mepc, a0
        li      a0,0
        mret

.section .data.io
.global tohost
tohost: .word 0

