code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <stddef.h> #include <stdint.h> #include <string.h> #include <limits.h> #include <stdio.h> #include "k_api.h" /* part of ktask_t */ typedef struct { void *task_stack; }ktask_t_shadow; //#define OS_BACKTRACE_DEBUG extern void krhino_task_deathbed(void); extern ktask_t_shadow *debug_task_find(char *name); extern int debug_task_is_running(ktask_t_shadow *task); extern void *debug_task_stack_bottom(ktask_t_shadow *task); extern char *k_int2str(int num, char *str); void backtrace_handle(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)); #if defined(__CC_ARM) #ifdef __BIG_ENDIAN #error "Not support big-endian!" #endif #elif defined(__ICCARM__) #if (__LITTLE_ENDIAN__ == 0) #error "Not support big-endian!" #endif #elif defined(__GNUC__) #if (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #error "Not support big-endian!" #endif #endif #define BT_FUNC_LIMIT 0x2000 #define BT_LVL_LIMIT 64 #define BT_PC2ADDR(pc) ((char *)(((uintptr_t)(pc)) & 0xfffffffe)) /* alios_debug_pc_check depends on mcu*/ __attribute__((weak)) int alios_debug_pc_check(char *pc) { return 0; } #if defined(__ICCARM__) static unsigned int __builtin_popcount(unsigned int u) { unsigned int ret = 0; while (u) { u = (u & (u - 1)); ret++; } return ret; } #endif void getPLSfromCtx(void *context, char **PC, char **LR, int **SP) { int *ptr = context; int exc_return; /* reference to cpu_task_stack_init */ exc_return = ptr[8]; if ((exc_return & 0x10) == 0x10) { *PC = (char *)ptr[15]; *LR = (char *)ptr[14]; *SP = ptr + 17; } else { *PC = (char *)ptr[31]; *LR = (char *)ptr[30]; *SP = ptr + 51; } } /* get "blx" or "bl" before LR, return offset */ static int backtraceFindLROffset(char *LR, int (*print_func)(const char *fmt, ...)) { unsigned short ins16; char s_panic_call[] = "backtrace : 0x \r\n"; LR = BT_PC2ADDR(LR); /* callstack bottom */ if (((int)LR & 0xffffffe0) == 0xffffffe0) { /* EXC_RETURN, so here is callstack bottom of interrupt handler */ if (print_func != NULL) { print_func("backtrace : ^interrupt^\r\n"); } return 0; } if (LR == BT_PC2ADDR(&krhino_task_deathbed)) { /* task delete, so here is callstack bottom of task */ if (print_func != NULL) { print_func("backtrace : ^task entry^\r\n"); } return 0; } if (alios_debug_pc_check(LR) != 0) { if (print_func) { print_func("backtrace : invalid pc : 0x%x\r\n", LR); } return -1; } ins16 = *(unsigned short *)(LR - 4); if ((ins16 & 0xf000) == 0xf000) { if (print_func != NULL) { k_int2str((int)LR - 4, &s_panic_call[14]); print_func(s_panic_call); } return 5; } else { if (print_func != NULL) { k_int2str((int)LR - 2, &s_panic_call[14]); print_func(s_panic_call); } return 3; } } /* find current function caller, update PC and SP returns: 0 success 1 success and find buttom -1 fail */ static int backtraceFromStack(int **pSP, char **pPC, int (*print_func)(const char *fmt, ...)) { char *CodeAddr = NULL; int *SP = *pSP; char *PC = *pPC; char *LR; int i; unsigned short ins16; unsigned int ins32; unsigned int framesize = 0; unsigned int shift = 0; unsigned int sub = 0; int offset = 1; #ifdef OS_BACKTRACE_DEBUG printf("[backtraceFromStack in ] SP = %p, PC = %p\n\r", *pSP, *pPC); #endif if (SP == debug_task_stack_bottom(NULL)) { if (print_func != NULL) { print_func("backtrace : ^task entry^\r\n"); } return 1; } if (alios_debug_pc_check(*pPC) != 0) { if (print_func) { print_func("backtrace : invalid pc : 0x%x\r\n", *pPC); } return -1; } /* func call ways: 1. "stmdb sp!, ..." or "push ..." to open stack frame and save LR 2. "sub sp, ..." or "sub.w sp, ..." to open stack more 3. call */ /* 1. scan code, find frame size from "push" or "stmdb sp!" */ for (i = 2; i < BT_FUNC_LIMIT; i += 2) { /* find nearest "push {..., lr}" */ ins16 = *(unsigned short *)(PC - i); if ((ins16 & 0xff00) == 0xb500) { framesize = __builtin_popcount((unsigned char)ins16); framesize++; /* find double push */ ins16 = *(unsigned short *)(PC - i - 2); if ((ins16 & 0xff00) == 0xb400) { offset += __builtin_popcount((unsigned char)ins16); framesize += __builtin_popcount((unsigned char)ins16); } CodeAddr = PC - i; break; } /* find "stmdb sp!, ..." */ /* The Thumb instruction stream is a sequence of halfword-aligned * halfwords */ ins32 = *(unsigned short *)(PC - i); ins32 <<= 16; ins32 |= *(unsigned short *)(PC - i + 2); if ((ins32 & 0xFFFFF000) == 0xe92d4000) { framesize = __builtin_popcount(ins32 & 0xfff); framesize++; CodeAddr = PC - i; break; } } if (CodeAddr == NULL) { /* error branch */ if (print_func != NULL) { print_func("Backtrace fail!\r\n"); } return -1; } /* 2. scan code, find frame size from "sub" or "sub.w" */ for (i = 0; i < BT_FUNC_LIMIT;) { if (CodeAddr + i > PC) { break; } /* find "sub sp, ..." */ ins16 = *(unsigned short *)(CodeAddr + i); if ((ins16 & 0xff80) == 0xb080) { framesize += (ins16 & 0x7f); break; } /* find "sub.w sp, sp, ..." */ ins32 = *(unsigned short *)(CodeAddr + i); ins32 <<= 16; ins32 |= *(unsigned short *)(CodeAddr + i + 2); if ((ins32 & 0xFBFF8F00) == 0xF1AD0D00) { sub = 128 + (ins32 & 0x7f); shift = (ins32 >> 7) & 0x1; shift += ((ins32 >> 12) & 0x7) << 1; shift += ((ins32 >> 26) & 0x1) << 4; framesize += sub << (30 - shift); break; } if ((ins16 & 0xf800) >= 0xe800) { i += 4; } else { i += 2; } } #ifdef OS_BACKTRACE_DEBUG printf("[backtraceFromStack out] frsz = %d offset = %d SP=%p\n\r", framesize, offset, SP); #endif /* 3. output */ LR = (char *)*(SP + framesize - offset); offset = backtraceFindLROffset(LR, print_func); if (offset < 0) { return -1; } *pSP = SP + framesize; *pPC = LR - offset; return offset == 0 ? 1 : 0; } /* find current function caller, update PC and SP returns: 0 success 1 success and find buttom -1 fail */ static int backtraceFromLR(int **pSP, char **pPC, char *LR, int (*print_func)(const char *fmt, ...)) { int *SP = *pSP; char *PC = *pPC; char *CodeAddr = NULL; int i; unsigned short ins16; unsigned int framesize = 0; int offset; #ifdef OS_BACKTRACE_DEBUG printf("[backtraceFromLR in ] SP = %p, PC = %p, LR = %p\n\r", *pSP, *pPC, LR); #endif if (alios_debug_pc_check(*pPC) != 0) { offset = backtraceFindLROffset(LR, print_func); if ( offset < 0 ){ return -1; } PC = LR - offset; *pPC = PC; return offset == 0 ? 1 : 0; } /*find stack framesize: 1. "push ..." to open stack 2. "sub sp, ..." to open stack 3. 1 + 2 4. do not open stack */ /* 1. scan code, find frame size from "push" or "sub" */ for (i = 2; i < BT_FUNC_LIMIT; i += 2) { ins16 = *(unsigned short *)(PC - i); /* find "push {..., lr}" */ if ((ins16 & 0xff00) == 0xb500) { /* another function */ break; } /* find "push {...}" */ if ((ins16 & 0xff00) == 0xb400) { framesize = __builtin_popcount((unsigned char)ins16); CodeAddr = PC - i; break; } /* find "sub sp, ..." */ if ((ins16 & 0xff80) == 0xb080) { framesize = (ins16 & 0x7f); CodeAddr = PC - i; /* find push before sub */ ins16 = *(unsigned short *)(PC - i - 2); if ((ins16 & 0xff00) == 0xb400) { framesize += __builtin_popcount((unsigned char)ins16); CodeAddr = PC - i - 2; } break; } } /* 2. check the "push" or "sub sp" belongs to another function */ if (CodeAddr != NULL) { for (i = 2; i < PC - CodeAddr; i += 2) { ins16 = *(unsigned short *)(PC - i); /* find "pop {..., pc}" or "bx lr" */ if ((ins16 & 0xff00) == 0xbd00 || ins16 == 0x4770) { /* SP no changed */ framesize = 0; } } } /* else: SP no changed */ #ifdef OS_BACKTRACE_DEBUG printf("[backtraceFromLR out] frsz = %d offset = %d SP=%p\n\r", framesize, offset, SP); #endif /* 3. output */ offset = backtraceFindLROffset(LR, print_func); if ( offset < 0 ){ return -1; } *pSP = SP + framesize; *pPC = LR - offset; return offset == 0 ? 1 : 0; } /* printf call stack return levels of call stack */ int backtrace_now(int (*print_func)(const char *fmt, ...)) { char *PC; int *SP; int lvl; int ret; if (print_func == NULL) { print_func = printf; } /* compiler specific */ #if defined(__CC_ARM) SP = (int *)__current_sp(); PC = (char *)__current_pc(); #elif defined(__ICCARM__) asm volatile("mov %0, sp\n" : "=r"(SP)); asm volatile("mov %0, pc\n" : "=r"(PC)); #elif defined(__GNUC__) __asm__ volatile("mov %0, sp\n" : "=r"(SP)); __asm__ volatile("mov %0, pc\n" : "=r"(PC)); #endif print_func("========== Call stack ==========\r\n"); for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&SP, &PC, print_func); if (ret != 0) { break; } } print_func("========== End ==========\r\n"); return lvl; } /* printf call stack for task return levels of call stack */ void backtrace_task(void *task, int (*print_func)(const char *fmt, ...)) { char *PC; char *LR; int *SP; int lvl = 0; int ret; char panic_call[] = "backtrace : 0x \r\n"; //ktask_t_shadow *task; if (print_func == NULL) { print_func = printf; } getPLSfromCtx(((ktask_t *)task)->task_stack, &PC, &LR, &SP); #ifdef OS_BACKTRACE_DEBUG printf("[backtrace_task] SP = %p, PC = %p, LR = %p\r\n", SP, PC, LR); #endif print_func("========== Call stack ==========\r\n"); k_int2str((int)BT_PC2ADDR(PC), &panic_call[14]); print_func(panic_call); ret = debug_task_is_running(task); switch (ret) { case 0 : case 1 : case 2 : backtrace_handle(PC, SP, LR, print_func); break; default: print_func("Status of task \"%s\" is 'Running', Can not backtrace!\n", ((ktask_t *)task)->task_name ? ((ktask_t *)task)->task_name : "anonym"); break; } print_func("========== End ==========\r\n"); } /* backtrace start with PC and SP, find LR from stack memory return levels of call stack */ int backtrace_caller(char *PC, int *SP, int (*print_func)(const char *fmt, ...)) { int *bt_sp; char *bt_pc; int lvl, ret; char s_panic_call[] = "backtrace : 0x \r\n"; /* caller must save LR in stack, so find LR from stack */ if (SP == NULL) { return 0; } /* try with no LR */ bt_sp = SP; bt_pc = BT_PC2ADDR(PC); ret = -1; for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&bt_sp, &bt_pc, NULL); if (ret != 0) { break; } } if (ret == 1) { /* try success, output */ k_int2str((int)PC, &s_panic_call[14]); if (print_func != NULL) { print_func(s_panic_call); } bt_sp = SP; bt_pc = PC; ret = -1; for (lvl = 1; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&bt_sp, &bt_pc, print_func); if (ret != 0) { break; } } return lvl; } return 0; } /* backtrace start with PC SP and LR return levels of call stack */ int backtrace_callee(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)) { int *bt_sp; char *bt_pc; char *bt_lr; int lvl, ret; char s_panic_call[] = "backtrace : 0x \r\n"; if (SP == NULL) { return 0; } /* Backtrace: assume ReturnAddr is saved in LR when exception */ k_int2str((int)PC, &s_panic_call[14]); if (print_func != NULL) { print_func(s_panic_call); } lvl = 1; bt_sp = SP; bt_pc = PC; bt_lr = LR; /* try, with LR */ ret = backtraceFromLR(&bt_sp, &bt_pc, bt_lr, print_func); if (ret == 0) { for (; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&bt_sp, &bt_pc, print_func); if (ret != 0) { break; } } } return lvl; } void *g_back_trace; /** Get call stack, return levels of call stack trace[] output buffer size buffer size offset which lvl start */ int backtrace_now_get(void *trace[], int size, int offset) { char *PC; int *SP; int lvl; int ret; /* compiler specific */ #if defined(__CC_ARM) SP = (int *)__current_sp(); PC = (char *)__current_pc(); #elif defined(__ICCARM__) asm volatile("mov %0, sp\n" : "=r"(SP)); asm volatile("mov %0, pc\n" : "=r"(PC)); #elif defined(__GNUC__) __asm__ volatile("mov %0, sp\n" : "=r"(SP)); __asm__ volatile("mov %0, pc\n" : "=r"(PC)); #endif memset(trace, 0, size*sizeof(void *)); g_back_trace = trace; for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&SP, &PC, NULL); if (ret != 0) { break; } if (lvl >= offset && lvl - offset < size) { trace[lvl - offset] = PC; } if (lvl - offset >= size) { break; } } return lvl - offset < 0 ? 0 : lvl - offset; } void backtrace_handle(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)) { if (SP == NULL) { print_func("SP is NULL, Can't backtrace\r\n"); return; } if (backtrace_caller(PC, SP, print_func) > 0) { /* Backtrace 1st try: assume ReturnAddr is saved in stack when exception */ /* backtrace success, do not try other way */ goto exit; } else if (backtrace_callee(PC, SP, LR, print_func) > 0) { /* Backtrace 2nd try: assume ReturnAddr is saved in LR when exception */ /* backtrace success, do not try other way */ goto exit; } else { /* Backtrace 3rd try: assume PC is invalalb, backtrace from LR */ backtrace_caller(LR, SP, print_func); } exit: return; }
YifuLiu/AliOS-Things
hardware/arch/armv8m/common/backtrace.c
C
apache-2.0
15,751
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> //#include "debug_api.h" #define REG_NAME_WIDTH 7 typedef struct { /* saved in assembler */ int R0; int R1; int R2; int R3; int R4; int R5; int R6; int R7; int R8; int R9; int R10; int R11; int R12; int LR; // Link Register (LR) int PC; // Program Counter (PC) int xPSR; // Program Status Registers int SP; // Stack Pointer int MSP; // Main stack pointer int PSP; // Process stack pointer int EXC_RETURN; // Exception Return int EXC_NUMBER; // Exception Num int PRIMASK; // Interrupt Mask int FAULTMASK; // Interrupt Mask int BASEPRI; // Interrupt Mask } PANIC_CONTEXT; typedef struct { int CFSR; int HFSR; int MMFAR; int BFAR; int AFSR; } FAULT_REGS; #if DEBUG_PANIC_CONTEXT_IN_STACK > 0 PANIC_CONTEXT g_panic_contex; #endif void panicGetCtx(void *context, char **pPC, char **pLR, int **pSP) { PANIC_CONTEXT *arm_context = (PANIC_CONTEXT *)context; *pSP = (int *)arm_context->SP; *pPC = (char *)arm_context->PC; *pLR = (char *)arm_context->LR; } void panicShowRegs(void *context, int (*print_func)(const char *fmt, ...)) { int x; int *regs = (int *)context; char s_panic_regs[REG_NAME_WIDTH + 14]; FAULT_REGS stFregs; /* PANIC_CONTEXT */ char s_panic_ctx[] = "R0 " "R1 " "R2 " "R3 " "R4 " "R5 " "R6 " "R7 " "R8 " "R9 " "R10 " "R11 " "R12 " "LR " "PC " "xPSR " "SP " "MSP " "PSP " "EXC_RET" "EXC_NUM" "PRIMASK" "FLTMASK" "BASEPRI"; /* FAULT_REGS */ char s_panic_reg[] = "CFSR " "HFSR " "MMFAR " "BFAR " "AFSR "; if (regs == NULL) { return; } print_func("========== Regs info ==========\r\n"); /* show PANIC_CONTEXT */ for (x = 0; x < sizeof(s_panic_ctx) / REG_NAME_WIDTH; x++) { memcpy(&s_panic_regs[0], &s_panic_ctx[x * REG_NAME_WIDTH], REG_NAME_WIDTH); memcpy(&s_panic_regs[REG_NAME_WIDTH], " 0x", 3); k_int2str(regs[x], &s_panic_regs[REG_NAME_WIDTH + 3]); s_panic_regs[REG_NAME_WIDTH + 11] = '\r'; s_panic_regs[REG_NAME_WIDTH + 12] = '\n'; s_panic_regs[REG_NAME_WIDTH + 13] = 0; print_func(s_panic_regs); } /* show FAULT_REGS */ stFregs.CFSR = (*((volatile int *)(0xE000ED28))); stFregs.HFSR = (*((volatile int *)(0xE000ED2C))); stFregs.MMFAR = (*((volatile int *)(0xE000ED34))); stFregs.BFAR = (*((volatile int *)(0xE000ED38))); stFregs.AFSR = (*((volatile int *)(0xE000ED3C))); for (x = 0; x < sizeof(stFregs) / sizeof(int); x++) { memcpy(&s_panic_regs[0], &s_panic_reg[x * REG_NAME_WIDTH], REG_NAME_WIDTH); memcpy(&s_panic_regs[REG_NAME_WIDTH], " 0x", 3); k_int2str(((int *)(&stFregs))[x], &s_panic_regs[REG_NAME_WIDTH + 3]); s_panic_regs[REG_NAME_WIDTH + 11] = '\r'; s_panic_regs[REG_NAME_WIDTH + 12] = '\n'; s_panic_regs[REG_NAME_WIDTH + 13] = 0; print_func(s_panic_regs); } } #if (RHINO_CONFIG_CLI_AS_NMI > 0) void panicNmiInputFilter(uint8_t ch) { static int check_cnt = 0; /* for '$#@!' */ if ( ch == '$' && check_cnt == 0) { check_cnt++; } else if ( ch == '#' && check_cnt == 1) { check_cnt++; } else if ( ch == '@' && check_cnt == 2) { check_cnt++; } else if ( ch == '!' && check_cnt == 3) { panicNmiFlagSet(); __asm__ __volatile__("udf":::"memory"); } else { check_cnt = 0; } } #else void panicNmiInputFilter(uint8_t ch){} #endif
YifuLiu/AliOS-Things
hardware/arch/armv8m/common/panic_c.c
C
apache-2.0
4,438
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited * * SPDX-License-Identifier: Apache-2.0 */ #include <k_api.h> void *cpu_task_stack_init(cpu_stack_t *stack_base, size_t stack_size, void *arg, task_entry_t entry) { cpu_stack_t *stk; uint32_t temp = (uint32_t)(stack_base + stack_size); /* stack aligned by 8 byte */ temp &= 0xfffffff8; stk = (cpu_stack_t *)temp; /* task context saved & restore by hardware: */ *(--stk) = (cpu_stack_t)0x01000000L; /* xPSR: EPSR.T = 1, thumb mode */ *(--stk) = (cpu_stack_t)entry; /* Entry Point */ *(--stk) = (cpu_stack_t)krhino_task_deathbed; /* R14 (LR) */ *(--stk) = (cpu_stack_t)0x12121212L; /* R12 */ *(--stk) = (cpu_stack_t)0x03030303L; /* R3 */ *(--stk) = (cpu_stack_t)0x02020202L; /* R2 */ *(--stk) = (cpu_stack_t)0x01010101L; /* R1 */ *(--stk) = (cpu_stack_t)arg; /* R0 : argument */ /* task context saved & restore by software: */ /* EXC_RETURN = 0xFFFFFFBCL Task begin state: Thread mode + non-floating-point state + PSP + Non-secure */ *(--stk) = (cpu_stack_t)0xFFFFFFBCL; *(--stk) = (cpu_stack_t)0x11111111L; /* R11 */ *(--stk) = (cpu_stack_t)0x10101010L; /* R10 */ *(--stk) = (cpu_stack_t)0x09090909L; /* R9 */ *(--stk) = (cpu_stack_t)0x08080808L; /* R8 */ *(--stk) = (cpu_stack_t)0x07070707L; /* R7 */ *(--stk) = (cpu_stack_t)0x06060606L; /* R6 */ *(--stk) = (cpu_stack_t)0x05050505L; /* R5 */ *(--stk) = (cpu_stack_t)0x04040404L; /* R4 */ return stk; }
YifuLiu/AliOS-Things
hardware/arch/armv8m/common/port_c.c
C
apache-2.0
1,743
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef BACKTRACE_H #define BACKTRACE_H /* printf call stack return levels of call stack */ int backtrace_now(int (*print_func)(const char *fmt, ...)); /* printf call stack for task return levels of call stack */ int backtrace_task(char *taskname, int (*print_func)(const char *fmt, ...)); /* backtrace start with PC and SP, find LR from stack memory return levels of call stack */ int backtrace_caller(char *PC, int *SP, int (*print_func)(const char *fmt, ...)); /* backtrace start with PC SP and LR return levels of call stack */ int backtrace_callee(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)); #endif /* BACKTRACE_H */
YifuLiu/AliOS-Things
hardware/arch/armv8m/include/backtrace.h
C
apache-2.0
773
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_COMPILER_H #define K_COMPILER_H #if defined(__CC_ARM) #define RHINO_INLINE static __inline /* get the return address of the current function unsigned int __return_address(void) */ #define RHINO_GET_RA() (void *)__return_address() /* get the the value of the stack pointer unsigned int __current_sp(void) */ #define RHINO_GET_SP() (void *)__current_sp() /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __builtin_clz(x) /* Returns the number of trailing 0-bits in x, starting at the least signifi cant bit position. */ #define RHINO_BIT_CTZ(x) __builtin_ctz(x) #ifndef RHINO_WEAK #define RHINO_WEAK __weak #endif #ifndef RHINO_ASM #define RHINO_ASM __asm #endif /* Instruction Synchronization Barrier */ #define OS_ISB() __isb(15) /* Full system Any-Any */ /* Data Memory Barrier */ #define OS_DMB() __dmb(15) /* Full system Any-Any */ /* Data Synchronization Barrier */ #define OS_DSB() __dsb(15) /* Full system Any-Any */ #elif defined(__ICCARM__) #include "intrinsics.h" #define RHINO_INLINE static inline /* get the return address of the current function unsigned int __get_LR(void) */ #define RHINO_GET_RA() (void *)__get_LR() /* get the the value of the stack pointer unsigned int __get_SP(void) */ #define RHINO_GET_SP() (void *)__get_SP() /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __CLZ(x) //#define RHINO_BIT_CTZ(x) #ifndef RHINO_WEAK #define RHINO_WEAK __weak #endif #ifndef RHINO_ASM #define RHINO_ASM asm #endif /* Instruction Synchronization Barrier */ #define OS_ISB() __isb(15) /* Full system Any-Any */ /* Data Memory Barrier */ #define OS_DMB() __dmb(15) /* Full system Any-Any */ /* Data Synchronization Barrier */ #define OS_DSB() __dsb(15) /* Full system Any-Any */ #elif defined(__GNUC__) #define RHINO_INLINE static inline /* get the return address of the current function void * __builtin_return_address (unsigned int level) */ #define RHINO_GET_RA() __builtin_return_address(0) /* get the return address of the current function */ __attribute__((always_inline)) RHINO_INLINE void *RHINO_GET_SP(void) { void *sp; __asm__ volatile("mov %0, SP\n":"=r"(sp)); return sp; } /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __builtin_clz(x) /* Returns the number of trailing 0-bits in x, starting at the least signifi cant bit position. */ #define RHINO_BIT_CTZ(x) __builtin_ctz(x) #ifndef RHINO_WEAK #define RHINO_WEAK __attribute__((weak)) #endif #ifndef RHINO_ASM #define RHINO_ASM __asm__ #endif /* Instruction Synchronization Barrier */ #define OS_ISB() __asm volatile ("isb sy":::"memory") /* Data Memory Barrier */ #define OS_DMB() __asm volatile ("dmb sy":::"memory") /* Data Synchronization Barrier */ #define OS_DSB() __asm volatile ("dsb sy":::"memory") /* Undefine exception */ #define OS_UDF() __asm volatile ("udf":::"memory") #else #error "Unsupported compiler" #endif #endif /* K_COMPILER_H */
YifuLiu/AliOS-Things
hardware/arch/armv8m/include/k_compiler.h
C
apache-2.0
3,686
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_TYPES_H #define K_TYPES_H #include "k_compiler.h" #define RHINO_TASK_STACK_OVF_MAGIC 0xdeadbeafu /* stack overflow magic value */ #define RHINO_INTRPT_STACK_OVF_MAGIC 0xdeaddeadu /* stack overflow magic value */ #define RHINO_MM_CORRUPT_DYE 0xFEFEFEFE #define RHINO_MM_FREE_DYE 0xABABABAB typedef uint32_t cpu_stack_t; typedef uint32_t hr_timer_t; typedef uint32_t lr_timer_t; typedef uint32_t cpu_cpsr_t; #endif /* K_TYPES_H */
YifuLiu/AliOS-Things
hardware/arch/armv8m/include/k_types.h
C
apache-2.0
538
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef PORT_H #define PORT_H cpu_cpsr_t cpu_intrpt_save(void); void cpu_intrpt_restore(cpu_cpsr_t cpsr); void cpu_intrpt_switch(void); void cpu_task_switch(void); void cpu_first_task_start(void); void *cpu_task_stack_init(cpu_stack_t *base, size_t size, void *arg, task_entry_t entry); RHINO_INLINE uint8_t cpu_cur_get(void) { return 0; } #define CPSR_ALLOC() cpu_cpsr_t cpsr #define RHINO_CPU_INTRPT_DISABLE() do{cpsr = cpu_intrpt_save();}while(0) #define RHINO_CPU_INTRPT_ENABLE() do{cpu_intrpt_restore(cpsr);}while(0) #endif /* PORT_H */
YifuLiu/AliOS-Things
hardware/arch/armv8m/include/port.h
C
apache-2.0
643
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_API_H #define K_API_H /** @addtogroup rhino API * All rhino header files. * * @{ */ #include <stddef.h> #include <stdint.h> #include <string.h> #include <limits.h> #include "k_config.h" #include "k_default_config.h" #include "k_types.h" #include "k_err.h" #include "k_sys.h" #include "k_critical.h" #include "k_spin_lock.h" #include "k_list.h" #if (RHINO_CONFIG_SCHED_CFS > 0) #include "k_cfs.h" #endif #include "k_obj.h" #include "k_sched.h" #include "k_task.h" #include "k_ringbuf.h" #include "k_queue.h" #include "k_buf_queue.h" #include "k_sem.h" #include "k_task_sem.h" #include "k_mutex.h" #include "k_timer.h" #include "k_time.h" #include "k_event.h" #include "k_stats.h" #if RHINO_CONFIG_MM_DEBUG #include "k_mm_debug.h" #endif #include "k_mm_blk.h" #include "k_mm_region.h" #include "k_mm.h" #include "k_workqueue.h" #include "k_internal.h" #include "k_trace.h" #include "k_soc.h" #include "k_hook.h" #include "k_bitmap.h" #include "port.h" /** @} */ #endif /* K_API_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32_32gpr/k_api.h
C
apache-2.0
1,071
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_ARCH_H #define K_ARCH_H #include "riscv_csr.h" #if __riscv_xlen == 64 #define REGISTER_LEN 8 #define OS_UDF() \ do { \ *(long *)(0xffffffffffffffff) = 1; \ } while (0) #elif __riscv_xlen == 32 #define REGISTER_LEN 4 #define OS_UDF() \ do { \ *(long *)(0xffffffff) = 1; \ } while (0) #else #error Assembler did not define __riscv_xlen #endif /* Exception Code */ #define CAUSE_MISALIGNED_FETCH 0x0 #define CAUSE_FETCH_ACCESS 0x1 #define CAUSE_ILLEGAL_INSTRUCTION 0x2 #define CAUSE_BREAKPOINT 0x3 #define CAUSE_MISALIGNED_LOAD 0x4 #define CAUSE_LOAD_ACCESS 0x5 #define CAUSE_MISALIGNED_STORE 0x6 #define CAUSE_STORE_ACCESS 0x7 #define CAUSE_USER_ECALL 0x8 #define CAUSE_HYPERVISOR_ECALL 0x9 #define CAUSE_SUPERVISOR_ECALL 0xa #define CAUSE_MACHINE_ECALL 0xb #define CAUSE_FETCH_PAGE_FAULT 0xc #define CAUSE_LOAD_PAGE_FAULT 0xd #define CAUSE_STORE_PAGE_FAULT 0xf #define CAUSE_FETCH_GUEST_PAGE_FAULT 0x14 #define CAUSE_LOAD_GUEST_PAGE_FAULT 0x15 #define CAUSE_STORE_GUEST_PAGE_FAULT 0x17 #ifndef __ASSEMBLY__ typedef struct { long X1; long X2; long X3; long X4; long X5; long X6; long X7; long X8; long X9; long X10; long X11; long X12; long X13; long X14; long X15; long X16; long X17; long X18; long X19; long X20; long X21; long X22; long X23; long X24; long X25; long X26; long X27; long X28; long X29; long X30; long X31; long PC; long MSTATUS; #ifdef RISCV_SUPPORT_FPU long FPU[32]; #endif } context_t; #else /* Define the offset of the register in the task context */ #define BASE_CONTEXT_LEN (33 * REGISTER_LEN) #define FLOAT_CONTEXT_LEN (32 * REGISTER_LEN) #define X1_OFFSET 0 #define X2_OFFSET (X1_OFFSET + REGISTER_LEN) #define X3_OFFSET (X2_OFFSET + REGISTER_LEN) #define X4_OFFSET (X3_OFFSET + REGISTER_LEN) #define X5_OFFSET (X4_OFFSET + REGISTER_LEN) #define X6_OFFSET (X5_OFFSET + REGISTER_LEN) #define X7_OFFSET (X6_OFFSET + REGISTER_LEN) #define X8_OFFSET (X7_OFFSET + REGISTER_LEN) #define X9_OFFSET (X8_OFFSET + REGISTER_LEN) #define X10_OFFSET (X9_OFFSET + REGISTER_LEN) #define X11_OFFSET (X10_OFFSET + REGISTER_LEN) #define X12_OFFSET (X11_OFFSET + REGISTER_LEN) #define X13_OFFSET (X12_OFFSET + REGISTER_LEN) #define X14_OFFSET (X13_OFFSET + REGISTER_LEN) #define X15_OFFSET (X14_OFFSET + REGISTER_LEN) #define X16_OFFSET (X15_OFFSET + REGISTER_LEN) #define X17_OFFSET (X16_OFFSET + REGISTER_LEN) #define X18_OFFSET (X17_OFFSET + REGISTER_LEN) #define X19_OFFSET (X18_OFFSET + REGISTER_LEN) #define X20_OFFSET (X19_OFFSET + REGISTER_LEN) #define X21_OFFSET (X20_OFFSET + REGISTER_LEN) #define X22_OFFSET (X21_OFFSET + REGISTER_LEN) #define X23_OFFSET (X22_OFFSET + REGISTER_LEN) #define X24_OFFSET (X23_OFFSET + REGISTER_LEN) #define X25_OFFSET (X24_OFFSET + REGISTER_LEN) #define X26_OFFSET (X25_OFFSET + REGISTER_LEN) #define X27_OFFSET (X26_OFFSET + REGISTER_LEN) #define X28_OFFSET (X27_OFFSET + REGISTER_LEN) #define X29_OFFSET (X28_OFFSET + REGISTER_LEN) #define X30_OFFSET (X29_OFFSET + REGISTER_LEN) #define X31_OFFSET (X30_OFFSET + REGISTER_LEN) #define PC_OFFSET (X31_OFFSET + REGISTER_LEN) #define MSTATUS_OFFSET (PC_OFFSET + REGISTER_LEN) #define F0_OFFSET (0) #define F1_OFFSET (F0_OFFSET + REGISTER_LEN) #define F2_OFFSET (F1_OFFSET + REGISTER_LEN) #define F3_OFFSET (F2_OFFSET + REGISTER_LEN) #define F4_OFFSET (F3_OFFSET + REGISTER_LEN) #define F5_OFFSET (F4_OFFSET + REGISTER_LEN) #define F6_OFFSET (F5_OFFSET + REGISTER_LEN) #define F7_OFFSET (F6_OFFSET + REGISTER_LEN) #define F8_OFFSET (F7_OFFSET + REGISTER_LEN) #define F9_OFFSET (F8_OFFSET + REGISTER_LEN) #define F10_OFFSET (F9_OFFSET + REGISTER_LEN) #define F11_OFFSET (F10_OFFSET + REGISTER_LEN) #define F12_OFFSET (F11_OFFSET + REGISTER_LEN) #define F13_OFFSET (F12_OFFSET + REGISTER_LEN) #define F14_OFFSET (F13_OFFSET + REGISTER_LEN) #define F15_OFFSET (F14_OFFSET + REGISTER_LEN) #define F16_OFFSET (F15_OFFSET + REGISTER_LEN) #define F17_OFFSET (F16_OFFSET + REGISTER_LEN) #define F18_OFFSET (F17_OFFSET + REGISTER_LEN) #define F19_OFFSET (F18_OFFSET + REGISTER_LEN) #define F20_OFFSET (F19_OFFSET + REGISTER_LEN) #define F21_OFFSET (F20_OFFSET + REGISTER_LEN) #define F22_OFFSET (F21_OFFSET + REGISTER_LEN) #define F23_OFFSET (F22_OFFSET + REGISTER_LEN) #define F24_OFFSET (F23_OFFSET + REGISTER_LEN) #define F25_OFFSET (F24_OFFSET + REGISTER_LEN) #define F26_OFFSET (F25_OFFSET + REGISTER_LEN) #define F27_OFFSET (F26_OFFSET + REGISTER_LEN) #define F28_OFFSET (F27_OFFSET + REGISTER_LEN) #define F29_OFFSET (F28_OFFSET + REGISTER_LEN) #define F30_OFFSET (F29_OFFSET + REGISTER_LEN) #define F31_OFFSET (F30_OFFSET + REGISTER_LEN) #endif #endif /* K_ARCH_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32_32gpr/k_arch.h
C
apache-2.0
5,167
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef PORT_H #define PORT_H #include <k_types.h> #include <k_task.h> #ifdef CONFIG_OS_TRACE #include <trcTrig.h> #include <trcUser.h> #include <trcKernelPort.h> #endif cpu_cpsr_t cpu_intrpt_save(void); void cpu_intrpt_restore(cpu_cpsr_t cpsr); void cpu_intrpt_switch(void); void cpu_task_switch(void); void cpu_first_task_start(void); void *cpu_task_stack_init(cpu_stack_t *base, size_t size, void *arg, task_entry_t entry); RHINO_INLINE uint8_t cpu_cur_get(void) { return 0; } #define CPSR_ALLOC() cpu_cpsr_t cpsr #define RHINO_CPU_INTRPT_DISABLE() do { cpsr = cpu_intrpt_save(); } while (0) #define RHINO_CPU_INTRPT_ENABLE() do { cpu_intrpt_restore(cpsr); } while (0) #endif /* PORT_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32_32gpr/port.h
C
apache-2.0
797
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef RISCV_CSR_H #define RISCV_CSR_H /* Status register flags */ #define SR_SIE 0x00000002UL /* Supervisor Interrupt Enable */ #define SR_MIE 0x00000008UL /* Machine Interrupt Enable */ #define SR_SPIE 0x00000020UL /* Previous Supervisor IE */ #define SR_MPIE 0x00000080UL /* Previous Machine IE */ #define SR_SPP 0x00000100UL /* Previously Supervisor mode */ #define SR_MPP_U 0x00000000UL /* Previously User mode */ #define SR_MPP_S 0x00000800UL /* Previously Supervisor mode */ #define SR_MPP_M 0x00001800UL /* Previously Machine mode */ #define SR_SUM 0x00040000UL /* Supervisor User Memory Access */ #define SR_FS 0x00006000UL /* Floating-point Status */ #define SR_FS_OFF 0x00000000UL #define SR_FS_INITIAL 0x00002000UL #define SR_FS_CLEAN 0x00004000UL #define SR_FS_DIRTY 0x00006000UL /* Interrupt-enable Registers */ #define IE_MTIE 0x00000080UL #define IE_MEIE 0x00000800UL #endif
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32_32gpr/riscv_csr.h
C
apache-2.0
1,117
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_ARCH_H #define K_ARCH_H #include "riscv_csr.h" #if __riscv_xlen == 64 #define REGISTER_LEN 8 #define OS_UDF() \ do { \ *(long *)(0xffffffffffffffff) = 1; \ } while (0) #elif __riscv_xlen == 32 #define REGISTER_LEN 4 #define OS_UDF() \ do { \ *(long *)(0xffffffff) = 1; \ } while (0) #else #error Assembler did not define __riscv_xlen #endif /* Exception Code */ #define CAUSE_MISALIGNED_FETCH 0x0 #define CAUSE_FETCH_ACCESS 0x1 #define CAUSE_ILLEGAL_INSTRUCTION 0x2 #define CAUSE_BREAKPOINT 0x3 #define CAUSE_MISALIGNED_LOAD 0x4 #define CAUSE_LOAD_ACCESS 0x5 #define CAUSE_MISALIGNED_STORE 0x6 #define CAUSE_STORE_ACCESS 0x7 #define CAUSE_USER_ECALL 0x8 #define CAUSE_HYPERVISOR_ECALL 0x9 #define CAUSE_SUPERVISOR_ECALL 0xa #define CAUSE_MACHINE_ECALL 0xb #define CAUSE_FETCH_PAGE_FAULT 0xc #define CAUSE_LOAD_PAGE_FAULT 0xd #define CAUSE_STORE_PAGE_FAULT 0xf #define CAUSE_FETCH_GUEST_PAGE_FAULT 0x14 #define CAUSE_LOAD_GUEST_PAGE_FAULT 0x15 #define CAUSE_STORE_GUEST_PAGE_FAULT 0x17 #ifndef __ASSEMBLY__ typedef struct { long X1; long X4; long X5; long X6; long X7; long X8; long X9; long X10; long X11; long X12; long X13; long X14; long X15; long X16; long X17; long X18; long X19; long X20; long X21; long X22; long X23; long X24; long X25; long X26; long X27; long X28; long X29; long X30; long X31; long PC; long MSTATUS; long FPU[32]; } context_t; #else /* Define the offset of the register in the task context */ #define BASE_CONTEXT_LEN (31 * REGISTER_LEN) #define FLOAT_CONTEXT_LEN (32 * REGISTER_LEN) #define X1_OFFSET 0 #define X4_OFFSET (X1_OFFSET + REGISTER_LEN) #define X5_OFFSET (X4_OFFSET + REGISTER_LEN) #define X6_OFFSET (X5_OFFSET + REGISTER_LEN) #define X7_OFFSET (X6_OFFSET + REGISTER_LEN) #define X8_OFFSET (X7_OFFSET + REGISTER_LEN) #define X9_OFFSET (X8_OFFSET + REGISTER_LEN) #define X10_OFFSET (X9_OFFSET + REGISTER_LEN) #define X11_OFFSET (X10_OFFSET + REGISTER_LEN) #define X12_OFFSET (X11_OFFSET + REGISTER_LEN) #define X13_OFFSET (X12_OFFSET + REGISTER_LEN) #define X14_OFFSET (X13_OFFSET + REGISTER_LEN) #define X15_OFFSET (X14_OFFSET + REGISTER_LEN) #define X16_OFFSET (X15_OFFSET + REGISTER_LEN) #define X17_OFFSET (X16_OFFSET + REGISTER_LEN) #define X18_OFFSET (X17_OFFSET + REGISTER_LEN) #define X19_OFFSET (X18_OFFSET + REGISTER_LEN) #define X20_OFFSET (X19_OFFSET + REGISTER_LEN) #define X21_OFFSET (X20_OFFSET + REGISTER_LEN) #define X22_OFFSET (X21_OFFSET + REGISTER_LEN) #define X23_OFFSET (X22_OFFSET + REGISTER_LEN) #define X24_OFFSET (X23_OFFSET + REGISTER_LEN) #define X25_OFFSET (X24_OFFSET + REGISTER_LEN) #define X26_OFFSET (X25_OFFSET + REGISTER_LEN) #define X27_OFFSET (X26_OFFSET + REGISTER_LEN) #define X28_OFFSET (X27_OFFSET + REGISTER_LEN) #define X29_OFFSET (X28_OFFSET + REGISTER_LEN) #define X30_OFFSET (X29_OFFSET + REGISTER_LEN) #define X31_OFFSET (X30_OFFSET + REGISTER_LEN) #define PC_OFFSET (X31_OFFSET + REGISTER_LEN) #define MSTATUS_OFFSET (PC_OFFSET + REGISTER_LEN) #define F0_OFFSET (0) #define F1_OFFSET (F0_OFFSET + REGISTER_LEN) #define F2_OFFSET (F1_OFFSET + REGISTER_LEN) #define F3_OFFSET (F2_OFFSET + REGISTER_LEN) #define F4_OFFSET (F3_OFFSET + REGISTER_LEN) #define F5_OFFSET (F4_OFFSET + REGISTER_LEN) #define F6_OFFSET (F5_OFFSET + REGISTER_LEN) #define F7_OFFSET (F6_OFFSET + REGISTER_LEN) #define F8_OFFSET (F7_OFFSET + REGISTER_LEN) #define F9_OFFSET (F8_OFFSET + REGISTER_LEN) #define F10_OFFSET (F9_OFFSET + REGISTER_LEN) #define F11_OFFSET (F10_OFFSET + REGISTER_LEN) #define F12_OFFSET (F11_OFFSET + REGISTER_LEN) #define F13_OFFSET (F12_OFFSET + REGISTER_LEN) #define F14_OFFSET (F13_OFFSET + REGISTER_LEN) #define F15_OFFSET (F14_OFFSET + REGISTER_LEN) #define F16_OFFSET (F15_OFFSET + REGISTER_LEN) #define F17_OFFSET (F16_OFFSET + REGISTER_LEN) #define F18_OFFSET (F17_OFFSET + REGISTER_LEN) #define F19_OFFSET (F18_OFFSET + REGISTER_LEN) #define F20_OFFSET (F19_OFFSET + REGISTER_LEN) #define F21_OFFSET (F20_OFFSET + REGISTER_LEN) #define F22_OFFSET (F21_OFFSET + REGISTER_LEN) #define F23_OFFSET (F22_OFFSET + REGISTER_LEN) #define F24_OFFSET (F23_OFFSET + REGISTER_LEN) #define F25_OFFSET (F24_OFFSET + REGISTER_LEN) #define F26_OFFSET (F25_OFFSET + REGISTER_LEN) #define F27_OFFSET (F26_OFFSET + REGISTER_LEN) #define F28_OFFSET (F27_OFFSET + REGISTER_LEN) #define F29_OFFSET (F28_OFFSET + REGISTER_LEN) #define F30_OFFSET (F29_OFFSET + REGISTER_LEN) #define F31_OFFSET (F30_OFFSET + REGISTER_LEN) #endif #endif /* K_ARCH_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32fd_32gpr/k_arch.h
C
apache-2.0
5,017
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_TYPES_H #define K_TYPES_H #include "k_compiler.h" #if __riscv_xlen == 64 #define RHINO_TASK_STACK_OVF_MAGIC 0xdeadbeafdeadbeafull /* stack overflow magic value */ #define RHINO_INTRPT_STACK_OVF_MAGIC 0xdeadbeafdeadbeafull /* stack overflow magic value */ #define RHINO_MM_FRAG_ALLOCATED 0xabcddcababcddcabull /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_FRAG_FREE 0xfefdecdbfefdecdbull /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_CORRUPT_DYE 0xFEFEFEFEFEFEFEFEULL #define RHINO_MM_FREE_DYE 0xABABABABABABABABULL #define AOS_ARCH_LP64 1 typedef uint64_t cpu_stack_t; typedef uint64_t cpu_cpsr_t; #elif __riscv_xlen == 32 #define RHINO_TASK_STACK_OVF_MAGIC 0xdeadbeafu /* stack overflow magic value */ #define RHINO_INTRPT_STACK_OVF_MAGIC 0xdeadbeafu /* stack overflow magic value */ #define RHINO_MM_FRAG_ALLOCATED 0xabcddcabu /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_FRAG_FREE 0xfefdecdbu /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_CORRUPT_DYE 0xFEFEFEFEU #define RHINO_MM_FREE_DYE 0xABABABABU typedef uint32_t cpu_stack_t; typedef uint32_t cpu_cpsr_t; #else #error Assembler did not define __riscv_xlen #endif typedef uint64_t hr_timer_t; typedef uint64_t lr_timer_t; #endif /* K_TYPES_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32fd_32gpr/k_types.h
C
apache-2.0
1,562
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef PORT_H #define PORT_H #include <k_types.h> #include <k_task.h> #ifdef CONFIG_OS_TRACE #include <trcTrig.h> #include <trcUser.h> #include <trcKernelPort.h> #endif cpu_cpsr_t cpu_intrpt_save(void); void cpu_intrpt_restore(cpu_cpsr_t cpsr); void cpu_intrpt_switch(void); void cpu_task_switch(void); void cpu_first_task_start(void); void *cpu_task_stack_init(cpu_stack_t *base, size_t size, void *arg, task_entry_t entry); RHINO_INLINE uint8_t cpu_cur_get(void) { return 0; } #define CPSR_ALLOC() cpu_cpsr_t cpsr #define RHINO_CPU_INTRPT_DISABLE() do { cpsr = cpu_intrpt_save(); } while (0) #define RHINO_CPU_INTRPT_ENABLE() do { cpu_intrpt_restore(cpsr); } while (0) #endif /* PORT_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32fd_32gpr/port.h
C
apache-2.0
797
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef RISCV_CSR_H #define RISCV_CSR_H /* Status register flags */ #define SR_SIE 0x00000002UL /* Supervisor Interrupt Enable */ #define SR_MIE 0x00000008UL /* Machine Interrupt Enable */ #define SR_SPIE 0x00000020UL /* Previous Supervisor IE */ #define SR_MPIE 0x00000080UL /* Previous Machine IE */ #define SR_SPP 0x00000100UL /* Previously Supervisor mode */ #define SR_MPP_U 0x00000000UL /* Previously User mode */ #define SR_MPP_S 0x00000800UL /* Previously Supervisor mode */ #define SR_MPP_M 0x00001800UL /* Previously Machine mode */ #define SR_SUM 0x00040000UL /* Supervisor User Memory Access */ #define SR_FS 0x00006000UL /* Floating-point Status */ #define SR_FS_OFF 0x00000000UL #define SR_FS_INITIAL 0x00002000UL #define SR_FS_CLEAN 0x00004000UL #define SR_FS_DIRTY 0x00006000UL /* Interrupt-enable Registers */ #define IE_MTIE 0x00000080UL #define IE_MEIE 0x00000800UL #endif
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv32fd_32gpr/riscv_csr.h
C
apache-2.0
1,117
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_ARCH_H #define K_ARCH_H #include "riscv_csr.h" #if __riscv_xlen == 64 #define REGISTER_LEN 8 #define OS_UDF() \ do { \ *(long *)(0xffffffffffffffff) = 1; \ } while (0) #elif __riscv_xlen == 32 #define REGISTER_LEN 4 #define OS_UDF() \ do { \ *(long *)(0xffffffff) = 1; \ } while (0) #else #error Assembler did not define __riscv_xlen #endif /* Exception Code */ #define CAUSE_MISALIGNED_FETCH 0x0 #define CAUSE_FETCH_ACCESS 0x1 #define CAUSE_ILLEGAL_INSTRUCTION 0x2 #define CAUSE_BREAKPOINT 0x3 #define CAUSE_MISALIGNED_LOAD 0x4 #define CAUSE_LOAD_ACCESS 0x5 #define CAUSE_MISALIGNED_STORE 0x6 #define CAUSE_STORE_ACCESS 0x7 #define CAUSE_USER_ECALL 0x8 #define CAUSE_HYPERVISOR_ECALL 0x9 #define CAUSE_SUPERVISOR_ECALL 0xa #define CAUSE_MACHINE_ECALL 0xb #define CAUSE_FETCH_PAGE_FAULT 0xc #define CAUSE_LOAD_PAGE_FAULT 0xd #define CAUSE_STORE_PAGE_FAULT 0xf #define CAUSE_FETCH_GUEST_PAGE_FAULT 0x14 #define CAUSE_LOAD_GUEST_PAGE_FAULT 0x15 #define CAUSE_STORE_GUEST_PAGE_FAULT 0x17 #ifndef __ASSEMBLY__ typedef struct { long X1; long X4; long X5; long X6; long X7; long X8; long X9; long X10; long X11; long X12; long X13; long X14; long X15; long X16; long X17; long X18; long X19; long X20; long X21; long X22; long X23; long X24; long X25; long X26; long X27; long X28; long X29; long X30; long X31; long PC; long MSTATUS; long FPU[32]; } context_t; #else /* Define the offset of the register in the task context */ #define BASE_CONTEXT_LEN (31 * REGISTER_LEN) #define FLOAT_CONTEXT_LEN (32 * REGISTER_LEN) #define X1_OFFSET 0 #define X4_OFFSET (X1_OFFSET + REGISTER_LEN) #define X5_OFFSET (X4_OFFSET + REGISTER_LEN) #define X6_OFFSET (X5_OFFSET + REGISTER_LEN) #define X7_OFFSET (X6_OFFSET + REGISTER_LEN) #define X8_OFFSET (X7_OFFSET + REGISTER_LEN) #define X9_OFFSET (X8_OFFSET + REGISTER_LEN) #define X10_OFFSET (X9_OFFSET + REGISTER_LEN) #define X11_OFFSET (X10_OFFSET + REGISTER_LEN) #define X12_OFFSET (X11_OFFSET + REGISTER_LEN) #define X13_OFFSET (X12_OFFSET + REGISTER_LEN) #define X14_OFFSET (X13_OFFSET + REGISTER_LEN) #define X15_OFFSET (X14_OFFSET + REGISTER_LEN) #define X16_OFFSET (X15_OFFSET + REGISTER_LEN) #define X17_OFFSET (X16_OFFSET + REGISTER_LEN) #define X18_OFFSET (X17_OFFSET + REGISTER_LEN) #define X19_OFFSET (X18_OFFSET + REGISTER_LEN) #define X20_OFFSET (X19_OFFSET + REGISTER_LEN) #define X21_OFFSET (X20_OFFSET + REGISTER_LEN) #define X22_OFFSET (X21_OFFSET + REGISTER_LEN) #define X23_OFFSET (X22_OFFSET + REGISTER_LEN) #define X24_OFFSET (X23_OFFSET + REGISTER_LEN) #define X25_OFFSET (X24_OFFSET + REGISTER_LEN) #define X26_OFFSET (X25_OFFSET + REGISTER_LEN) #define X27_OFFSET (X26_OFFSET + REGISTER_LEN) #define X28_OFFSET (X27_OFFSET + REGISTER_LEN) #define X29_OFFSET (X28_OFFSET + REGISTER_LEN) #define X30_OFFSET (X29_OFFSET + REGISTER_LEN) #define X31_OFFSET (X30_OFFSET + REGISTER_LEN) #define PC_OFFSET (X31_OFFSET + REGISTER_LEN) #define MSTATUS_OFFSET (PC_OFFSET + REGISTER_LEN) #define F0_OFFSET (0) #define F1_OFFSET (F0_OFFSET + REGISTER_LEN) #define F2_OFFSET (F1_OFFSET + REGISTER_LEN) #define F3_OFFSET (F2_OFFSET + REGISTER_LEN) #define F4_OFFSET (F3_OFFSET + REGISTER_LEN) #define F5_OFFSET (F4_OFFSET + REGISTER_LEN) #define F6_OFFSET (F5_OFFSET + REGISTER_LEN) #define F7_OFFSET (F6_OFFSET + REGISTER_LEN) #define F8_OFFSET (F7_OFFSET + REGISTER_LEN) #define F9_OFFSET (F8_OFFSET + REGISTER_LEN) #define F10_OFFSET (F9_OFFSET + REGISTER_LEN) #define F11_OFFSET (F10_OFFSET + REGISTER_LEN) #define F12_OFFSET (F11_OFFSET + REGISTER_LEN) #define F13_OFFSET (F12_OFFSET + REGISTER_LEN) #define F14_OFFSET (F13_OFFSET + REGISTER_LEN) #define F15_OFFSET (F14_OFFSET + REGISTER_LEN) #define F16_OFFSET (F15_OFFSET + REGISTER_LEN) #define F17_OFFSET (F16_OFFSET + REGISTER_LEN) #define F18_OFFSET (F17_OFFSET + REGISTER_LEN) #define F19_OFFSET (F18_OFFSET + REGISTER_LEN) #define F20_OFFSET (F19_OFFSET + REGISTER_LEN) #define F21_OFFSET (F20_OFFSET + REGISTER_LEN) #define F22_OFFSET (F21_OFFSET + REGISTER_LEN) #define F23_OFFSET (F22_OFFSET + REGISTER_LEN) #define F24_OFFSET (F23_OFFSET + REGISTER_LEN) #define F25_OFFSET (F24_OFFSET + REGISTER_LEN) #define F26_OFFSET (F25_OFFSET + REGISTER_LEN) #define F27_OFFSET (F26_OFFSET + REGISTER_LEN) #define F28_OFFSET (F27_OFFSET + REGISTER_LEN) #define F29_OFFSET (F28_OFFSET + REGISTER_LEN) #define F30_OFFSET (F29_OFFSET + REGISTER_LEN) #define F31_OFFSET (F30_OFFSET + REGISTER_LEN) #endif #endif /* K_ARCH_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv64fd_32gpr/k_arch.h
C
apache-2.0
5,017
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_TYPES_H #define K_TYPES_H #include "k_compiler.h" #if __riscv_xlen == 64 #define RHINO_TASK_STACK_OVF_MAGIC 0xdeadbeafdeadbeafull /* stack overflow magic value */ #define RHINO_INTRPT_STACK_OVF_MAGIC 0xdeadbeafdeadbeafull /* stack overflow magic value */ #define RHINO_MM_FRAG_ALLOCATED 0xabcddcababcddcabull /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_FRAG_FREE 0xfefdecdbfefdecdbull /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_CORRUPT_DYE 0xFEFEFEFEFEFEFEFEULL #define RHINO_MM_FREE_DYE 0xABABABABABABABABULL #define AOS_ARCH_LP64 1 typedef uint64_t cpu_stack_t; typedef uint64_t cpu_cpsr_t; #elif __riscv_xlen == 32 #define RHINO_TASK_STACK_OVF_MAGIC 0xdeadbeafu /* stack overflow magic value */ #define RHINO_INTRPT_STACK_OVF_MAGIC 0xdeadbeafu /* stack overflow magic value */ #define RHINO_MM_FRAG_ALLOCATED 0xabcddcabu /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_FRAG_FREE 0xfefdecdbu /* 32 bit value, if 64 bit system, you need change it to 64 bit */ #define RHINO_MM_CORRUPT_DYE 0xFEFEFEFEU #define RHINO_MM_FREE_DYE 0xABABABABU typedef uint32_t cpu_stack_t; typedef uint32_t cpu_cpsr_t; #else #error Assembler did not define __riscv_xlen #endif typedef uint64_t hr_timer_t; typedef uint64_t lr_timer_t; #endif /* K_TYPES_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv64fd_32gpr/k_types.h
C
apache-2.0
1,562
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef PORT_H #define PORT_H #include <k_types.h> #include <k_task.h> #ifdef CONFIG_OS_TRACE #include <trcTrig.h> #include <trcUser.h> #include <trcKernelPort.h> #endif cpu_cpsr_t cpu_intrpt_save(void); void cpu_intrpt_restore(cpu_cpsr_t cpsr); void cpu_intrpt_switch(void); void cpu_task_switch(void); void cpu_first_task_start(void); void *cpu_task_stack_init(cpu_stack_t *base, size_t size, void *arg, task_entry_t entry); RHINO_INLINE uint8_t cpu_cur_get(void) { return 0; } #define CPSR_ALLOC() cpu_cpsr_t cpsr #define RHINO_CPU_INTRPT_DISABLE() do { cpsr = cpu_intrpt_save(); } while (0) #define RHINO_CPU_INTRPT_ENABLE() do { cpu_intrpt_restore(cpsr); } while (0) #endif /* PORT_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv64fd_32gpr/port.h
C
apache-2.0
797
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef RISCV_CSR_H #define RISCV_CSR_H /* Status register flags */ #define SR_SIE 0x00000002UL /* Supervisor Interrupt Enable */ #define SR_MIE 0x00000008UL /* Machine Interrupt Enable */ #define SR_SPIE 0x00000020UL /* Previous Supervisor IE */ #define SR_MPIE 0x00000080UL /* Previous Machine IE */ #define SR_SPP 0x00000100UL /* Previously Supervisor mode */ #define SR_MPP_U 0x00000000UL /* Previously User mode */ #define SR_MPP_S 0x00000800UL /* Previously Supervisor mode */ #define SR_MPP_M 0x00001800UL /* Previously Machine mode */ #define SR_SUM 0x00040000UL /* Supervisor User Memory Access */ #define SR_FS 0x00006000UL /* Floating-point Status */ #define SR_FS_OFF 0x00000000UL #define SR_FS_INITIAL 0x00002000UL #define SR_FS_CLEAN 0x00004000UL #define SR_FS_DIRTY 0x00006000UL /* Interrupt-enable Registers */ #define IE_MTIE 0x00000080UL #define IE_MEIE 0x00000800UL #endif
YifuLiu/AliOS-Things
hardware/arch/riscv/include/rv64fd_32gpr/riscv_csr.h
C
apache-2.0
1,117
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <k_api.h> #include <k_arch.h> void dispatcher_exception(long arg, long exc_type, context_t *contex) { switch (exc_type) { case CAUSE_MACHINE_ECALL: /* This is a task scheduling request */ if (arg == 0) { return; } break; default: break; } return; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32_32gpr/dispatcher_c.c
C
apache-2.0
398
#include <k_config.h> #include <k_arch.h> /****************************************************************************** @ Declares the function that this file will call @******************************************************************************/ .extern g_active_task .extern g_preferred_ready_task .extern krhino_stack_ovf_check .extern krhino_task_sched_stats_get .extern exception_stack_top .extern dispatcher_exception .extern dispatcher_interrupt .global task_restore .global _interrupt_return_address .global ht_dispatcher .global sys_stack_base .global sys_stack_top .global exception_stack_base .global exception_stack_top /****************************************************************************** @ Exception Vector. mtvec.mode must be set to 0, exceptions and interrupts use @ the same vector entry @******************************************************************************/ #define CONFIG_ARCH_INTERRUPTSTACK 4096 .section .bss .align 3 sys_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK sys_stack_top: exception_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK exception_stack_top: .section .vectors .align 6 .globl __Vectors .type __Vectors, @object __Vectors: j ht_dispatcher /****************************************************************************** @ Jump to this function when an exception or interrupt occurs. This function is @ used to schedule the execution flow of exceptions, interrupts, and tasks. @ System call 0 is used to trigger task scheduling. @******************************************************************************/ .text .align 8 .func ht_dispatcher: /* first step: save context */ #ifdef RISCV_SUPPORT_FPU addi sp, sp, -(FLOAT_CONTEXT_LEN) fsw f0, (F0_OFFSET)(sp) fsw f1, (F1_OFFSET)(sp) fsw f2, (F2_OFFSET)(sp) fsw f3, (F3_OFFSET)(sp) fsw f4, (F4_OFFSET)(sp) fsw f5, (F5_OFFSET)(sp) fsw f6, (F6_OFFSET)(sp) fsw f7, (F7_OFFSET)(sp) fsw f8, (F8_OFFSET)(sp) fsw f9, (F9_OFFSET)(sp) fsw f10,(F10_OFFSET)(sp) fsw f11,(F11_OFFSET)(sp) fsw f12,(F12_OFFSET)(sp) fsw f13,(F13_OFFSET)(sp) fsw f14,(F14_OFFSET)(sp) fsw f15,(F15_OFFSET)(sp) fsw f16,(F16_OFFSET)(sp) fsw f17,(F17_OFFSET)(sp) fsw f18,(F18_OFFSET)(sp) fsw f19,(F19_OFFSET)(sp) fsw f20,(F20_OFFSET)(sp) fsw f21,(F21_OFFSET)(sp) fsw f22,(F22_OFFSET)(sp) fsw f23,(F23_OFFSET)(sp) fsw f24,(F24_OFFSET)(sp) fsw f25,(F25_OFFSET)(sp) fsw f26,(F26_OFFSET)(sp) fsw f27,(F27_OFFSET)(sp) fsw f28,(F28_OFFSET)(sp) fsw f29,(F29_OFFSET)(sp) fsw f30,(F30_OFFSET)(sp) fsw f31,(F31_OFFSET)(sp) #endif addi sp, sp, -(BASE_CONTEXT_LEN) sw x1, (X1_OFFSET)(sp) sw x4, (X4_OFFSET)(sp) sw x5, (X5_OFFSET)(sp) sw x6, (X6_OFFSET)(sp) sw x7, (X7_OFFSET)(sp) sw x8, (X8_OFFSET)(sp) sw x9, (X9_OFFSET)(sp) sw x10, (X10_OFFSET)(sp) sw x11, (X11_OFFSET)(sp) sw x12, (X12_OFFSET)(sp) sw x13, (X13_OFFSET)(sp) sw x14, (X14_OFFSET)(sp) sw x15, (X15_OFFSET)(sp) sw x16, (X16_OFFSET)(sp) sw x17, (X17_OFFSET)(sp) sw x18, (X18_OFFSET)(sp) sw x19, (X19_OFFSET)(sp) sw x20, (X20_OFFSET)(sp) sw x21, (X21_OFFSET)(sp) sw x22, (X22_OFFSET)(sp) sw x23, (X23_OFFSET)(sp) sw x24, (X24_OFFSET)(sp) sw x25, (X25_OFFSET)(sp) sw x26, (X26_OFFSET)(sp) sw x27, (X27_OFFSET)(sp) sw x28, (X28_OFFSET)(sp) sw x29, (X29_OFFSET)(sp) sw x30, (X30_OFFSET)(sp) sw x31, (X31_OFFSET)(sp) csrr t0, mstatus sw t0, (MSTATUS_OFFSET)(sp) /* g_active_task->task_stack = context region */ la a1, g_active_task lw a1, (a1) sw sp, (a1) /* exception or interrupt is determined by the mcause register */ csrr t0, mcause blt t0, x0, interrupt /* second step: process exception. ecall 0 is used to trig task sched */ /* Save the exception return address, the lenght of instruction may be 2 or 4 byte*/ /* read the instruction which trigger the exception */ csrr t1, mepc lb t2, 0(t1) li t3, 0x3 and t2, t2, t3 bne t2, t3, 1f addi t1, t1, 0x2 1: addi t1, t1, 0x2 2: sw t1, (PC_OFFSET)(sp) /* use exception statck to process exception */ mv a2, sp la sp, exception_stack_top mv a1, t0 la t0, dispatcher_exception jalr t0 beq x0,x0, task_sched /* third step: process interrupt */ interrupt: csrr t1, mepc sw t1, (PC_OFFSET)(sp) /* use sys statck to process interrupt */ la sp, sys_stack_top andi a0, t0, 0x7FF la t0, dispatcher_interrupt jalr t0 _interrupt_return_address: /* forth step: task sched */ task_sched: #if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0) call krhino_stack_ovf_check #endif #if (RHINO_CONFIG_SYS_STATS > 0) call krhino_task_sched_stats_get #endif /* save context: R0 = g_active_task->task_stack = context region */ la a0, g_active_task la a1, g_preferred_ready_task lw a2, (a1) sw a2, (a0) task_restore: la a1, g_active_task lw a1, (a1) lw sp, (a1) lw t0, (MSTATUS_OFFSET)(sp) csrw mstatus, t0 lw t0, (PC_OFFSET)(sp) csrw mepc, t0 lw x1, (X1_OFFSET)(sp) lw x4, (X4_OFFSET)(sp) lw x5, (X5_OFFSET)(sp) lw x6, (X6_OFFSET)(sp) lw x7, (X7_OFFSET)(sp) lw x8, (X8_OFFSET)(sp) lw x9, (X9_OFFSET)(sp) lw x10, (X10_OFFSET)(sp) lw x11, (X11_OFFSET)(sp) lw x12, (X12_OFFSET)(sp) lw x13, (X13_OFFSET)(sp) lw x14, (X14_OFFSET)(sp) lw x15, (X15_OFFSET)(sp) lw x16, (X16_OFFSET)(sp) lw x17, (X17_OFFSET)(sp) lw x18, (X18_OFFSET)(sp) lw x19, (X19_OFFSET)(sp) lw x20, (X20_OFFSET)(sp) lw x21, (X21_OFFSET)(sp) lw x22, (X22_OFFSET)(sp) lw x23, (X23_OFFSET)(sp) lw x24, (X24_OFFSET)(sp) lw x25, (X25_OFFSET)(sp) lw x26, (X26_OFFSET)(sp) lw x27, (X27_OFFSET)(sp) lw x28, (X28_OFFSET)(sp) lw x29, (X29_OFFSET)(sp) lw x30, (X30_OFFSET)(sp) lw x31, (X31_OFFSET)(sp) addi sp, sp, (BASE_CONTEXT_LEN) #ifdef RISCV_SUPPORT_FPU flw f0, (F0_OFFSET)(sp) flw f1, (F1_OFFSET)(sp) flw f2, (F2_OFFSET)(sp) flw f3, (F3_OFFSET)(sp) flw f4, (F4_OFFSET)(sp) flw f5, (F5_OFFSET)(sp) flw f6, (F6_OFFSET)(sp) flw f7, (F7_OFFSET)(sp) flw f8, (F8_OFFSET)(sp) flw f9, (F9_OFFSET)(sp) flw f10,(F10_OFFSET)(sp) flw f11,(F11_OFFSET)(sp) flw f12,(F12_OFFSET)(sp) flw f13,(F13_OFFSET)(sp) flw f14,(F14_OFFSET)(sp) flw f15,(F15_OFFSET)(sp) flw f16,(F16_OFFSET)(sp) flw f17,(F17_OFFSET)(sp) flw f18,(F18_OFFSET)(sp) flw f19,(F19_OFFSET)(sp) flw f20,(F20_OFFSET)(sp) flw f21,(F21_OFFSET)(sp) flw f22,(F22_OFFSET)(sp) flw f23,(F23_OFFSET)(sp) flw f24,(F24_OFFSET)(sp) flw f25,(F25_OFFSET)(sp) flw f26,(F26_OFFSET)(sp) flw f27,(F27_OFFSET)(sp) flw f28,(F28_OFFSET)(sp) flw f29,(F29_OFFSET)(sp) flw f30,(F30_OFFSET)(sp) flw f31,(F31_OFFSET)(sp) addi sp, sp, (FLOAT_CONTEXT_LEN) #endif mret .endfunc
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32_32gpr/dispatcher_s.S
Motorola 68K Assembly
apache-2.0
7,817
#include <k_arch.h> #include <k_api.h> void dispatcher_interrupt(long irq) { krhino_intrpt_enter(); /* add board irq handler, to do... */ krhino_intrpt_exit(); }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32_32gpr/irq_dispatcher.c
C
apache-2.0
188
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ #include <k_api.h> #include <k_arch.h> void *cpu_task_stack_init(cpu_stack_t *stack_base, size_t stack_size, void *arg, task_entry_t entry) { context_t *ctx, *ctx_prev; register int *gp asm("x3"); ctx_prev = (context_t *)((unsigned long)(stack_base + stack_size) & ~0x0fUL); ctx = ctx_prev - 1; ctx->MSTATUS = (cpu_stack_t)SR_FS_INITIAL | SR_MPP_M | SR_MPIE; /* mstatus */ ctx->PC = (cpu_stack_t)entry; ctx->X31 = (cpu_stack_t)0x31313131L; /* X31 */ ctx->X30 = (cpu_stack_t)0x30303030L; /* X30 */ ctx->X29 = (cpu_stack_t)0x29292929L; /* X29 */ ctx->X28 = (cpu_stack_t)0x28282828L; /* X28 */ ctx->X27 = (cpu_stack_t)0x27272727L; /* X27 */ ctx->X26 = (cpu_stack_t)0x26262626L; /* X26 */ ctx->X25 = (cpu_stack_t)0x25252525L; /* X25 */ ctx->X24 = (cpu_stack_t)0x24242424L; /* X24 */ ctx->X23 = (cpu_stack_t)0x23232323L; /* X23 */ ctx->X22 = (cpu_stack_t)0x22222222L; /* X22 */ ctx->X21 = (cpu_stack_t)0x21212121L; /* X21 */ ctx->X20 = (cpu_stack_t)0x20202020L; /* X20 */ ctx->X19 = (cpu_stack_t)0x19191919L; /* X19 */ ctx->X18 = (cpu_stack_t)0x18181818L; /* X18 */ ctx->X17 = (cpu_stack_t)0x17171717L; /* X17 */ ctx->X16 = (cpu_stack_t)0x16161616L; /* X16 */ ctx->X15 = (uint32_t)0x15151515L; /* X15 */ ctx->X14 = (uint32_t)0x14141414L; /* X14 */ ctx->X13 = (uint32_t)0x13131313L; /* X13 */ ctx->X12 = (uint32_t)0x12121212L; /* X12 */ ctx->X11 = (uint32_t)0x11111111L; /* X11 */ ctx->X10 = (uint32_t)arg; /* X10 */ ctx->X9 = (uint32_t)0x09090909L; /* X9 */ ctx->X8 = (uint32_t)0x08080808L; /* X8 */ ctx->X7 = (uint32_t)0x07070707L; /* X7 */ ctx->X6 = (uint32_t)0x06060606L; /* X6 */ ctx->X5 = (uint32_t)0x05050505L; /* X5 */ ctx->X4 = (uint32_t)0x04040404L; /* X4 */ ctx->X3 = (uint32_t)gp; /* X3 */ ctx->X2 = (uint32_t)ctx_prev; /* X3 */ ctx->X1 = (uint32_t)krhino_task_deathbed; /* X1 */ return (void *)ctx; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32_32gpr/port_c.c
C
apache-2.0
3,321
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ /* Enable interrupts when returning from the handler */ #include "k_arch.h" #define MSTATUS_PRV1 0x1880 /****************************************************************************** * Functions: * size_t cpu_intrpt_save(void); * void cpu_intrpt_restore(size_t psr); ******************************************************************************/ .global cpu_intrpt_save .type cpu_intrpt_save, %function cpu_intrpt_save: csrr a0, mstatus csrc mstatus, 8 ret .global cpu_intrpt_restore .type cpu_intrpt_restore, %function cpu_intrpt_restore: csrw mstatus, a0 ret /****************************************************************************** * Functions: * void cpu_intrpt_switch(void); * void cpu_task_switch(void); ******************************************************************************/ .global cpu_task_switch .type cpu_task_switch, %function cpu_task_switch: mv a0, x0 ecall ret .global cpu_intrpt_switch .type cpu_intrpt_switch, %function cpu_intrpt_switch: ret /****************************************************************************** * Functions: * void cpu_first_task_start(void); ******************************************************************************/ .global cpu_first_task_start .align 8 .func cpu_first_task_start: li t0, (IE_MTIE | IE_MEIE) csrw mie, t0 la t0, task_restore jr t0 .endfunc
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32_32gpr/port_s.S
Unix Assembly
apache-2.0
2,061
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ #include <k_api.h> #include <k_config.h> #if (RHINO_CONFIG_STACK_OVF_CHECK_HW != 0) void cpu_intrpt_stack_protect(void) { } void task_stack_crash_warning(void) { printf("****The task stack base has been broken !!!****\n"); } void cpu_task_stack_protect(cpu_stack_t *base, size_t size) { uint32_t base_addr = (uint32_t)base; int num_return = wp_register(base_addr, AWATCH, task_stack_crash_warning); if (num_return == 1) { wp_enable(1); } else if (num_return == 2 || num_return == -1) { wp_unregister(1); int number_tmp = wp_register(base_addr, AWATCH, task_stack_crash_warning); if (number_tmp == 1){ wp_enable(1); } } } #endif
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32fd_32gpr/cpu_impl.c
C
apache-2.0
1,342
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ #include <k_api.h> #undef PSR_SP #define PSR_SP (1UL << 29) static ktask_t *tee_caller_task = NULL; static inline uint32_t getcurrentpsr(void) { uint32_t flags = 0; __asm__ __volatile__( "ebreak\n" /* TODO */ ); return flags; } static inline void clear_psr_sp(void) { __asm__ __volatile__ ( "ebreak\n" /* TODO */ ); } static inline void set_psr_sp(void) { __asm__ __volatile__ ( "ebreak\n" /* TODO */ ); } void csky_get_tee_caller_task(void) { uint32_t temp_psr; temp_psr = getcurrentpsr(); if (temp_psr & PSR_SP) { tee_caller_task = (tee_caller_task == NULL) ? g_active_task[cpu_cur_get()] : tee_caller_task; } } void csky_deal_tee_caller_task(void) { uint32_t temp_psr; temp_psr = getcurrentpsr(); if (temp_psr & PSR_SP) { if (tee_caller_task != NULL) { if (tee_caller_task == g_active_task[cpu_cur_get()]) { tee_caller_task = NULL; } else { clear_psr_sp(); } } } else { if (tee_caller_task != NULL) { if (tee_caller_task == g_active_task[cpu_cur_get()]) { tee_caller_task = NULL; set_psr_sp(); } } } }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32fd_32gpr/csky_sched.c
C
apache-2.0
1,892
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ #include <k_api.h> void *cpu_task_stack_init(cpu_stack_t *stack_base, size_t stack_size, void *arg, task_entry_t entry) { cpu_stack_t *stk; register int *gp asm("x3"); uint32_t temp = (uint32_t)(stack_base + stack_size); temp &= 0xFFFFFFF8UL; stk = (cpu_stack_t *)temp; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)0x12345678L; *(--stk) = (uint32_t)0x87654321L; *(--stk) = (uint32_t)entry; /* PC */ *(--stk) = (uint32_t)0x31313131L; /* X31 */ *(--stk) = (uint32_t)0x30303030L; /* X30 */ *(--stk) = (uint32_t)0x29292929L; /* X29 */ *(--stk) = (uint32_t)0x28282828L; /* X28 */ *(--stk) = (uint32_t)0x27272727L; /* X27 */ *(--stk) = (uint32_t)0x26262626L; /* X26 */ *(--stk) = (uint32_t)0x25252525L; /* X25 */ *(--stk) = (uint32_t)0x24242424L; /* X24 */ *(--stk) = (uint32_t)0x23232323L; /* X23 */ *(--stk) = (uint32_t)0x22222222L; /* X22 */ *(--stk) = (uint32_t)0x21212121L; /* X21 */ *(--stk) = (uint32_t)0x20202020L; /* X20 */ *(--stk) = (uint32_t)0x19191919L; /* X19 */ *(--stk) = (uint32_t)0x18181818L; /* X18 */ *(--stk) = (uint32_t)0x17171717L; /* X17 */ *(--stk) = (uint32_t)0x16161616L; /* X16 */ *(--stk) = (uint32_t)0x15151515L; /* X15 */ *(--stk) = (uint32_t)0x14141414L; /* X14 */ *(--stk) = (uint32_t)0x13131313L; /* X13 */ *(--stk) = (uint32_t)0x12121212L; /* X12 */ *(--stk) = (uint32_t)0x11111111L; /* X11 */ *(--stk) = (uint32_t)arg; /* X10 */ *(--stk) = (uint32_t)0x09090909L; /* X9 */ *(--stk) = (uint32_t)0x08080808L; /* X8 */ *(--stk) = (uint32_t)0x07070707L; /* X7 */ *(--stk) = (uint32_t)0x06060606L; /* X6 */ *(--stk) = (uint32_t)0x05050505L; /* X5 */ *(--stk) = (uint32_t)0x04040404L; /* X4 */ *(--stk) = (uint32_t)gp; /* X3 */ *(--stk) = (uint32_t)krhino_task_deathbed; /* X1 */ return stk; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32fd_32gpr/port_c.c
C
apache-2.0
6,013
/* * Copyright (C) 2016 YunOS Project. All rights reserved. * * 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. */ /* Enable interrupts when returning from the handler */ #define MSTATUS_PRV1 0x1880 /****************************************************************************** * Functions: * size_t cpu_intrpt_save(void); * void cpu_intrpt_restore(size_t psr); ******************************************************************************/ .global cpu_intrpt_save .type cpu_intrpt_save, %function cpu_intrpt_save: csrr a0, mstatus csrc mstatus, 8 ret .global cpu_intrpt_restore .type cpu_intrpt_restore, %function cpu_intrpt_restore: csrw mstatus, a0 ret /****************************************************************************** * Functions: * void cpu_intrpt_switch(void); * void cpu_task_switch(void); ******************************************************************************/ .global cpu_task_switch .type cpu_task_switch, %function cpu_task_switch: li t0, 0xE080100C lb t1, (t0) li t2, 0x01 or t1, t1, t2 sb t1, (t0) ret .global cpu_intrpt_switch .type cpu_intrpt_switch, %function cpu_intrpt_switch: li t0, 0xE080100C lb t1, (t0) li t2, 0x01 or t1, t1, t2 sb t1, (t0) ret /****************************************************************************** * Functions: * void cpu_first_task_start(void); ******************************************************************************/ .global cpu_first_task_start .type cpu_first_task_start, %function cpu_first_task_start: j __task_switch_nosave /****************************************************************************** * Functions: * void tspend_handler(void); ******************************************************************************/ .global tspend_handler .type tspend_handler, %function tspend_handler: addi sp, sp, -(128+128) fsd f31, (0 + 0 )(sp) fsd f30, (4 + 4 )(sp) fsd f29, (8 + 8 )(sp) fsd f28, (12 + 12)(sp) fsd f27, (16 + 16)(sp) fsd f26, (20 + 20)(sp) fsd f25, (24 + 24)(sp) fsd f24, (28 + 28)(sp) fsd f23, (32 + 32)(sp) fsd f22, (36 + 36)(sp) fsd f21, (40 + 40)(sp) fsd f20, (44 + 44)(sp) fsd f19, (48 + 48)(sp) fsd f18, (52 + 52)(sp) fsd f17, (56 + 56)(sp) fsd f16, (60 + 60)(sp) fsd f15, (64 + 64)(sp) fsd f14, (68 + 68)(sp) fsd f13, (72 + 72)(sp) fsd f12, (76 + 76)(sp) fsd f11, (80 + 80)(sp) fsd f10, (84 + 84)(sp) fsd f9, (88 + 88)(sp) fsd f8, (92 + 92)(sp) fsd f7, (96 + 96)(sp) fsd f6, (100+100)(sp) fsd f5, (104+104)(sp) fsd f4, (108+108)(sp) fsd f3, (112+112)(sp) fsd f2, (116+116)(sp) fsd f1, (120+120)(sp) fsd f0, (124+124)(sp) addi sp, sp, -124 sw x1, 0(sp) sw x3, 4(sp) sw x4, 8(sp) sw x5, 12(sp) sw x6, 16(sp) sw x7, 20(sp) sw x8, 24(sp) sw x9, 28(sp) sw x10, 32(sp) sw x11, 36(sp) sw x12, 40(sp) sw x13, 44(sp) sw x14, 48(sp) sw x15, 52(sp) sw x16, 56(sp) sw x17, 60(sp) sw x18, 64(sp) sw x19, 68(sp) sw x20, 72(sp) sw x21, 76(sp) sw x22, 80(sp) sw x23, 84(sp) sw x24, 88(sp) sw x25, 92(sp) sw x26, 96(sp) sw x27, 100(sp) sw x28, 104(sp) sw x29, 108(sp) sw x30, 112(sp) sw x31, 116(sp) csrr t0, mepc sw t0, 120(sp) la a1, g_active_task lw a1, (a1) sw sp, (a1) li t0, 0xE000E100 lw t1, (t0) li t2, 0xFEFFFFFF and t1, t1, t2 sw t1, (t0) __task_switch_nosave: la a0, g_preferred_ready_task la a1, g_active_task lw a2, (a0) sw a2, (a1) lw sp, (a2) /* Run in machine mode */ li t0, MSTATUS_PRV1 csrs mstatus, t0 lw t0, 120(sp) csrw mepc, t0 lw x1, 0(sp) lw x3, 4(sp) lw x4, 8(sp) lw x5, 12(sp) lw x6, 16(sp) lw x7, 20(sp) lw x8, 24(sp) lw x9, 28(sp) lw x10, 32(sp) lw x11, 36(sp) lw x12, 40(sp) lw x13, 44(sp) lw x14, 48(sp) lw x15, 52(sp) lw x16, 56(sp) lw x17, 60(sp) lw x18, 64(sp) lw x19, 68(sp) lw x20, 72(sp) lw x21, 76(sp) lw x22, 80(sp) lw x23, 84(sp) lw x24, 88(sp) lw x25, 92(sp) lw x26, 96(sp) lw x27, 100(sp) lw x28, 104(sp) lw x29, 108(sp) lw x30, 112(sp) lw x31, 116(sp) addi sp, sp, 124 fld f31, (0 + 0 )(sp) fld f30, (4 + 4 )(sp) fld f29, (8 + 8 )(sp) fld f28, (12 + 12)(sp) fld f27, (16 + 16)(sp) fld f26, (20 + 20)(sp) fld f25, (24 + 24)(sp) fld f24, (28 + 28)(sp) fld f23, (32 + 32)(sp) fld f22, (36 + 36)(sp) fld f21, (40 + 40)(sp) fld f20, (44 + 44)(sp) fld f19, (48 + 48)(sp) fld f18, (52 + 52)(sp) fld f17, (56 + 56)(sp) fld f16, (60 + 60)(sp) fld f15, (64 + 64)(sp) fld f14, (68 + 68)(sp) fld f13, (72 + 72)(sp) fld f12, (76 + 76)(sp) fld f11, (80 + 80)(sp) fld f10, (84 + 84)(sp) fld f9, (88 + 88)(sp) fld f8, (92 + 92)(sp) fld f7, (96 + 96)(sp) fld f6, (100+100)(sp) fld f5, (104+104)(sp) fld f4, (108+108)(sp) fld f3, (112+112)(sp) fld f2, (116+116)(sp) fld f1, (120+120)(sp) fld f0, (124+124)(sp) addi sp, sp, (128+128) mret
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv32fd_32gpr/port_s.S
Motorola 68K Assembly
apache-2.0
6,542
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <stddef.h> #include <stdint.h> #include <string.h> #include <limits.h> #include <stdio.h> #include "k_api.h" #include "aos/debug.h" /* part of ktask_t */ typedef struct { void *task_stack; } ktask_t_shadow; //#define OS_BACKTRACE_DEBUG extern char *__etext; extern char *__stext; #define BT_CHK_PC_AVAIL(pc) ((uintptr_t)(pc) < (uintptr_t)(&__etext) \ && (uintptr_t)(pc) > (uintptr_t)(&__stext)) #define BT_PC2ADDR(pc) ((char *)(((uintptr_t)(pc)))) #define BT_FUNC_LIMIT 0x2000 #define BT_LVL_LIMIT 64 extern void krhino_task_deathbed(void); extern ktask_t_shadow *debug_task_find(char *name); extern int debug_task_is_running(ktask_t_shadow *task); extern void *debug_task_stack_bottom(ktask_t_shadow *task); extern char *k_int2str(int num, char *str); extern void _interrupt_return_address(void); void backtrace_handle(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)); /* get framesize from c ins */ static int riscv_backtrace_framesize_get(unsigned short inst) { unsigned int imm = 0; /* addi sp, sp, -im */ if ((inst & 0xFF83) == 0x1101) { imm = (inst >> 2) & 0x1F; imm = (~imm & 0x1F) + 1; return imm >> 3; } /* c.addi16sp sp, nzuimm6<<4 */ if ((inst & 0xFF83) == 0x7101) { imm = (inst >> 3) & 0x3; imm = (imm << 1) | ((inst >> 5) & 0x1); imm = (imm << 1) | ((inst >> 2) & 0x1); imm = (imm << 1) | ((inst >> 6) & 0x1); imm = ((~imm & 0x1f) + 1) << 4; return imm >> 3; } return -1; } /* get ra position in the stach */ static int riscv_backtrace_ra_offset_get(unsigned short inst) { unsigned int imm = 0; /* c.fsdsp rs2, uimm6<<3(sp) */ if ((inst & 0xE07F) == 0xE006) { imm = (inst >> 7) & 0x7; imm = (imm << 3) | ((inst >> 10) & 0x7); /* The unit is size_t, So we don't have to move 3 bits to the left */ return imm; } return -1; } /* get the offset between the jump instruction and the return address */ static int backtraceFindLROffset(char *LR, int (*print_func)(const char *fmt, ...)) { int offset = 0; char *LR_indeed; unsigned int ins32; char s_panic_call[] = "backtrace : 0x \r\n"; LR_indeed = BT_PC2ADDR(LR); /* callstack bottom */ if (LR_indeed == BT_PC2ADDR(&_interrupt_return_address)) { /* EXC_RETURN, so here is callstack bottom of interrupt handler */ if (print_func != NULL) { print_func("backtrace : ^interrupt^\r\n"); } return 0; } if (LR_indeed == BT_PC2ADDR(&krhino_task_deathbed)) { /* task delete, so here is callstack bottom of task */ if (print_func != NULL) { print_func("backtrace : ^task entry^\r\n"); } return 0; } /* Usually jump using the JAL instruction */ ins32 = *(unsigned int *)(LR_indeed - 4); if ((ins32 & 0x3) == 0x3) { offset = 4; } else { offset = 2; } if (print_func != NULL) { k_int2str((int)LR_indeed - offset, &s_panic_call[14]); print_func(s_panic_call); } return offset; } /* find current function caller, update PC and SP returns: 0 success 1 success and find buttom -1 fail */ static int riscv_backtraceFromStack(long **pSP, char **pPC, int (*print_func)(const char *fmt, ...)) { char *CodeAddr = NULL; long *SP = *pSP; char *PC = *pPC; char *LR; int i; int framesize; int offset = 0; unsigned short ins16; #ifdef OS_BACKTRACE_DEBUG printk("[riscv_backtraceFromStack in ] SP = %p, PC = %p\n\r", *pSP, *pPC); #endif if (SP == debug_task_stack_bottom(NULL)) { if (print_func != NULL) { print_func("backtrace : ^task entry^\r\n"); } return 1; } /* 1. scan code, find lr pushed */ for (i = 0; i < BT_FUNC_LIMIT; i += 4) { CodeAddr = (char *)(((long)PC & (~0x3)) - i); ins16 = *(unsigned short *)(CodeAddr + 2); framesize = riscv_backtrace_framesize_get(ins16); if (framesize >= 0) { break; } ins16 = *(unsigned short *)(CodeAddr); framesize = riscv_backtrace_framesize_get(ins16); if (framesize >= 0) { break; } } if (i == BT_FUNC_LIMIT) { /* error branch */ if (print_func != NULL) { print_func("Backtrace fail!\r\n"); } return -1; } /* 2. scan code, find ins: sd ra,24(sp) */ for (i = 0; CodeAddr + i < PC; i += 4) { ins16 = *(unsigned short *)(CodeAddr + i + 2); offset = riscv_backtrace_ra_offset_get(ins16); if (offset >= 0) { break; } ins16 = *(unsigned short *)(CodeAddr + i); offset = riscv_backtrace_ra_offset_get(ins16); if (offset >= 0) { break; } } #ifdef OS_BACKTRACE_DEBUG printk("[arm_backtraceFromStack out] frsz = %d offset = %d SP=%p\n\r", framesize, offset, SP); #endif /* 3. output */ LR = (char *)(*(SP + offset)); if (BT_CHK_PC_AVAIL(LR) == 0) { if (print_func != NULL) { print_func("backtrace : invalid lr\r\n"); } return -1; } *pSP = SP + framesize; offset = backtraceFindLROffset(LR, print_func); *pPC = LR - offset; return offset == 0 ? 1 : 0; } static int backtraceFromStack(long **pSP, char **pPC, int (*print_func)(const char *fmt, ...)) { if (BT_CHK_PC_AVAIL(*pPC) == 0) { return -1; } return riscv_backtraceFromStack(pSP, pPC, print_func); } /* printf call stack return levels of call stack */ int backtrace_now(int (*print_func)(const char *fmt, ...)) { char *PC; long *SP; int lvl; int ret; if (print_func == NULL) { print_func = printf; } SP = RHINO_GET_SP(); PC = RHINO_GET_PC(); print_func("========== Call stack ==========\r\n"); for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&SP, &PC, print_func); if (ret != 0) { break; } } print_func("========== End ==========\r\n"); return lvl; } /* printf call stack for task return levels of call stack */ void backtrace_task(void *task, int (*print_func)(const char *fmt, ...)) { } /* backtrace start with PC and SP, find LR from stack memory return levels of call stack */ int backtrace_caller(char *PC, int *SP, int (*print_func)(const char *fmt, ...)) { return 0; } /* backtrace start with PC SP and LR return levels of call stack */ int backtrace_callee(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)) { return 0; } /** Get call stack, return levels of call stack trace[] output buffer size buffer size offset which lvl start */ int backtrace_now_get(void *trace[], int size, int offset) { char *PC; long *SP; int lvl; int ret; SP = RHINO_GET_SP(); PC = RHINO_GET_PC(); memset(trace, 0, size * sizeof(void *)); for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&SP, &PC, NULL); if (ret != 0) { break; } if (lvl >= offset && lvl - offset < size) { trace[lvl - offset] = PC; } if (lvl - offset >= size) { break; } } return lvl - offset < 0 ? 0 : lvl - offset; } void backtrace_handle(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)) { int lvl; int ret; long *pSP = (long *)SP; if (print_func == NULL) { print_func = printf; } for (lvl = 0; lvl < BT_LVL_LIMIT; lvl++) { ret = backtraceFromStack(&pSP, &PC, print_func); if (ret != 0) { break; } } return; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/backtrace.c
C
apache-2.0
8,095
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef BACKTRACE_H #define BACKTRACE_H /* printf call stack return levels of call stack */ int backtrace_now(int (*print_func)(const char *fmt, ...)); /* printf call stack for task return levels of call stack */ int backtrace_task(char *taskname, int (*print_func)(const char *fmt, ...)); /* backtrace start with PC and SP, find LR from stack memory return levels of call stack */ int backtrace_caller(char *PC, int *SP, int (*print_func)(const char *fmt, ...)); /* backtrace start with PC SP and LR return levels of call stack */ int backtrace_callee(char *PC, int *SP, char *LR, int (*print_func)(const char *fmt, ...)); #endif /* BACKTRACE_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/backtrace.h
C
apache-2.0
773
#include <k_arch.h> /****************************************************************************** @ Declares the function and variable that this file will call @******************************************************************************/ .extern exception_stack_top .extern dispatcher_exception .extern dispatcher_interrupt /****************************************************************************** @ Exception Vector. mtvec.mode must be set to 0, exceptions and interrupts use @ the same vector entry @******************************************************************************/ .section .vectors .align 6 .globl __Vectors .type __Vectors, @object __Vectors: j ht_dispatcher /****************************************************************************** @ Jump to this function when an exception or interrupt occurs. This function is @ used to schedule the execution flow of exceptions, interrupts, and tasks. @ System call 0 is used to trigger task scheduling. @******************************************************************************/ .text .align 8 .func ht_dispatcher: /* first step: save context */ addi sp, sp, -(FLOAT_CONTEXT_LEN) fsd f0, (F0_OFFSET)(sp) fsd f1, (F1_OFFSET)(sp) fsd f2, (F2_OFFSET)(sp) fsd f3, (F3_OFFSET)(sp) fsd f4, (F4_OFFSET)(sp) fsd f5, (F5_OFFSET)(sp) fsd f6, (F6_OFFSET)(sp) fsd f7, (F7_OFFSET)(sp) fsd f8, (F8_OFFSET)(sp) fsd f9, (F9_OFFSET)(sp) fsd f10,(F10_OFFSET)(sp) fsd f11,(F11_OFFSET)(sp) fsd f12,(F12_OFFSET)(sp) fsd f13,(F13_OFFSET)(sp) fsd f14,(F14_OFFSET)(sp) fsd f15,(F15_OFFSET)(sp) fsd f16,(F16_OFFSET)(sp) fsd f17,(F17_OFFSET)(sp) fsd f18,(F18_OFFSET)(sp) fsd f19,(F19_OFFSET)(sp) fsd f20,(F20_OFFSET)(sp) fsd f21,(F21_OFFSET)(sp) fsd f22,(F22_OFFSET)(sp) fsd f23,(F23_OFFSET)(sp) fsd f24,(F24_OFFSET)(sp) fsd f25,(F25_OFFSET)(sp) fsd f26,(F26_OFFSET)(sp) fsd f27,(F27_OFFSET)(sp) fsd f28,(F28_OFFSET)(sp) fsd f29,(F29_OFFSET)(sp) fsd f30,(F30_OFFSET)(sp) fsd f31,(F31_OFFSET)(sp) addi sp, sp, -(BASE_CONTEXT_LEN) sd x1, (X1_OFFSET)(sp) sd x4, (X4_OFFSET)(sp) sd x5, (X5_OFFSET)(sp) sd x6, (X6_OFFSET)(sp) sd x7, (X7_OFFSET)(sp) sd x8, (X8_OFFSET)(sp) sd x9, (X9_OFFSET)(sp) sd x10, (X10_OFFSET)(sp) sd x11, (X11_OFFSET)(sp) sd x12, (X12_OFFSET)(sp) sd x13, (X13_OFFSET)(sp) sd x14, (X14_OFFSET)(sp) sd x15, (X15_OFFSET)(sp) sd x16, (X16_OFFSET)(sp) sd x17, (X17_OFFSET)(sp) sd x18, (X18_OFFSET)(sp) sd x19, (X19_OFFSET)(sp) sd x20, (X20_OFFSET)(sp) sd x21, (X21_OFFSET)(sp) sd x22, (X22_OFFSET)(sp) sd x23, (X23_OFFSET)(sp) sd x24, (X24_OFFSET)(sp) sd x25, (X25_OFFSET)(sp) sd x26, (X26_OFFSET)(sp) sd x27, (X27_OFFSET)(sp) sd x28, (X28_OFFSET)(sp) sd x29, (X29_OFFSET)(sp) sd x30, (X30_OFFSET)(sp) sd x31, (X31_OFFSET)(sp) csrr t0, mepc sd t0, (PC_OFFSET)(sp) csrr t0, mstatus sd t0, (MSTATUS_OFFSET)(sp) /* exception or interrupt is determined by the mcause register */ csrr t0, mcause blt t0, x0, interrupt /* second step: process exception. */ mv a2, sp mv a1, t0 la t0, dispatcher_exception jalr t0 beq x0,x0, context_restore /* third step: process interrupt */ interrupt: /* use sys statck to process interrupt */ andi a0, t0, 0x7FF la t0, dispatcher_interrupt jalr t0 /* forth step: restore context */ context_restore: ld t0, (MSTATUS_OFFSET)(sp) csrw mstatus, t0 ld t0, (PC_OFFSET)(sp) csrw mepc, t0 ld x1, (X1_OFFSET)(sp) ld x4, (X4_OFFSET)(sp) ld x5, (X5_OFFSET)(sp) ld x6, (X6_OFFSET)(sp) ld x7, (X7_OFFSET)(sp) ld x8, (X8_OFFSET)(sp) ld x9, (X9_OFFSET)(sp) ld x10, (X10_OFFSET)(sp) ld x11, (X11_OFFSET)(sp) ld x12, (X12_OFFSET)(sp) ld x13, (X13_OFFSET)(sp) ld x14, (X14_OFFSET)(sp) ld x15, (X15_OFFSET)(sp) ld x16, (X16_OFFSET)(sp) ld x17, (X17_OFFSET)(sp) ld x18, (X18_OFFSET)(sp) ld x19, (X19_OFFSET)(sp) ld x20, (X20_OFFSET)(sp) ld x21, (X21_OFFSET)(sp) ld x22, (X22_OFFSET)(sp) ld x23, (X23_OFFSET)(sp) ld x24, (X24_OFFSET)(sp) ld x25, (X25_OFFSET)(sp) ld x26, (X26_OFFSET)(sp) ld x27, (X27_OFFSET)(sp) ld x28, (X28_OFFSET)(sp) ld x29, (X29_OFFSET)(sp) ld x30, (X30_OFFSET)(sp) ld x31, (X31_OFFSET)(sp) addi sp, sp, (BASE_CONTEXT_LEN) fld f0, (F0_OFFSET)(sp) fld f1, (F1_OFFSET)(sp) fld f2, (F2_OFFSET)(sp) fld f3, (F3_OFFSET)(sp) fld f4, (F4_OFFSET)(sp) fld f5, (F5_OFFSET)(sp) fld f6, (F6_OFFSET)(sp) fld f7, (F7_OFFSET)(sp) fld f8, (F8_OFFSET)(sp) fld f9, (F9_OFFSET)(sp) fld f10,(F10_OFFSET)(sp) fld f11,(F11_OFFSET)(sp) fld f12,(F12_OFFSET)(sp) fld f13,(F13_OFFSET)(sp) fld f14,(F14_OFFSET)(sp) fld f15,(F15_OFFSET)(sp) fld f16,(F16_OFFSET)(sp) fld f17,(F17_OFFSET)(sp) fld f18,(F18_OFFSET)(sp) fld f19,(F19_OFFSET)(sp) fld f20,(F20_OFFSET)(sp) fld f21,(F21_OFFSET)(sp) fld f22,(F22_OFFSET)(sp) fld f23,(F23_OFFSET)(sp) fld f24,(F24_OFFSET)(sp) fld f25,(F25_OFFSET)(sp) fld f26,(F26_OFFSET)(sp) fld f27,(F27_OFFSET)(sp) fld f28,(F28_OFFSET)(sp) fld f29,(F29_OFFSET)(sp) fld f30,(F30_OFFSET)(sp) fld f31,(F31_OFFSET)(sp) addi sp, sp, (FLOAT_CONTEXT_LEN) mret .endfunc
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/dispatcher_boot.S
Motorola 68K Assembly
apache-2.0
6,155
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <k_api.h> #include <k_arch.h> void exceptionHandler(void *context); void dispatcher_exception(long arg, long exc_type, context_t *contex) { switch (exc_type) { case CAUSE_MACHINE_ECALL: /* This is a task scheduling request */ if (arg == 0) { return; } break; default: exceptionHandler(contex); break; } return; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/dispatcher_c.c
C
apache-2.0
470
#include <k_config.h> #include <k_arch.h> /****************************************************************************** @ Declares the function that this file will call @******************************************************************************/ .extern g_active_task .extern g_preferred_ready_task .extern krhino_stack_ovf_check .extern krhino_task_sched_stats_get .extern exception_stack_top .extern dispatcher_exception .extern dispatcher_interrupt .global task_restore .global _interrupt_return_address /****************************************************************************** @ Exception Vector. mtvec.mode must be set to 0, exceptions and interrupts use @ the same vector entry @******************************************************************************/ .section .vectors .align 6 .globl __Vectors .type __Vectors, @object __Vectors: j ht_dispatcher /****************************************************************************** @ Jump to this function when an exception or interrupt occurs. This function is @ used to schedule the execution flow of exceptions, interrupts, and tasks. @ System call 0 is used to trigger task scheduling. @******************************************************************************/ .text .align 8 .func ht_dispatcher: /* first step: save context */ addi sp, sp, -(FLOAT_CONTEXT_LEN) fsd f0, (F0_OFFSET)(sp) fsd f1, (F1_OFFSET)(sp) fsd f2, (F2_OFFSET)(sp) fsd f3, (F3_OFFSET)(sp) fsd f4, (F4_OFFSET)(sp) fsd f5, (F5_OFFSET)(sp) fsd f6, (F6_OFFSET)(sp) fsd f7, (F7_OFFSET)(sp) fsd f8, (F8_OFFSET)(sp) fsd f9, (F9_OFFSET)(sp) fsd f10,(F10_OFFSET)(sp) fsd f11,(F11_OFFSET)(sp) fsd f12,(F12_OFFSET)(sp) fsd f13,(F13_OFFSET)(sp) fsd f14,(F14_OFFSET)(sp) fsd f15,(F15_OFFSET)(sp) fsd f16,(F16_OFFSET)(sp) fsd f17,(F17_OFFSET)(sp) fsd f18,(F18_OFFSET)(sp) fsd f19,(F19_OFFSET)(sp) fsd f20,(F20_OFFSET)(sp) fsd f21,(F21_OFFSET)(sp) fsd f22,(F22_OFFSET)(sp) fsd f23,(F23_OFFSET)(sp) fsd f24,(F24_OFFSET)(sp) fsd f25,(F25_OFFSET)(sp) fsd f26,(F26_OFFSET)(sp) fsd f27,(F27_OFFSET)(sp) fsd f28,(F28_OFFSET)(sp) fsd f29,(F29_OFFSET)(sp) fsd f30,(F30_OFFSET)(sp) fsd f31,(F31_OFFSET)(sp) addi sp, sp, -(BASE_CONTEXT_LEN) sd x1, (X1_OFFSET)(sp) sd x4, (X4_OFFSET)(sp) sd x5, (X5_OFFSET)(sp) sd x6, (X6_OFFSET)(sp) sd x7, (X7_OFFSET)(sp) sd x8, (X8_OFFSET)(sp) sd x9, (X9_OFFSET)(sp) sd x10, (X10_OFFSET)(sp) sd x11, (X11_OFFSET)(sp) sd x12, (X12_OFFSET)(sp) sd x13, (X13_OFFSET)(sp) sd x14, (X14_OFFSET)(sp) sd x15, (X15_OFFSET)(sp) sd x16, (X16_OFFSET)(sp) sd x17, (X17_OFFSET)(sp) sd x18, (X18_OFFSET)(sp) sd x19, (X19_OFFSET)(sp) sd x20, (X20_OFFSET)(sp) sd x21, (X21_OFFSET)(sp) sd x22, (X22_OFFSET)(sp) sd x23, (X23_OFFSET)(sp) sd x24, (X24_OFFSET)(sp) sd x25, (X25_OFFSET)(sp) sd x26, (X26_OFFSET)(sp) sd x27, (X27_OFFSET)(sp) sd x28, (X28_OFFSET)(sp) sd x29, (X29_OFFSET)(sp) sd x30, (X30_OFFSET)(sp) sd x31, (X31_OFFSET)(sp) csrr t0, mstatus sd t0, (MSTATUS_OFFSET)(sp) /* g_active_task->task_stack = context region */ la a1, g_active_task ld a1, (a1) sd sp, (a1) /* exception or interrupt is determined by the mcause register */ csrr t0, mcause blt t0, x0, interrupt /* second step: process exception. ecall 0 is used to trig task sched */ /* Save the exception return address, the lenght of instruction may be 2 or 4 byte*/ /* read the instruction which trigger the exception */ csrr t1, mepc lb t2, 0(t1) li t3, 0x3 and t2, t2, t3 bne t2, t3, 1f addi t1, t1, 0x2 1: addi t1, t1, 0x2 2: sd t1, (PC_OFFSET)(sp) /* use exception statck to process exception */ mv a2, sp la sp, exception_stack_top mv a1, t0 la t0, dispatcher_exception jalr t0 beq x0,x0, task_sched /* third step: process interrupt */ interrupt: csrr t1, mepc sd t1, (PC_OFFSET)(sp) /* use sys statck to process interrupt */ la sp, sys_stack_top andi a0, t0, 0x7FF la t0, dispatcher_interrupt jalr t0 _interrupt_return_address: /* forth step: task sched */ task_sched: #if (RHINO_CONFIG_TASK_STACK_OVF_CHECK > 0) call krhino_stack_ovf_check #endif #if (RHINO_CONFIG_SYS_STATS > 0) call krhino_task_sched_stats_get #endif /* save context: R0 = g_active_task->task_stack = context region */ la a0, g_active_task la a1, g_preferred_ready_task ld a2, (a1) sd a2, (a0) task_restore: la a1, g_active_task ld a1, (a1) ld sp, (a1) ld t0, (MSTATUS_OFFSET)(sp) csrw mstatus, t0 ld t0, (PC_OFFSET)(sp) csrw mepc, t0 ld x1, (X1_OFFSET)(sp) ld x4, (X4_OFFSET)(sp) ld x5, (X5_OFFSET)(sp) ld x6, (X6_OFFSET)(sp) ld x7, (X7_OFFSET)(sp) ld x8, (X8_OFFSET)(sp) ld x9, (X9_OFFSET)(sp) ld x10, (X10_OFFSET)(sp) ld x11, (X11_OFFSET)(sp) ld x12, (X12_OFFSET)(sp) ld x13, (X13_OFFSET)(sp) ld x14, (X14_OFFSET)(sp) ld x15, (X15_OFFSET)(sp) ld x16, (X16_OFFSET)(sp) ld x17, (X17_OFFSET)(sp) ld x18, (X18_OFFSET)(sp) ld x19, (X19_OFFSET)(sp) ld x20, (X20_OFFSET)(sp) ld x21, (X21_OFFSET)(sp) ld x22, (X22_OFFSET)(sp) ld x23, (X23_OFFSET)(sp) ld x24, (X24_OFFSET)(sp) ld x25, (X25_OFFSET)(sp) ld x26, (X26_OFFSET)(sp) ld x27, (X27_OFFSET)(sp) ld x28, (X28_OFFSET)(sp) ld x29, (X29_OFFSET)(sp) ld x30, (X30_OFFSET)(sp) ld x31, (X31_OFFSET)(sp) addi sp, sp, (BASE_CONTEXT_LEN) fld f0, (F0_OFFSET)(sp) fld f1, (F1_OFFSET)(sp) fld f2, (F2_OFFSET)(sp) fld f3, (F3_OFFSET)(sp) fld f4, (F4_OFFSET)(sp) fld f5, (F5_OFFSET)(sp) fld f6, (F6_OFFSET)(sp) fld f7, (F7_OFFSET)(sp) fld f8, (F8_OFFSET)(sp) fld f9, (F9_OFFSET)(sp) fld f10,(F10_OFFSET)(sp) fld f11,(F11_OFFSET)(sp) fld f12,(F12_OFFSET)(sp) fld f13,(F13_OFFSET)(sp) fld f14,(F14_OFFSET)(sp) fld f15,(F15_OFFSET)(sp) fld f16,(F16_OFFSET)(sp) fld f17,(F17_OFFSET)(sp) fld f18,(F18_OFFSET)(sp) fld f19,(F19_OFFSET)(sp) fld f20,(F20_OFFSET)(sp) fld f21,(F21_OFFSET)(sp) fld f22,(F22_OFFSET)(sp) fld f23,(F23_OFFSET)(sp) fld f24,(F24_OFFSET)(sp) fld f25,(F25_OFFSET)(sp) fld f26,(F26_OFFSET)(sp) fld f27,(F27_OFFSET)(sp) fld f28,(F28_OFFSET)(sp) fld f29,(F29_OFFSET)(sp) fld f30,(F30_OFFSET)(sp) fld f31,(F31_OFFSET)(sp) addi sp, sp, (FLOAT_CONTEXT_LEN) mret .endfunc
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/dispatcher_s.S
Motorola 68K Assembly
apache-2.0
7,419
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_COMPILER_H #define K_COMPILER_H #if defined(__CC_ARM) #define RHINO_INLINE static __inline /* get the return address of the current function unsigned int __return_address(void) */ #define RHINO_GET_RA() (void *)__return_address() /* get the the value of the stack pointer unsigned int __current_sp(void) */ #define RHINO_GET_SP() (void *)__current_sp() /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __builtin_clz(x) /* Returns the number of trailing 0-bits in x, starting at the least signifi cant bit position. */ #define RHINO_BIT_CTZ(x) __builtin_ctz(x) #ifndef RHINO_WEAK #define RHINO_WEAK __weak #endif #ifndef RHINO_ASM #define RHINO_ASM __asm #endif /* Instruction Synchronization Barrier */ #define OS_ISB() __isb(15) /* Full system Any-Any */ /* Data Memory Barrier */ #define OS_DMB() __dmb(15) /* Full system Any-Any */ /* Data Synchronization Barrier */ #define OS_DSB() __dsb(15) /* Full system Any-Any */ #elif defined(__ICCARM__) #include "intrinsics.h" #define RHINO_INLINE static inline /* get the return address of the current function unsigned int __get_LR(void) */ #define RHINO_GET_RA() (void *)__get_LR() /* get the the value of the stack pointer unsigned int __get_SP(void) */ #define RHINO_GET_SP() (void *)__get_SP() /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __CLZ(x) //#define RHINO_BIT_CTZ(x) #ifndef RHINO_WEAK #define RHINO_WEAK __weak #endif #ifndef RHINO_ASM #define RHINO_ASM asm #endif /* Instruction Synchronization Barrier */ #define OS_ISB() __isb(15) /* Full system Any-Any */ /* Data Memory Barrier */ #define OS_DMB() __dmb(15) /* Full system Any-Any */ /* Data Synchronization Barrier */ #define OS_DSB() __dsb(15) /* Full system Any-Any */ #elif defined(__GNUC__) #define RHINO_INLINE static inline /* get the return address of the current function void * __builtin_return_address (unsigned int level) */ #define RHINO_GET_RA() __builtin_return_address(0) /* get the return address of the current function */ __attribute__((always_inline)) RHINO_INLINE void *RHINO_GET_SP(void) { void *sp; __asm__ volatile("mv %0, sp\n" : "=r"(sp)); return sp; } /* get the return address of the current function */ __attribute__((always_inline)) RHINO_INLINE void *RHINO_GET_PC(void) { void *pc; __asm__ volatile("auipc %0, 0\n" : "=r"(pc)); return pc; } /* Returns the number of leading 0-bits in x, starting at the most signifi cant bit position. */ #define RHINO_BIT_CLZ(x) __builtin_clz(x) /* Returns the number of trailing 0-bits in x, starting at the least signifi cant bit position. */ #define RHINO_BIT_CTZ(x) __builtin_ctz(x) #ifndef RHINO_WEAK #define RHINO_WEAK __attribute__((weak)) #endif #ifndef RHINO_ASM #define RHINO_ASM __asm__ #endif #else #error "Unsupported compiler" #endif #endif /* K_COMPILER_H */
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/k_compiler.h
C
apache-2.0
3,472
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <csi_core.h> #include <k_arch.h> #include <aos/debug.h> #define REG_NAME_WIDTH 8 extern volatile uint32_t g_crash_steps; typedef context_t PANIC_CONTEXT; typedef struct { long mcause; long mtval; long sp; long lr; } FAULT_REGS; static char *k_ll2str(intptr_t num, char *str) { int i = 15; char index[] = "0123456789ABCDEF"; uintptr_t usnum = (uintptr_t)num; for(; i >= 0; i--){ str[i] = index[usnum % 16]; usnum /= 16; } return str; } void panicGetCtx(void *context, char **pPC, char **pLR, int **pSP) { PANIC_CONTEXT *rv64_context = (PANIC_CONTEXT *)context; *pSP = (int *)((long)rv64_context + sizeof(PANIC_CONTEXT)); *pPC = (char *)rv64_context->PC; *pLR = (char *)rv64_context->X1; } void panicShowRegs(void *context, int (*print_func)(const char *fmt, ...)) { int x; long *regs = (long *)context; char s_panic_regs[REG_NAME_WIDTH + 14 + 8]; FAULT_REGS stFregs; /* PANIC_CONTEXT */ char s_panic_ctx[] = "X1(ra) " "X4(tp) " "X5(t0) " "X6(t1) " "X7(t2) " "X8(s0) " "X9(s1) " "X10(a0) " "X11(a1) " "X12(a2) " "X13(a3) " "X14(a4) " "X15(a5) " "X16(a6) " "X17(a7) " "X18(s2) " "X19(s3) " "X20(s4) " "X21(s5) " "X22(s6) " "X23(s7) " "X24(s8) " "X25(s9) " "X26(s10)" "X27(s11)" "X28(t3) " "X29(t4) " "X30(t5) " "X31(t6) " "MEPC " "MSTAT "; /* FAULT_REGS */ char s_panic_reg[] = "MCAUSE " "MTVAL " "SP " "LR "; if (regs == NULL) { return; } print_func("========== Regs info ==========\r\n"); /* show PANIC_CONTEXT */ for (x = 0; x < sizeof(s_panic_ctx) / REG_NAME_WIDTH; x++) { memcpy(&s_panic_regs[0], &s_panic_ctx[x * REG_NAME_WIDTH], REG_NAME_WIDTH); memcpy(&s_panic_regs[REG_NAME_WIDTH], " 0x", 3); k_ll2str(regs[x], &s_panic_regs[REG_NAME_WIDTH + 3]); s_panic_regs[REG_NAME_WIDTH + 11 + 8] = '\r'; s_panic_regs[REG_NAME_WIDTH + 12 + 8] = '\n'; s_panic_regs[REG_NAME_WIDTH + 13 + 8] = 0; print_func(s_panic_regs); } /* show FAULT_REGS */ stFregs.mcause = __get_MCAUSE(); stFregs.mtval = __get_MTVAL(); stFregs.sp = (long)(context + sizeof(PANIC_CONTEXT)); stFregs.lr = (long)regs[0]; for (x = 0; x < sizeof(stFregs) / sizeof(long); x++) { memcpy(&s_panic_regs[0], &s_panic_reg[x * REG_NAME_WIDTH], REG_NAME_WIDTH); memcpy(&s_panic_regs[REG_NAME_WIDTH], " 0x", 3); k_ll2str(((long *)(&stFregs))[x], &s_panic_regs[REG_NAME_WIDTH + 3]); s_panic_regs[REG_NAME_WIDTH + 11 + 8] = '\r'; s_panic_regs[REG_NAME_WIDTH + 12 + 8] = '\n'; s_panic_regs[REG_NAME_WIDTH + 13 + 8] = 0; print_func(s_panic_regs); } } #if (RHINO_CONFIG_CLI_AS_NMI > 0) void panicNmiInputFilter(uint8_t ch) { static int check_cnt = 0; /* for '$#@!' */ if ( ch == '$' && check_cnt == 0) { check_cnt++; } else if ( ch == '#' && check_cnt == 1) { check_cnt++; } else if ( ch == '@' && check_cnt == 2) { check_cnt++; } else if ( ch == '!' && check_cnt == 3) { panicNmiFlagSet(); __asm__ __volatile__("udf":::"memory"); } else { check_cnt = 0; } } #else void panicNmiInputFilter(uint8_t ch){} #endif extern void panicHandler(void *context); void exceptionHandler(void *context) { g_crash_steps++; if (g_crash_steps > 1) { context = NULL; } panicHandler(context); }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/panic_c.c
C
apache-2.0
4,468
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <k_api.h> #include <k_arch.h> void *cpu_task_stack_init(cpu_stack_t *stack_base, size_t stack_size, void *arg, task_entry_t entry) { cpu_stack_t *stk; /* stack aligned by 8 byte */ stk = (cpu_stack_t *)((uintptr_t)(stack_base + stack_size) & 0xfffffff0); *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F31 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F30 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F29 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F28 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F27 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F26 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F25 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F24 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F23 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F22 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F21 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F20 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F19 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F18 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F17 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F16 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F15 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F14 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F13 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F12 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F11 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F10 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F9 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F8 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F7 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F6 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F5 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F4 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F3 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F2 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F1 */ *(--stk) = (cpu_stack_t)0x1234567812345678L; /* F0 */ /* FS=0b01 MPP=0b11 MPIE=0b1 */ *(--stk) = (cpu_stack_t)SR_FS_INITIAL | SR_MPP_M | SR_MPIE; /* mstatus */ *(--stk) = (cpu_stack_t)entry; /* Entry Point */ *(--stk) = (cpu_stack_t)0x3131313131313131L; /* X31 */ *(--stk) = (cpu_stack_t)0x3030303030303030L; /* X30 */ *(--stk) = (cpu_stack_t)0x2929292929292929L; /* X29 */ *(--stk) = (cpu_stack_t)0x2828282828282828L; /* X28 */ *(--stk) = (cpu_stack_t)0x2727272727272727L; /* X27 */ *(--stk) = (cpu_stack_t)0x2626262626262626L; /* X26 */ *(--stk) = (cpu_stack_t)0x2525252525252525L; /* X25 */ *(--stk) = (cpu_stack_t)0x2424242424242424L; /* X24 */ *(--stk) = (cpu_stack_t)0x2323232323232323L; /* X23 */ *(--stk) = (cpu_stack_t)0x2222222222222222L; /* X22 */ *(--stk) = (cpu_stack_t)0x2121212121212121L; /* X21 */ *(--stk) = (cpu_stack_t)0x2020202020202020L; /* X20 */ *(--stk) = (cpu_stack_t)0x1919191919191919L; /* X19 */ *(--stk) = (cpu_stack_t)0x1818181818181818L; /* X18 */ *(--stk) = (cpu_stack_t)0x1717171717171717L; /* X17 */ *(--stk) = (cpu_stack_t)0x1616161616161616L; /* X16 */ *(--stk) = (cpu_stack_t)0x1515151515151515L; /* X15 */ *(--stk) = (cpu_stack_t)0x1414141414141414L; /* X14 */ *(--stk) = (cpu_stack_t)0x1313131313131313L; /* X13 */ *(--stk) = (cpu_stack_t)0x1212121212121212L; /* X12 */ *(--stk) = (cpu_stack_t)0x1111111111111111L; /* X11 */ *(--stk) = (cpu_stack_t)arg; /* X10 */ *(--stk) = (cpu_stack_t)0x0909090909090909L; /* X9 */ *(--stk) = (cpu_stack_t)0x0808080808080808L; /* X8 */ *(--stk) = (cpu_stack_t)0x0707070707070707L; /* X7 */ *(--stk) = (cpu_stack_t)0x0606060606060606L; /* X6 */ *(--stk) = (cpu_stack_t)0x0505050505050505L; /* X5 */ *(--stk) = (cpu_stack_t)0x0404040404040404L; /* X4 */ *(--stk) = (cpu_stack_t)krhino_task_deathbed; /* X1 */ return (void *)stk; }
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/port_c.c
C
apache-2.0
5,105
#include <k_config.h> #include <k_arch.h> /****************************************************************************** @ EXPORT FUNCTIONS @******************************************************************************/ .global cpu_intrpt_save .global cpu_intrpt_restore .global cpu_task_switch .global cpu_intrpt_switch .global cpu_first_task_start .extern task_restore /****************************************************************************** @ EQUATES @******************************************************************************/ .equ RISCV_MSTATUS_MIE, (1<<3) /*machine-level interrupt bit*/ /****************************************************************************** @ CODE GENERATION DIRECTIVES @*******************************************************************************/ .text .align 3 /****************************************************************************** @ Functions: @ size_t cpu_intrpt_save(void); @ void cpu_intrpt_restore(size_t cpsr); @******************************************************************************/ cpu_intrpt_save: csrrci a0, mstatus, RISCV_MSTATUS_MIE ret cpu_intrpt_restore: csrw mstatus, a0 ret /****************************************************************************** @ Functions: @ void cpu_intrpt_switch(void); @ void cpu_task_switch(void); @******************************************************************************/ cpu_task_switch: mv a0, x0 ecall ret cpu_intrpt_switch: ret /****************************************************************************** @ Functions: @ void cpu_first_task_start(void); @******************************************************************************/ .align 8 .func cpu_first_task_start: /* Enable mtime and external interrupts. */ li t0, (IE_MTIE | IE_MEIE) csrw mie, t0 la t0, task_restore jr t0 .endfunc
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/port_s.S
Unix Assembly
apache-2.0
2,024
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file startup.S * @brief startup file. Should use with * GCC for RISC-V Embedded Processors * @version V1.0 * @date 29. July 2019 ******************************************************************************/ #include <csi_config.h> #include <k_arch.h> .global sys_stack_base .global sys_stack_top .global exception_stack_base .global exception_stack_top .globl Reset_Handler .section .bss .align 3 sys_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK sys_stack_top: exception_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK exception_stack_top: .text .align 2 j Reset_Handler .align 2 .long 0x594B5343 /* CSKY ASCII */ .long 0x594B5343 /* CSKY ASCII */ .align 2 .long Reset_Handler _start: .type Reset_Handler, %function Reset_Handler: .option push .option norelax /* disable ie and clear all interrupts */ csrw mie, zero csrw mip, zero /* Disable MIE to avoid triggering interrupts before the first task starts. */ /* This bit is set when a task recovers context. */ li a0, SR_MIE csrc mstatus, a0 la gp, __global_pointer$ .option pop la a0, __Vectors csrw mtvec, a0 #if ((CONFIG_CPU_E906F==1) || (CONFIG_CPU_E906D==1))|| (CONFIG_CPU_C910D==1) li a0, 0x2000 csrs mstatus, a0 #endif #if ((CONFIG_CPU_E906F==1) || (CONFIG_CPU_E906D==1)) la a0, __Vectors csrw mtvt, a0 #endif la sp, sys_stack_top /* Clear bss section */ la a0, __bss_start__ la a1, __bss_end__ bgeu a0, a1, 2f 1: sd zero, (a0) addi a0, a0, 4 bltu a0, a1, 1b 2: #ifndef __NO_SYSTEM_INIT la a0, SystemInit jalr a0 #endif #ifndef __NO_BOARD_INIT la a0, board_pre_init jalr a0 #endif la a0, main jalr a0 .size Reset_Handler, . - Reset_Handler __exit: j __exit
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/startup.S
Motorola 68K Assembly
apache-2.0
2,088
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file startup.S * @brief startup file. Should use with * GCC for RISC-V Embedded Processors * @version V1.0 * @date 29. July 2019 ******************************************************************************/ #include <csi_config.h> #include <k_arch.h> .global sys_stack_base .global sys_stack_top .global exception_stack_base .global exception_stack_top .globl Reset_Handler .section .bss .align 3 sys_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK sys_stack_top: exception_stack_base: .space CONFIG_ARCH_INTERRUPTSTACK exception_stack_top: .text .align 2 j Reset_Handler .align 2 .long 0x594B5343 /* CSKY ASCII */ .long 0x594B5343 /* CSKY ASCII */ .align 2 .long Reset_Handler _start: .type Reset_Handler, %function Reset_Handler: .option push .option norelax /* disable ie and clear all interrupts */ csrw mie, zero csrw mip, zero /* Disable MIE to avoid triggering interrupts before the first task starts. */ /* This bit is set when a task recovers context. */ li a0, SR_MIE csrc mstatus, a0 la gp, __global_pointer$ .option pop la a0, __Vectors csrw mtvec, a0 #if ((CONFIG_CPU_E906F==1) || (CONFIG_CPU_E906D==1))|| (CONFIG_CPU_C910D==1) li a0, 0x2000 csrs mstatus, a0 #endif #if ((CONFIG_CPU_E906F==1) || (CONFIG_CPU_E906D==1)) la a0, __Vectors csrw mtvt, a0 #endif la sp, sys_stack_top /* Clear bss section */ la a0, __bss_start__ la a1, __bss_end__ bgeu a0, a1, 2f 1: sd zero, (a0) addi a0, a0, 4 bltu a0, a1, 1b 2: #ifndef __NO_SYSTEM_INIT la a0, SystemInit jalr a0 #endif #ifndef __NO_BOARD_INIT la a0, board_pre_init jalr a0 #endif /* enable interrupt */ li a0, SR_MIE csrs mstatus, a0 la a0, main jalr a0 .size Reset_Handler, . - Reset_Handler __exit: j __exit
YifuLiu/AliOS-Things
hardware/arch/riscv/src/rv64fd_32gpr/startup_boot.S
Motorola 68K Assembly
apache-2.0
2,163
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited * * License-Identifier: Apache-2.0 * * 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. * */ /****************************************************************************** * @file csi_kernel.h * @brief header file for kernel definition * @version V1.0 * @date 02. June 2017 ******************************************************************************/ #ifndef _CSI_KERNEL_ #define _CSI_KERNEL_ #if defined(CONFIG_KERNEL_RHINO) #include "k_api.h" #endif #include <stdlib.h> #include <stdint.h> #include <errno.h> #ifdef __cplusplus extern "C" { #endif /* =================================================================================== */ /* Enumerations, structures, defines */ /* =================================================================================== */ /// Status code values returned by CSI-kernel functions. 0 - success, negative represents error code ,see errno.h typedef int32_t k_status_t; /// Kernel scheduler state. typedef enum { KSCHED_ST_INACTIVE = 0, ///< Inactive: The kernel is not ready yet. csi_kernel_init needs to be executed successfully. KSCHED_ST_READY = 1, ///< Ready: The kernel is not yet running. csi_kernel_start transfers the kernel to the running state. KSCHED_ST_RUNNING = 2, ///< Running: The kernel is initialized and running. KSCHED_ST_LOCKED = 3, ///< Locked: The kernel was locked with csi_kernel_sched_lock. The functions csi_kernel_sched_unlock or csi_kernel_sched_restore_lock unlocks it. KSCHED_ST_SUSPEND = 4, ///< Suspended: The kernel was suspended using csi_kernel_sched_suspend. The function csi_kernel_sched_resume returns to normal operation KSCHED_ST_ERROR = 5 ///< Error: An error occurred. } k_sched_stat_t; /// task state. typedef enum { KTASK_ST_INACTIVE = 0, ///< Inactive. KTASK_ST_READY = 1, ///< Ready. KTASK_ST_RUNNING = 2, ///< Running. KTASK_ST_BLOCKED = 3, ///< Blocked. KTASK_ST_TERMINATED = 4, ///< Terminated. KTASK_ST_ERROR = 5 ///< Error: An error occurred. } k_task_stat_t; /// timer state. typedef enum { KTIMER_ST_INACTIVE = 0, ///< not running KTIMER_ST_ACTIVE = 1, ///< running } k_timer_stat_t; /// Timer type. typedef enum { KTIMER_TYPE_ONCE = 0, ///< One-shot timer. KTIMER_TYPE_PERIODIC = 1 ///< Repeating timer. } k_timer_type_t; /// event option. typedef enum { KEVENT_OPT_SET_ANY = 0, ///< Check any bit in flags to be 1. KEVENT_OPT_SET_ALL = 1, ///< Check all bits in flags to be 1. KEVENT_OPT_CLR_ANY = 2, ///< Check any bit in flags to be 0. KEVENT_OPT_CLR_ALL = 3 ///< Check all bits in flags to be 0. } k_event_opt_t; /// Priority definition. typedef enum { KPRIO_IDLE = 0, ///< priority: idle (lowest) KPRIO_LOW0 , ///< priority: low KPRIO_LOW1 , ///< priority: low + 1 KPRIO_LOW2 , ///< priority: low + 2 KPRIO_LOW3 , ///< priority: low + 3 KPRIO_LOW4 , ///< priority: low + 4 KPRIO_LOW5 , ///< priority: low + 5 KPRIO_LOW6 , ///< priority: low + 6 KPRIO_LOW7 , ///< priority: low + 7 KPRIO_NORMAL_BELOW0 , ///< priority: below normal KPRIO_NORMAL_BELOW1 , ///< priority: below normal + 1 KPRIO_NORMAL_BELOW2 , ///< priority: below normal + 2 KPRIO_NORMAL_BELOW3 , ///< priority: below normal + 3 KPRIO_NORMAL_BELOW4 , ///< priority: below normal + 4 KPRIO_NORMAL_BELOW5 , ///< priority: below normal + 5 KPRIO_NORMAL_BELOW6 , ///< priority: below normal + 6 KPRIO_NORMAL_BELOW7 , ///< priority: below normal + 7 KPRIO_NORMAL , ///< priority: normal (default) KPRIO_NORMAL1 , ///< priority: normal + 1 KPRIO_NORMAL2 , ///< priority: normal + 2 KPRIO_NORMAL3 , ///< priority: normal + 3 KPRIO_NORMAL4 , ///< priority: normal + 4 KPRIO_NORMAL5 , ///< priority: normal + 5 KPRIO_NORMAL6 , ///< priority: normal + 6 KPRIO_NORMAL7 , ///< priority: normal + 7 KPRIO_NORMAL_ABOVE0 , ///< priority: above normal + 1 KPRIO_NORMAL_ABOVE1 , ///< priority: above normal + 2 KPRIO_NORMAL_ABOVE2 , ///< priority: above normal + 3 KPRIO_NORMAL_ABOVE3 , ///< priority: above normal + 4 KPRIO_NORMAL_ABOVE4 , ///< priority: above normal + 5 KPRIO_NORMAL_ABOVE5 , ///< priority: above normal + 6 KPRIO_NORMAL_ABOVE6 , ///< priority: above normal + 7 KPRIO_NORMAL_ABOVE7 , ///< priority: above normal + 8 KPRIO_HIGH0 , ///< priority: high KPRIO_HIGH1 , ///< priority: high + 1 KPRIO_HIGH2 , ///< priority: high + 2 KPRIO_HIGH3 , ///< priority: high + 3 KPRIO_HIGH4 , ///< priority: high + 4 KPRIO_HIGH5 , ///< priority: high + 5 KPRIO_HIGH6 , ///< priority: high + 6 KPRIO_HIGH7 , ///< priority: high + 7 KPRIO_REALTIME0 , ///< priority: realtime + 1 KPRIO_REALTIME1 , ///< priority: realtime + 2 KPRIO_REALTIME2 , ///< priority: realtime + 3 KPRIO_REALTIME3 , ///< priority: realtime + 4 KPRIO_REALTIME4 , ///< priority: realtime + 5 KPRIO_REALTIME5 , ///< priority: realtime + 6 KPRIO_REALTIME6 , ///< priority: realtime + 7 KPRIO_REALTIME7 , ///< priority: realtime + 8 KPRIO_ISR , ///< priority: Reserved for ISR deferred thread KPRIO_ERROR ///< Illegal priority } k_priority_t; /// Entry point of a task. typedef void (*k_task_entry_t)(void *arg); /// Entry point of a timer call back function. typedef void (*k_timer_cb_t)(void *arg); /// \details Task handle identifies the task. typedef void *k_task_handle_t; /// \details Timer handle identifies the timer. typedef void *k_timer_handle_t; /// \details Event Flags handle identifies the event flags. typedef void *k_event_handle_t; /// \details Mutex handle identifies the mutex. typedef void *k_mutex_handle_t; /// \details Semaphore handle identifies the semaphore. typedef void *k_sem_handle_t; /// \details Memory Pool handle identifies the memory pool. typedef void *k_mpool_handle_t; /// \details Message Queue handle identifies the message queue. typedef void *k_msgq_handle_t; /* =================================================================================== */ /* Kernel Management Functions */ /* =================================================================================== */ /// Initialize the Kernel. Before it is successfully executed, no RTOS function should be called /// \return execution status code. \ref k_status_t k_status_t csi_kernel_init(void); /// Start the kernel .It will not return to its calling function in case of success /// \return execution status code. \ref k_status_t k_status_t csi_kernel_start(void); /// Get the current kernel state. /// \return current kernel state \ref k_sched_stat_t . k_sched_stat_t csi_kernel_get_stat(void); /* =================================================================================== */ /* scheduler Management Functions */ /* =================================================================================== */ /// Lock the scheduler. /// \return previous lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_lock(void); /// Unlock the scheduler. /// \return previous lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_unlock(void); /// Restore the scheduler lock state. /// \param[in] lock lock state obtained by \ref csi_kernel_sched_lock or \ref csi_kernel_sched_unlock. /// \return new lock state (1 - locked, 0 - not locked, error code if negative). int32_t csi_kernel_sched_restore_lock(int32_t lock); /// Suspend the scheduler. /// \return time in ticks, for how long the system can sleep or power-down. uint32_t csi_kernel_sched_suspend(void); /// Resume the scheduler. /// \param[in] sleep_ticks time in ticks for how long the system was in sleep or power-down mode. void csi_kernel_sched_resume(uint32_t sleep_ticks); /* =================================================================================== */ /* Task Management Functions */ /* =================================================================================== */ /// Create a task and add it to Active Tasks. /// \param[in] task task function. /// \param[in] name the name of task. /// \param[in] arg pointer that is passed to the task function as start argument. /// \param[in] prio task priority. /// \param[in] time_quanta the amount of time (in clock ticks) for the time quanta when round robin is enabled,if Zero, then use FIFO sched /// \param[in] stack stack base. /// \param[in] stack_size stack size. /// \param[in] task_handle reference to a task handle. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_new(k_task_entry_t task, const char *name, void *arg, k_priority_t prio, uint32_t time_quanta, void *stack, uint32_t stack_size, k_task_handle_t *task_handle); /// Delete a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_del(k_task_handle_t task_handle); /// Return the task handle of the current running task. /// \return task handle for reference by other functions or NULL in case of error. k_task_handle_t csi_kernel_task_get_cur(void); /// Get current task state of a task. /// \param[in] task_handle task handle to operate. /// \return current task state of the specified task. k_task_stat_t csi_kernel_task_get_stat(k_task_handle_t task_handle); /// Change priority of a task. /// \param[in] task_handle task handle to operate. /// \param[in] priority new priority value for the task function. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_set_prio(k_task_handle_t task_handle, k_priority_t priority); /// Get current priority of a task. /// \param[in] task_handle task handle to operate. /// \return current priority value of the specified task.negative indicates error code. k_priority_t csi_kernel_task_get_prio(k_task_handle_t task_handle); /// Get name of a task. /// \param[in] task_handle task handle to operate. /// \return name of the task. const char *csi_kernel_task_get_name(k_task_handle_t task_handle); /// Suspend execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_suspend(k_task_handle_t task_handle); /// Resume execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_resume(k_task_handle_t task_handle); /// Terminate execution of a task. /// \param[in] task_handle task handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_terminate(k_task_handle_t task_handle); /// Exit from the calling task. /// \return none void csi_kernel_task_exit(void); /// Pass control to next task that is in state \b READY. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_task_yield(void); /// Get number of active tasks. /// \return number of active tasks. uint32_t csi_kernel_task_get_count(void); /// Get stack size of a task. /// \param[in] task_handle task handle to operate. /// \return stack size in bytes. uint32_t csi_kernel_task_get_stack_size(k_task_handle_t task_handle); /// Get available stack space of a thread based on stack watermark recording during execution. /// \param[in] task_handle task handle to operate. /// \return remaining stack space in bytes. uint32_t csi_kernel_task_get_stack_space(k_task_handle_t task_handle); /// Enumerate active tasks. /// \param[out] task_array pointer to array for retrieving task handles. /// \param[in] array_items maximum number of items in array for retrieving task handles. /// \return number of enumerated tasks. uint32_t csi_kernel_task_list(k_task_handle_t *task_array, uint32_t array_items); /// System enter interrupt status. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_intrpt_enter(void); /// System exit interrupt status. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_intrpt_exit(void); /* =================================================================================== */ /* Generic time Functions */ /* =================================================================================== */ /// Waits for a time period specified in kernel ticks. /// \param[in] ticks time ticks value /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay(uint32_t ticks); /// Waits until an absolute time (specified in kernel ticks) is reached. /// \param[in] ticks absolute time in ticks /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay_until(uint64_t ticks); /// Convert kernel ticks to ms. /// \param[in] ticks ticks which will be converted to ms /// \return the ms of the ticks. uint64_t csi_kernel_tick2ms(uint32_t ticks); /// Convert ms to kernel ticks. /// \param[in] ms ms which will be converted to ticks /// \return the ticks of the ms. uint64_t csi_kernel_ms2tick(uint32_t ms); /// Waits for a time period specified in ms. /// \param[in] ms time to be delayed in ms /// \return execution status code. \ref k_status_t k_status_t csi_kernel_delay_ms(uint32_t ms); /// Get kernel ticks. /// \return kernel ticks number uint64_t csi_kernel_get_ticks(void); /// Get the RTOS kernel tick frequency. /// \return frequency of the kernel tick. uint32_t csi_kernel_get_tick_freq(void); /// Get the RTOS kernel system timer frequency. /// \return frequency of the system timer. uint32_t csi_kernel_get_systimer_freq(void); /* =================================================================================== */ /* Timer Management Functions */ /* =================================================================================== */ /// Create and Initialize a timer. /// \param[in] func start address of a timer call back function. /// \param[in] type time type, \ref k_timer_type_t. /// \param[in] arg argument to the timer call back function. /// \return timer handle for reference by other functions or NULL in case of error. k_timer_handle_t csi_kernel_timer_new(k_timer_cb_t func, k_timer_type_t type, void *arg); /// Delete a timer. /// \param[in] timer_handle timer handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_del(k_timer_handle_t timer_handle); /// Start or restart a timer. /// \param[in] timer_handle timer handle to operate. /// \param[in] ticks time out value in ticks /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_start(k_timer_handle_t timer_handle, uint32_t ticks); /// Stop a timer. /// \param[in] timer_handle timer handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_timer_stop(k_timer_handle_t timer_handle); /// Check if a timer is running. /// \param[in] timer_handle timer handle to operate. /// \return \ref k_timer_stat_t. k_timer_stat_t csi_kernel_timer_get_stat(k_timer_handle_t timer_handle); /* =================================================================================== */ /* Event Management Functions */ /* =================================================================================== */ /// Create and Initialize an Event Flags object. /// \return event flags handle for reference by other functions or NULL in case of error. k_event_handle_t csi_kernel_event_new(void); /// Delete an Event Flags object. /// \param[in] ev_handle event flags handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_del(k_event_handle_t ev_handle); /// Set the specified Event Flags. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags that shall be set. /// \param[out] ret_flags The value of the event after setting. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_set(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags); /// Clear the specified Event Flags. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags that shall be clear. /// \param[out] ret_flags event flags before clearing. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_clear(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags); /// Get the current Event Flags. This function allows the user to know “Who did it!” /// \param[in] ev_handle event flags handle to operate. /// \param[out] ret_flags The value of the current event. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_get(k_event_handle_t ev_handle, uint32_t *ret_flags); /// Wait for one or more Event Flags to become signaled. /// \param[in] ev_handle event flags handle to operate. /// \param[in] flags specifies the flags to wait for. /// \param[in] options specifies flags options, \ref k_event_opt_t. /// \param[in] clr_on_exit 1 - event flags will be cleared before exit, otherwise event flags are not altered /// \param[out] actl_flags The value of the event at the time either the bits being waited for became set, or the block time expired. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_event_wait(k_event_handle_t ev_handle, uint32_t flags, k_event_opt_t options, uint8_t clr_on_exit, uint32_t *actl_flags, int64_t timeout); /* =================================================================================== */ /* Mutex Management Functions */ /* =================================================================================== */ /// Create and Initialize a Mutex object. /// \return mutex handle for reference by other functions or NULL in case of error. k_mutex_handle_t csi_kernel_mutex_new(void); /// Delete a Mutex object. /// \param[in] mutex_handle mutex handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_del(k_mutex_handle_t mutex_handle); /// Acquire a Mutex or timeout if it is locked. /// \param[in] mutex_handle mutex handle to operate. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_lock(k_mutex_handle_t mutex_handle, int64_t timeout); /// Release a Mutex that was acquired by \ref csi_kernel_mutex_new. /// \param[in] mutex_handle mutex handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mutex_unlock(k_mutex_handle_t mutex_handle); /// Get Thread which owns a Mutex object. /// \param[in] mutex_handle mutex handle to operate. /// \return task handle or NULL when mutex was not acquired. k_task_handle_t csi_kernel_mutex_get_owner(k_mutex_handle_t mutex_handle); /* =================================================================================== */ /* Semaphore Management Functions */ /* =================================================================================== */ /// Create and Initialize a Semaphore object. /// \param[in] max_count maximum number of available tokens. /// \param[in] initial_count initial number of available tokens. /// \return semaphore handle for reference by other functions or NULL in case of error. k_sem_handle_t csi_kernel_sem_new(int32_t max_count, int32_t initial_count); /// Delete a Semaphore object. /// \param[in] sem_handle semaphore handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_del(k_sem_handle_t sem_handle); /// Acquire a Semaphore token or timeout if no tokens are available. /// \param[in] sem_handle semaphore handle to operate. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_wait(k_sem_handle_t sem_handle, int64_t timeout); /// Release a Semaphore token that was acquired by \ref csi_kernel_sem_wait. /// \param[in] sem_handle semaphore handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_sem_post(k_sem_handle_t sem_handle); /// Get current Semaphore token count. /// \param[in] sem_handle semaphore handle to operate. /// \return number of tokens available. negative indicates error code. int32_t csi_kernel_sem_get_count(k_sem_handle_t sem_handle); /* =================================================================================== */ /* Memory Pool Management Functions */ /* =================================================================================== */ /// Create and Initialize a Memory Pool object. /// \param[in] p_addr memory block base address. /// \param[in] block_count maximum number of memory blocks in memory pool. /// \param[in] block_size memory block size in bytes. /// \return memory pool handle for reference by other functions or NULL in case of error. k_mpool_handle_t csi_kernel_mpool_new(void *p_addr, int32_t block_count, int32_t block_size); /// Delete a Memory Pool object. /// \param[in] mp_handle memory pool handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mpool_del(k_mpool_handle_t mp_handle); /// Allocate a memory block from a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \param[in] size alloc size < /// \return address of the allocated memory block or NULL in case of no memory is available. void *csi_kernel_mpool_alloc(k_mpool_handle_t mp_handle, uint32_t size); /// Return an allocated memory block back to a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \param[in] block address of the allocated memory block to be returned to the memory pool. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_mpool_free(k_mpool_handle_t mp_handle, void *block); /// Get number of memory blocks used in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return number of memory blocks used. negative indicates error code. int32_t csi_kernel_mpool_get_count(k_mpool_handle_t mp_handle); /// Get maximum number of memory blocks in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return maximum number of memory blocks. uint32_t csi_kernel_mpool_get_capacity(k_mpool_handle_t mp_handle); /// Get memory block size in a Memory Pool. /// \param[in] mp_handle memory pool handle to operate. /// \return memory block size in bytes. uint32_t csi_kernel_mpool_get_block_size(k_mpool_handle_t mp_handle); /* =================================================================================== */ /* Message Queue Management Functions */ /* =================================================================================== */ /// Create and Initialize a Message Queue object. /// \param[in] msg_count maximum number of messages in queue. /// \param[in] msg_size maximum message size in bytes. /// \return message queue handle for reference by other functions or NULL in case of error. k_msgq_handle_t csi_kernel_msgq_new(int32_t msg_count, int32_t msg_size); /// Delete a Message Queue object. /// \param[in] mq_handle message queue handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_del(k_msgq_handle_t mq_handle); /// Put a Message into a Queue or timeout if Queue is full. /// \param[in] mq_handle message queue handle to operate. /// \param[in] msg_ptr pointer to buffer with message to put into a queue. /// \param[in] front_or_back specify this msg to be put to front or back. 1 - front, 0 -back /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_put(k_msgq_handle_t mq_handle, const void *msg_ptr, uint8_t front_or_back, int64_t timeout); /// Get a Message from a Queue or timeout if Queue is empty. /// \param[in] mq_handle message queue handle to operate. /// \param[out] msg_ptr pointer to buffer for message to get from a queue. /// \param[in] timeout time out value in ticks if > 0, 0 in case of no time-out, negative in case of wait forever /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_get(k_msgq_handle_t mq_handle, void *msg_ptr, int64_t timeout); /// Get number of queued messages in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return number of queued messages.negative indicates error code. int32_t csi_kernel_msgq_get_count(k_msgq_handle_t mq_handle); /// Get maximum number of messages in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return maximum number of messages. uint32_t csi_kernel_msgq_get_capacity(k_msgq_handle_t mq_handle); /// Get maximum message size in a message queue. /// \param[in] mq_handle message queue handle to operate. /// \return maximum message size in bytes. uint32_t csi_kernel_msgq_get_msg_size(k_msgq_handle_t mq_handle); /// Reset a Message Queue to initial empty state. /// \param[in] mq_handle message queue handle to operate. /// \return execution status code. \ref k_status_t k_status_t csi_kernel_msgq_flush(k_msgq_handle_t mq_handle); /* =================================================================================== */ /* Heap Management Functions */ /* =================================================================================== */ /// Allocates size bytes and returns a pointer to the allocated memory. /// \param[in] size Allocates size bytes. /// \param[in] caller the function who call this interface or NULL. /// \return a pointer to the allocated memory. void *csi_kernel_malloc(size_t size, void *caller); /// Frees the memory space pointed to by ptr /// \param[in] ptr a pointer to memory block, return by csi_kernel_malloc or csi_kernel_realloc. /// \param[in] caller the function who call this interface or NULL. /// \return void void csi_kernel_free(void *ptr, void *caller); /// Changes the size of the memory block pointed to by ptr to size bytes /// \param[in] ptr a pointer to memory block, return by csi_kernel_malloc or csi_kernel_realloc. /// \param[in] size Allocates size bytes. /// \param[in] caller the function who call this interface or NULL. /// \return a pointer to the allocated memory. void *csi_kernel_realloc(void *ptr, size_t size, void *caller); /// Get csi memory used info. /// \param[out] total the total memory can be use. /// \param[out] used the used memory by malloc. /// \param[out] free the free memory can be use. /// \param[out] peak the peak memory used. /// \return execution status code. \ref k_status_t. k_status_t csi_kernel_get_mminfo(int32_t *total, int32_t *used, int32_t *free, int32_t *peak); /// Dump csi memory . /// \param void /// \return execution status code. \ref k_status_t. k_status_t csi_kernel_mm_dump(void); #ifdef __cplusplus } #endif #endif // _CSI_KERNEL_
YifuLiu/AliOS-Things
hardware/board/c906/adapter/csi_kernel.h
C
apache-2.0
30,441
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited * * License-Identifier: Apache-2.0 * * 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. * */ /****************************************************************************** * @file csi_rhino.c * @brief the adapter file for the rhino * @version V1.0 * @date 20. July 2016 ******************************************************************************/ #include <csi_kernel.h> #include <k_api.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <csi_config.h> #include <soc.h> extern uint32_t dump_mmleak(void); #define AUTORUN 1 #define TMR_ONE_SHOT_DLY 10 #define TMR_PERIODIC_PERIOD 10 #define RHINO_OS_MS_PERIOD_TICK (1000 / RHINO_CONFIG_TICKS_PER_SECOND) k_status_t csi_kernel_init(void) { kstat_t ret = krhino_init(); #ifdef CONFIG_KERNEL_PWR_MGMT extern void cpu_pwrmgmt_init(void); cpu_pwrmgmt_init(); #endif if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_status_t csi_kernel_start(void) { kstat_t ret = krhino_start(); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_sched_stat_t csi_kernel_get_stat(void) { kstat_t get = g_sys_stat; if (get == RHINO_STOPPED) { return KSCHED_ST_INACTIVE; } else if (get == RHINO_RUNNING) { return KSCHED_ST_RUNNING; } return KSCHED_ST_ERROR; } int32_t csi_kernel_sched_lock(void) { return -EOPNOTSUPP; } int32_t csi_kernel_sched_unlock(void) { return -EOPNOTSUPP; } int32_t csi_kernel_sched_restore_lock(int32_t lock) { return -EOPNOTSUPP; } uint32_t csi_kernel_sched_suspend(void) { if (g_sys_stat != RHINO_RUNNING) { return 0; } krhino_sched_disable(); return 0; } void csi_kernel_sched_resume(uint32_t sleep_ticks) { if (g_sys_stat != RHINO_RUNNING) { return; } krhino_sched_enable(); } k_status_t csi_kernel_task_new(k_task_entry_t task, const char *name, void *arg, k_priority_t prio, uint32_t time_quanta, void *stack, uint32_t stack_size, k_task_handle_t *task_handle) { if ((task_handle == NULL) || (stack_size % sizeof(cpu_stack_t) != 0) || ((stack_size == 0) && (stack == NULL)) || prio <= KPRIO_IDLE || prio > KPRIO_REALTIME7) { return -EINVAL; } k_status_t rc = -1; #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) uint8_t prio_trans = RHINO_CONFIG_USER_PRI_MAX - prio; csi_kernel_sched_suspend(); kstat_t ret; if (name) { ret = krhino_task_dyn_create((ktask_t **)task_handle, name, arg, prio_trans, time_quanta, stack_size / sizeof(cpu_stack_t), task, AUTORUN); } else { ret = krhino_task_dyn_create((ktask_t **)task_handle, "user_task", arg, prio_trans, time_quanta, stack_size / sizeof(cpu_stack_t), task, AUTORUN); } if (ret == RHINO_SUCCESS) { csi_kernel_sched_resume(0); return 0; } else { csi_kernel_sched_resume(0); return -EPERM; } #endif return rc; } k_status_t csi_kernel_task_del(k_task_handle_t task_handle) { if (task_handle == NULL) { return -EINVAL; } k_status_t rc = -1; #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_task_dyn_del(task_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } #endif return rc; } k_task_handle_t csi_kernel_task_get_cur(void) { ktask_t *ret; ret = g_active_task[cpu_cur_get()]; return (k_task_handle_t)ret; } k_task_stat_t csi_kernel_task_get_stat(k_task_handle_t task_handle) { if (task_handle == NULL) { return KTASK_ST_ERROR; } if (csi_kernel_task_get_cur() == task_handle) { return KTASK_ST_RUNNING; } task_stat_t get; ktask_t *handle = (ktask_t *)task_handle; get = handle->task_state; switch (get) { case K_PEND: case K_SUSPENDED: case K_PEND_SUSPENDED: case K_SLEEP: case K_SLEEP_SUSPENDED: return KTASK_ST_BLOCKED; break; case K_DELETED: return KTASK_ST_TERMINATED; break; case K_RDY: return KTASK_ST_READY; break; default: return KTASK_ST_ERROR; } } k_status_t csi_kernel_task_set_prio(k_task_handle_t task_handle, k_priority_t priority) { if (task_handle == NULL || priority <= KPRIO_IDLE || priority > KPRIO_REALTIME7) { return -EINVAL; } uint8_t prio = RHINO_CONFIG_USER_PRI_MAX - priority; uint8_t old; kstat_t ret = krhino_task_pri_change(task_handle, prio, &old); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_priority_t csi_kernel_task_get_prio(k_task_handle_t task_handle) { if (task_handle == NULL) { return KPRIO_ERROR; } ktask_t *handle = (ktask_t *)task_handle; uint8_t ret = handle->prio; if (ret <= RHINO_CONFIG_USER_PRI_MAX) { ret = RHINO_CONFIG_USER_PRI_MAX - ret; } else { ret = RHINO_CONFIG_PRI_MAX - ret; } return ret; } const char *csi_kernel_task_get_name(k_task_handle_t task_handle) { if (task_handle == NULL) { return NULL; } ktask_t *handle = (ktask_t *)task_handle; return handle->task_name; } k_status_t csi_kernel_task_suspend(k_task_handle_t task_handle) { if (task_handle == NULL) { return -EINVAL; } kstat_t ret = krhino_task_suspend(task_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_status_t csi_kernel_task_resume(k_task_handle_t task_handle) { if (task_handle == NULL) { return -EINVAL; } kstat_t ret = krhino_task_resume(task_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_status_t csi_kernel_task_terminate(k_task_handle_t task_handle) { return csi_kernel_task_del(task_handle); } void csi_kernel_task_exit(void) { csi_kernel_task_del(csi_kernel_task_get_cur()); } k_status_t csi_kernel_task_yield(void) { kstat_t ret = krhino_task_yield(); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } uint32_t csi_kernel_task_get_count(void) { #if (RHINO_CONFIG_SYSTEM_STATS > 0) klist_t *taskhead; klist_t *taskend; klist_t *tmp; taskhead = &g_kobj_list.task_head; taskend = taskhead; uint32_t ret = 0; for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) { ret ++; } return ret; #else return 0; #endif } uint32_t csi_kernel_task_get_stack_size(k_task_handle_t task_handle) { if (task_handle == NULL) { return 0; } ktask_t *handle = (ktask_t *)task_handle; return sizeof(cpu_stack_t) * handle->stack_size; } uint32_t csi_kernel_task_get_stack_space(k_task_handle_t task_handle) { if (task_handle == NULL) { return 0; } size_t stack_free; kstat_t ret = krhino_task_stack_min_free(task_handle, &stack_free); if (ret == RHINO_SUCCESS) { return (uint32_t)(sizeof(cpu_stack_t) * stack_free); } else { return 0; } } uint32_t csi_kernel_task_list(k_task_handle_t *task_array, uint32_t array_items) { if (task_array == NULL || array_items == 0) { return 0; } uint32_t real_tsk_num = 0; #if (RHINO_CONFIG_SYSTEM_STATS > 0) klist_t *taskhead; klist_t *taskend; klist_t *tmp; ktask_t *task; k_task_handle_t *tk_tmp = task_array; taskhead = &g_kobj_list.task_head; taskend = taskhead; #ifdef CONFIG_BACKTRACE uint32_t task_free; size_t irq_flags; #endif #ifdef CONFIG_STACK_GUARD int stack_flags; #endif for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) { real_tsk_num ++; task = krhino_list_entry(tmp, ktask_t, task_stats_item); #ifdef CONFIG_BACKTRACE krhino_task_stack_min_free(task, &task_free); printf("\n%s:\n\t state %d, pri %d, stack: total %p, free %p\n", task->task_name, task->task_state, task->prio, sizeof(cpu_stack_t) * task->stack_size, sizeof(cpu_stack_t) * task_free); #endif } if (array_items < real_tsk_num) { real_tsk_num = array_items; } for (tmp = taskhead->next; tmp != taskend && real_tsk_num >= 1; tmp = tmp->next) { task = krhino_list_entry(tmp, ktask_t, task_stats_item); *tk_tmp = task; tk_tmp ++; } #ifdef CONFIG_BACKTRACE irq_flags = cpu_intrpt_save(); #ifdef CONFIG_STACK_GUARD extern int stack_guard_save(void); stack_flags = stack_guard_save(); #endif for (tmp = taskhead->next; tmp != taskend; tmp = tmp->next) { task = krhino_list_entry(tmp, ktask_t, task_stats_item); krhino_task_stack_min_free(task, &task_free); printf("\n%s:\n", task->task_name); extern int csky_task_backtrace(void *stack, char *buf, int len); csky_task_backtrace(task->task_stack, NULL, 0); } #ifdef CONFIG_STACK_GUARD extern void stack_guard_restore(int value); stack_guard_restore(stack_flags); #endif cpu_intrpt_restore(irq_flags); #endif /* CONFIG_BACKTRACE */ #endif /* RHINO_CONFIG_SYSTEM_STATS */ return real_tsk_num; } k_status_t csi_kernel_intrpt_enter(void) { kstat_t ret = krhino_intrpt_enter(); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } return 0; } k_status_t csi_kernel_intrpt_exit(void) { krhino_intrpt_exit(); return 0; } k_status_t csi_kernel_delay(uint32_t ticks) { kstat_t ret = krhino_task_sleep(ticks); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_status_t csi_kernel_delay_until(uint64_t ticks) { return -EOPNOTSUPP; } uint64_t csi_kernel_tick2ms(uint32_t ticks) { return ((uint64_t)ticks * RHINO_OS_MS_PERIOD_TICK); } uint64_t csi_kernel_ms2tick(uint32_t ms) { if (ms < RHINO_OS_MS_PERIOD_TICK) { return 0; } return (((uint64_t)ms) / RHINO_OS_MS_PERIOD_TICK); } k_status_t csi_kernel_delay_ms(uint32_t ms) { uint32_t ms_get = ms; if ((ms < RHINO_OS_MS_PERIOD_TICK) && (ms != 0)) { ms_get = RHINO_OS_MS_PERIOD_TICK; } uint64_t ticks = csi_kernel_ms2tick(ms_get); kstat_t ret = krhino_task_sleep(ticks); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } uint64_t csi_kernel_get_ticks(void) { return (uint64_t)krhino_sys_tick_get(); } uint64_t csi_kernel_suspend_tick(void) { // return next_task_wake_tick_get(); return 0; } void csi_kernel_update_tick(uint32_t ms) { extern uint64_t g_sys_tick_count; uint32_t ticks = ms * RHINO_CONFIG_TICKS_PER_SECOND / 1000; CPSR_ALLOC(); RHINO_CPU_INTRPT_DISABLE(); g_sys_tick_count += ticks; RHINO_CPU_INTRPT_ENABLE(); } uint32_t csi_kernel_get_tick_freq(void) { return RHINO_CONFIG_TICKS_PER_SECOND; } uint32_t csi_kernel_get_systimer_freq(void) { return drv_get_sys_freq(); } typedef struct tmr_arg { void *arg; k_timer_cb_t func; } tmr_arg_t; static void tmr_adapt_cb(void *timer, void *arg) { ktimer_t *get = (ktimer_t *)timer; tmr_arg_t *arg_above = (tmr_arg_t *)(get->timer_cb_arg); if (arg_above->func) { arg_above->func(arg_above->arg); } return; } k_timer_handle_t csi_kernel_timer_new(k_timer_cb_t func, k_timer_type_t type, void *arg) { if (type < 0 || type > 1 || func == NULL) { return NULL; } tick_t first = TMR_ONE_SHOT_DLY; tick_t round; if (type == KTIMER_TYPE_ONCE) { round = 0; } else { round = TMR_PERIODIC_PERIOD; } tmr_arg_t *get_arg = (tmr_arg_t *)malloc(sizeof(tmr_arg_t)); if (get_arg == NULL) { return NULL; } ktimer_t *tmr; get_arg->arg = arg; get_arg->func = func; #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_timer_dyn_create((ktimer_t **)&tmr, "UserTmr", (timer_cb_t)tmr_adapt_cb, first, round, get_arg, 0); if (ret == RHINO_SUCCESS) { return tmr; } else { free((void *)get_arg); return NULL; } #else free((void *)get_arg); return NULL; #endif } k_status_t csi_kernel_timer_del(k_timer_handle_t timer_handle) { if (timer_handle == NULL) { return -EINVAL; } k_status_t rc = -1; #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_timer_dyn_del((ktimer_t *)timer_handle); if (ret == RHINO_SUCCESS) { free(((ktimer_t *)timer_handle)->timer_cb_arg); return 0; } else { return -EPERM; } #endif return rc; } k_status_t csi_kernel_timer_start(k_timer_handle_t timer_handle, uint32_t ticks) { if (timer_handle == NULL || ticks == 0) { return -EINVAL; } tick_t round; ktimer_t *handle = (ktimer_t *)timer_handle; round = handle->round_ticks; tick_t tr; tick_t tf = ticks; if (round != 0) { tr = ticks; } else { tr = 0; } kstat_t ret1 = krhino_timer_change(handle, tf, tr); if (ret1 == RHINO_SUCCESS) { kstat_t ret2 = krhino_timer_start(handle); if (ret2 == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } else { return -EPERM; } } k_status_t csi_kernel_timer_stop(k_timer_handle_t timer_handle) { if (timer_handle == NULL) { return -EINVAL; } ktimer_t *handle = (ktimer_t *)timer_handle; kstat_t ret = krhino_timer_stop(handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } k_timer_stat_t csi_kernel_timer_get_stat(k_timer_handle_t timer_handle) { if (timer_handle == NULL) { return KTIMER_ST_INACTIVE; } ktimer_t *handle = (ktimer_t *)(timer_handle); k_timer_state_t get = handle->timer_state; if (get == TIMER_DEACTIVE) { return KTIMER_ST_INACTIVE; } else { return KTIMER_ST_ACTIVE; } } k_event_handle_t csi_kernel_event_new(void) { #if (RHINO_CONFIG_EVENT_FLAG > 0) #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kevent_t *event_handle; kstat_t ret = krhino_event_dyn_create((kevent_t **)&event_handle, "UserEvent", 0); if (ret == RHINO_SUCCESS) { return event_handle; } else { return NULL; } #else return NULL: #endif #else return NULL; #endif } k_status_t csi_kernel_event_del(k_event_handle_t ev_handle) { #if (RHINO_CONFIG_EVENT_FLAG > 0) if (ev_handle == NULL) { return -EINVAL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_event_dyn_del(ev_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } #else return -EPERM; #endif #else return -EOPNOTSUPP; #endif } k_status_t csi_kernel_event_set(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags) { #if (RHINO_CONFIG_EVENT_FLAG > 0) if (ev_handle == NULL || ret_flags == NULL) { return -EINVAL; } kstat_t ret = krhino_event_set(ev_handle, flags, RHINO_OR); if (ret == RHINO_SUCCESS) { kevent_t *handle = (kevent_t *)ev_handle; *ret_flags = handle->flags; return 0; } else { return -EPERM; } #else return -EOPNOTSUPP; #endif } k_status_t csi_kernel_event_clear(k_event_handle_t ev_handle, uint32_t flags, uint32_t *ret_flags) { return -EOPNOTSUPP; } k_status_t csi_kernel_event_get(k_event_handle_t ev_handle, uint32_t *ret_flags) { #if (RHINO_CONFIG_EVENT_FLAG > 0) if (ev_handle == NULL || ret_flags == NULL) { return -EINVAL; } kevent_t *handle = (kevent_t *)ev_handle; *ret_flags = handle->flags; return 0; #else return -EOPNOTSUPP; #endif } k_status_t csi_kernel_event_wait(k_event_handle_t ev_handle, uint32_t flags, k_event_opt_t options, uint8_t clr_on_exit, uint32_t *actl_flags, int64_t timeout) { #if (RHINO_CONFIG_EVENT_FLAG > 0) if (ev_handle == NULL || actl_flags == NULL || ((clr_on_exit != 0) && (clr_on_exit != 1))) { return -EINVAL; } if (options == KEVENT_OPT_CLR_ANY || options == KEVENT_OPT_CLR_ALL) { return -EOPNOTSUPP; } uint8_t opt = 0; if (options == KEVENT_OPT_SET_ANY) { if (clr_on_exit == 1) { opt = RHINO_OR_CLEAR; } else { opt = RHINO_OR; } } else if (options == KEVENT_OPT_SET_ALL) { if (clr_on_exit == 1) { opt = RHINO_AND_CLEAR; } else { opt = RHINO_AND; } } tick_t t; if (timeout < 0) { t = RHINO_WAIT_FOREVER; } else { t = timeout; } kstat_t ret = krhino_event_get(ev_handle, flags, opt, actl_flags, t); if (ret == RHINO_SUCCESS) { return 0; } else if (ret == RHINO_BLK_TIMEOUT) { return -ETIMEDOUT; } else { return -EPERM; } #else return -EOPNOTSUPP; #endif } k_mutex_handle_t csi_kernel_mutex_new(void) { #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kmutex_t *mutex_handle; kstat_t ret = krhino_mutex_dyn_create((kmutex_t **)&mutex_handle, "UserMutex"); if (ret == RHINO_SUCCESS) { return mutex_handle; } else { return NULL; } #else return NULL; #endif } k_status_t csi_kernel_mutex_del(k_mutex_handle_t mutex_handle) { if (mutex_handle == NULL) { return -EINVAL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_mutex_dyn_del(mutex_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } #else return -EPERM; #endif } k_status_t csi_kernel_mutex_lock(k_mutex_handle_t mutex_handle, int64_t timeout) { if (mutex_handle == NULL) { return -EINVAL; } tick_t t; if (timeout < 0) { t = RHINO_WAIT_FOREVER; } else { t = timeout; } kstat_t ret = krhino_mutex_lock(mutex_handle, t); if (ret == RHINO_SUCCESS || ret == RHINO_MUTEX_OWNER_NESTED) { return 0; } else if (ret == RHINO_BLK_TIMEOUT) { return -ETIMEDOUT; } else { return -EPERM; } } k_status_t csi_kernel_mutex_unlock(k_mutex_handle_t mutex_handle) { if (mutex_handle == NULL) { return -EINVAL; } kstat_t ret = krhino_mutex_unlock(mutex_handle); if (ret == RHINO_SUCCESS || ret == RHINO_MUTEX_OWNER_NESTED) { return 0; } else { return -EPERM; } } k_task_handle_t csi_kernel_mutex_get_owner(k_mutex_handle_t mutex_handle) { if (mutex_handle == NULL) { return NULL; } kmutex_t *handle = (kmutex_t *)mutex_handle; return handle->mutex_task; } k_sem_handle_t csi_kernel_sem_new(int32_t max_count, int32_t initial_count) { if (max_count <= 0 || initial_count < 0) { return NULL; } if (max_count < initial_count) { return NULL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) ksem_t *sem_handle; kstat_t ret = krhino_sem_dyn_create((ksem_t **)&sem_handle, "UserSem", initial_count); if (ret == RHINO_SUCCESS) { return sem_handle; } else { return NULL; } #else return NULL; #endif } k_status_t csi_kernel_sem_del(k_sem_handle_t sem_handle) { if (sem_handle == NULL) { return -EINVAL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) kstat_t ret = krhino_sem_dyn_del(sem_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } #else return -EPERM; #endif } k_status_t csi_kernel_sem_wait(k_sem_handle_t sem_handle, int64_t timeout) { if (sem_handle == NULL) { return -EINVAL; } tick_t t; if (timeout < 0) { t = RHINO_WAIT_FOREVER; } else { t = timeout; } kstat_t ret = krhino_sem_take(sem_handle, t); if (ret == RHINO_SUCCESS) { return 0; } else if (ret == RHINO_BLK_TIMEOUT) { return -ETIMEDOUT; } else { return -EPERM; } } k_status_t csi_kernel_sem_post(k_sem_handle_t sem_handle) { if (sem_handle == NULL) { return -EINVAL; } kstat_t ret = krhino_sem_give(sem_handle); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } int32_t csi_kernel_sem_get_count(k_sem_handle_t sem_handle) { if (sem_handle == NULL) { return -EINVAL; } sem_count_t cnt; kstat_t ret = krhino_sem_count_get(sem_handle, &cnt); if (ret == RHINO_SUCCESS) { return (int32_t)cnt; } else { return -EPERM; } } k_mpool_handle_t csi_kernel_mpool_new(void *p_addr, int32_t block_count, int32_t block_size) { if (p_addr == NULL || block_count < 0 || block_size <= 0 || (block_size % 4 != 0)) { return NULL; } #if (RHINO_CONFIG_MM_BLK > 0) mblk_pool_t *handle = (mblk_pool_t *)malloc(sizeof(mblk_pool_t)); if (handle == NULL) { return NULL; } kstat_t ret = krhino_mblk_pool_init(handle, "UserMp", p_addr, block_count * block_size); if (ret == RHINO_SUCCESS) { return handle; } else { return NULL; } #else return NULL; #endif } k_status_t csi_kernel_mpool_del(k_mpool_handle_t mp_handle) { if (mp_handle == NULL) { return -EINVAL; } memset(mp_handle, 0, sizeof(mblk_pool_t)); free(mp_handle); return 0; } void *csi_kernel_mpool_alloc(k_mpool_handle_t mp_handle, uint32_t size) { if (mp_handle == NULL) { return NULL; } #if (RHINO_CONFIG_MM_BLK > 0) return krhino_mblk_alloc(mp_handle, size); #else return NULL; #endif } k_status_t csi_kernel_mpool_free(k_mpool_handle_t mp_handle, void *block) { if (mp_handle == NULL || block == NULL) { return -EINVAL; } #if (RHINO_CONFIG_MM_BLK > 0) kstat_t ret = krhino_mblk_free(mp_handle, block); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } #else return -EPERM; #endif } int32_t csi_kernel_mpool_get_count(k_mpool_handle_t mp_handle) { return 0; } uint32_t csi_kernel_mpool_get_capacity(k_mpool_handle_t mp_handle) { return 0; } uint32_t csi_kernel_mpool_get_block_size(k_mpool_handle_t mp_handle) { return 0; } typedef struct mq_adapter { kbuf_queue_t *buf_q; int32_t msg_size; int32_t msg_count; } mq_adapter_t; k_msgq_handle_t csi_kernel_msgq_new(int32_t msg_count, int32_t msg_size) { if (msg_count <= 0 || msg_size <= 0) { return NULL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) mq_adapter_t *handle = (mq_adapter_t *)malloc(sizeof(mq_adapter_t)); if (handle == NULL) { return NULL; } kstat_t ret = krhino_buf_queue_dyn_create(&(handle->buf_q), "UserMsgQ", msg_size * (msg_count + 1), msg_size); if (ret == RHINO_SUCCESS) { handle->msg_count = msg_count; handle->msg_size = msg_size; return (k_msgq_handle_t)handle; } else { free(handle); return NULL; } #else return NULL; #endif } k_status_t csi_kernel_msgq_del(k_msgq_handle_t mq_handle) { if (!mq_handle) { return -EINVAL; } #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) mq_adapter_t *handle = (mq_adapter_t *)mq_handle; kstat_t ret = krhino_buf_queue_dyn_del(handle->buf_q); if (ret == RHINO_SUCCESS) { free(mq_handle); return 0; } else { return -EPERM; } #else return -EPERM; #endif } k_status_t csi_kernel_msgq_put(k_msgq_handle_t mq_handle, const void *msg_ptr, uint8_t front_or_back, int64_t timeout) { k_status_t retval = -EPERM; if ((!mq_handle) || (msg_ptr == NULL) || ((front_or_back != 0) && (front_or_back != 1))) { return -EINVAL; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; if (front_or_back == 0) { kstat_t ret = krhino_buf_queue_send(handle->buf_q, (void *)msg_ptr, handle->msg_size); if (ret == RHINO_SUCCESS) { retval = 0 ; } else { retval = -EPERM; } } else if (front_or_back == 1) { kstat_t ret = krhino_buf_queue_send(handle->buf_q, (void *)msg_ptr, handle->msg_size); if (ret == RHINO_SUCCESS) { retval = 0; } else { retval = -EPERM; } } return retval; } k_status_t csi_kernel_msgq_get(k_msgq_handle_t mq_handle, void *msg_ptr, int64_t timeout) { if (mq_handle == NULL || msg_ptr == NULL) { return -EINVAL; } tick_t t; if (timeout < 0) { t = RHINO_WAIT_FOREVER; } else { t = timeout; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; size_t size; kstat_t ret = krhino_buf_queue_recv(handle->buf_q, t, msg_ptr, &size); if (ret == RHINO_SUCCESS) { return 0; } else if (ret == RHINO_BLK_TIMEOUT) { return -ETIMEDOUT; } else { return -EPERM; } } int32_t csi_kernel_msgq_get_count(k_msgq_handle_t mq_handle) { if (mq_handle == NULL) { return -EINVAL; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; kbuf_queue_info_t info; kstat_t ret = krhino_buf_queue_info_get(handle->buf_q, &info); if (ret == RHINO_SUCCESS) { int32_t cnt = info.cur_num; return cnt; } else { return -EPERM; } } uint32_t csi_kernel_msgq_get_capacity(k_msgq_handle_t mq_handle) { if (mq_handle == NULL) { return 0; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; return handle->msg_count; } uint32_t csi_kernel_msgq_get_msg_size(k_msgq_handle_t mq_handle) { if (mq_handle == NULL) { return 0; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; return handle->buf_q->max_msg_size; } k_status_t csi_kernel_msgq_flush(k_msgq_handle_t mq_handle) { if (mq_handle == NULL) { return -EINVAL; } mq_adapter_t *handle = (mq_adapter_t *)mq_handle; kstat_t ret = krhino_buf_queue_flush(handle->buf_q); if (ret == RHINO_SUCCESS) { return 0; } else { return -EPERM; } } void *csi_kernel_malloc(size_t size, void *caller) { void *ret; (void)caller; if (size < 1) { return NULL; } csi_kernel_sched_suspend(); ret = krhino_mm_alloc(size); csi_kernel_sched_resume(0); return ret; } void csi_kernel_free(void *ptr, void *caller) { (void)caller; csi_kernel_sched_suspend(); krhino_mm_free(ptr); csi_kernel_sched_resume(0); } void *csi_kernel_realloc(void *ptr, size_t size, void *caller) { void *new_ptr; (void)caller; new_ptr = krhino_mm_realloc(ptr, size); return new_ptr; } k_status_t csi_kernel_get_mminfo(int32_t *total, int32_t *used, int32_t *free, int32_t *peak) { *total = g_kmm_head->used_size + g_kmm_head->free_size; *used = g_kmm_head->used_size; *free = g_kmm_head->free_size; *peak = g_kmm_head->maxused_size; return 0; } k_status_t csi_kernel_mm_dump(void) { #if (RHINO_CONFIG_MM_DEBUG > 0u) dumpsys_mm_info_func(KMM_ERROR_UNLOCKED); #endif return 0; }
YifuLiu/AliOS-Things
hardware/board/c906/adapter/csi_rhino.c
C
apache-2.0
27,849
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "drv_usart.h" #include "soc.h" #include <csi_config.h> #include <csi_core.h> #include "pin.h" #include "aos/init.h" #include "k_config.h" #include "board.h" #include "aos/hal/uart.h" extern void aos_heap_set(); extern void krhino_tick_proc(void); extern usart_handle_t console_handle; extern void ioreuse_initial(void); extern int clock_timer_init(void); extern int clock_timer_start(void); void board_pre_init(void) { } /** * @general board init entry board_basic_init * @retval None */ void board_basic_init(void) { /*mm heap set*/ aos_heap_set(); } /** * @general board tick init entry board_tick_init * @retval None */ void board_tick_init(void) { } /** * @init the default uart init example. */ void board_stduart_init(void) { int32_t ret = 0; uart_dev_t uart0; uart0.port = CONSOLE_IDX; ret = hal_uart_init(&uart0); if (ret < 0) { return; } } /** * Enable DMA controller clock */ void board_dma_init(void) { } /** * @brief GPIO Initialization Function * @param None * @retval None */ void board_gpio_init(void) { } /** * @brief WIFI Initialization Function * @param None * @retval None */ void board_wifi_init(void) { } void board_network_init(void) { } void board_kinit_init(kinit_t* init_args) { return; } void board_flash_init(void) { } /** * @brief This function handles System tick timer. */ void systick_handler(void) { krhino_tick_proc(); }
YifuLiu/AliOS-Things
hardware/board/c906/config/board.c
C
apache-2.0
1,587
#ifndef __CSI_CONFIG_H__ #define __CSI_CONFIG_H__ #define CONFIG_ARCH_RV64 1 #define CONFIG_CPU_C910D 1 #define CONFIG_RV64_CORETIM 1 #define CONFIG_SYSTEM_SECURE 1 #define CONFIG_CHIP_SMARTH_RV64 1 #define CONFIG_BOARD_SMARTH_C910_EVB 1 #define CONFIG_BOARD_NAME_STR "smarth_c906_evb" #define CONFIG_KERNEL_RHINO 1 #define CONFIG_HAVE_VIC 1 #define CONFIG_ARCH_INTERRUPTSTACK 4096 #define CONFIG_NEWLIB_WRAP 1 #define CONFIG_USER_DEFINED_LD_DIR_STR "" #endif
YifuLiu/AliOS-Things
hardware/board/c906/config/csi_config.h
C
apache-2.0
460
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <k_api.h> #include <assert.h> #include <stdio.h> #include <sys/time.h> #if (RHINO_CONFIG_HW_COUNT > 0) void soc_hw_timer_init(void) { } hr_timer_t soc_hr_hw_cnt_get(void) { return 0; //return *(volatile uint64_t *)0xc0000120; } lr_timer_t soc_lr_hw_cnt_get(void) { return 0; } #endif /* RHINO_CONFIG_HW_COUNT */ #if (RHINO_CONFIG_MM_TLF > 0) extern size_t __heap_start; extern size_t __heap_end; /* __bss_end__ and _estack is set by linkscript(*.ld) heap and stack begins from __bss_end__ to _estack */ k_mm_region_t g_mm_region[1]; int g_region_num = 1; void aos_heap_set() { g_mm_region[0].start = (uint8_t*)&__heap_start; g_mm_region[0].len = ((uint8_t*)&__heap_end - (uint8_t*)&__heap_start) - RHINO_CONFIG_SYSTEM_STACK_SIZE; } #endif #if (RHINO_CONFIG_TASK_STACK_CUR_CHECK > 0) size_t soc_get_cur_sp() { size_t sp = 0; #if defined (__GNUC__)&&!defined(__CC_ARM) asm volatile( "csrr %0,sp\n" :"=r"(sp)); #endif return sp; } static void soc_print_stack() { void *cur, *end; int i=0; int *p; end = krhino_cur_task_get()->task_stack_base + krhino_cur_task_get()->stack_size; cur = (void *)soc_get_cur_sp(); p = (int*)cur; while(p < (int*)end) { if(i%4==0) { printf("\r\n%p:",(long)p); } printf("%p ", *p); i++; p++; } printf("\r\n"); return; } #endif void soc_err_proc(kstat_t err) { (void)err; printf("soc_err_proc %d \r\n", err); //krhino_backtrace_now(); #if (RHINO_CONFIG_TASK_STACK_CUR_CHECK > 0) //soc_print_stack(); #endif while(1); } krhino_err_proc_t g_err_proc = soc_err_proc;
YifuLiu/AliOS-Things
hardware/board/c906/config/k_config.c
C
apache-2.0
1,780
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #ifndef K_CONFIG_H #define K_CONFIG_H /* kernel feature conf */ #ifndef RHINO_CONFIG_SEM #define RHINO_CONFIG_SEM 1 #endif #ifndef RHINO_CONFIG_QUEUE #define RHINO_CONFIG_QUEUE 1 #endif #ifndef RHINO_CONFIG_TASK_SEM #define RHINO_CONFIG_TASK_SEM 1 #endif #ifndef RHINO_CONFIG_EVENT_FLAG #define RHINO_CONFIG_EVENT_FLAG 1 #endif #ifndef RHINO_CONFIG_TIMER #define RHINO_CONFIG_TIMER 1 #endif #ifndef RHINO_CONFIG_BUF_QUEUE #define RHINO_CONFIG_BUF_QUEUE 1 #endif #ifndef RHINO_CONFIG_MM_BLK #define RHINO_CONFIG_MM_BLK 1 #endif #ifndef RHINO_CONFIG_MM_DEBUG #define RHINO_CONFIG_MM_DEBUG 0 #endif #ifndef RHINO_CONFIG_MM_TLF #define RHINO_CONFIG_MM_TLF 1 #endif #ifndef RHINO_CONFIG_MM_BLK_SIZE #define RHINO_CONFIG_MM_BLK_SIZE 256 #endif #ifndef RHINO_CONFIG_MM_MINISIZEBIT #define RHINO_CONFIG_MM_MINISIZEBIT 6 #endif #ifndef RHINO_CONFIG_MM_MAXMSIZEBIT #define RHINO_CONFIG_MM_MAXMSIZEBIT 28 #endif #ifndef RHINO_CONFIG_MM_TLF_BLK_SIZE #define RHINO_CONFIG_MM_TLF_BLK_SIZE 1024 #endif #ifndef RHINO_CONFIG_MM_TRACE_LVL #define RHINO_CONFIG_MM_TRACE_LVL 4//8 #endif /* kernel task conf */ #ifndef RHINO_CONFIG_TASK_INFO #define RHINO_CONFIG_TASK_INFO 1 #endif #ifndef RHINO_CONFIG_TASK_DEL #define RHINO_CONFIG_TASK_DEL 1 #endif #ifndef RHINO_CONFIG_TASK_STACK_OVF_CHECK #define RHINO_CONFIG_TASK_STACK_OVF_CHECK 1 #endif #ifndef RHINO_CONFIG_SCHED_RR #define RHINO_CONFIG_SCHED_RR 1 #endif #ifndef RHINO_CONFIG_TIME_SLICE_DEFAULT #define RHINO_CONFIG_TIME_SLICE_DEFAULT 50 #endif #ifndef RHINO_CONFIG_PRI_MAX #define RHINO_CONFIG_PRI_MAX 62 #endif #ifndef RHINO_CONFIG_USER_PRI_MAX #define RHINO_CONFIG_USER_PRI_MAX (RHINO_CONFIG_PRI_MAX - 2) #endif /* kernel workqueue conf */ #ifndef RHINO_CONFIG_WORKQUEUE #define RHINO_CONFIG_WORKQUEUE 1 #endif #ifndef RHINO_CONFIG_WORKQUEUE_STACK_SIZE #define RHINO_CONFIG_WORKQUEUE_STACK_SIZE 512 #endif /* kernel mm_region conf */ #ifndef RHINO_CONFIG_MM_REGION_MUTEX #define RHINO_CONFIG_MM_REGION_MUTEX 1 #endif /* kernel timer&tick conf */ #ifndef RHINO_CONFIG_HW_COUNT #define RHINO_CONFIG_HW_COUNT 0 #endif #ifndef RHINO_CONFIG_TICKS_PER_SECOND #define RHINO_CONFIG_TICKS_PER_SECOND 100 #endif /*must reserve enough stack size for timer cb will consume*/ #ifndef RHINO_CONFIG_TIMER_TASK_STACK_SIZE #define RHINO_CONFIG_TIMER_TASK_STACK_SIZE 512 #endif #ifndef RHINO_CONFIG_TIMER_TASK_PRI #define RHINO_CONFIG_TIMER_TASK_PRI 5 #endif /* kernel dyn alloc conf */ #ifndef RHINO_CONFIG_KOBJ_DYN_ALLOC #define RHINO_CONFIG_KOBJ_DYN_ALLOC 1 #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) #ifndef RHINO_CONFIG_K_DYN_TASK_STACK #define RHINO_CONFIG_K_DYN_TASK_STACK 512 #endif #ifndef RHINO_CONFIG_K_DYN_MEM_TASK_PRI #define RHINO_CONFIG_K_DYN_MEM_TASK_PRI 6 #endif #endif /* kernel idle conf */ #ifndef RHINO_CONFIG_IDLE_TASK_STACK_SIZE #define RHINO_CONFIG_IDLE_TASK_STACK_SIZE 512 #endif /* kernel hook conf */ #ifndef RHINO_CONFIG_USER_HOOK #define RHINO_CONFIG_USER_HOOK 0 #endif #ifndef RHINO_CONFIG_CPU_NUM #define RHINO_CONFIG_CPU_NUM 1 #endif #ifndef RHINO_CONFIG_SYSTEM_STACK_SIZE #define RHINO_CONFIG_SYSTEM_STACK_SIZE 0x180 #endif /*task user info index start*/ #ifndef RHINO_CONFIG_TASK_INFO_NUM #define RHINO_CONFIG_TASK_INFO_NUM 5 #endif #ifndef PTHREAD_CONFIG_USER_INFO_POS #define PTHREAD_CONFIG_USER_INFO_POS 0 #endif #ifndef RHINO_TASK_HOOK_USER_INFO_POS #define RHINO_TASK_HOOK_USER_INFO_POS 1 #endif #ifndef RHINO_CLI_CONSOLE_USER_INFO_POS #define RHINO_CLI_CONSOLE_USER_INFO_POS 2 #endif #ifndef RHINO_ERRNO_USER_INFO_POS #define RHINO_ERRNO_USER_INFO_POS 3 #endif /*task user info index end*/ #endif /* K_CONFIG_H */
YifuLiu/AliOS-Things
hardware/board/c906/config/k_config.h
C
apache-2.0
4,098
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ void flash_partition_init(void) { }
YifuLiu/AliOS-Things
hardware/board/c906/config/partition_conf.c
C
apache-2.0
103
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file pin.h * @brief header File for pin definition * @version V1.0 * @date 02. June 2018 ******************************************************************************/ #ifndef _PIN_H_ #define _PIN_H_ #include <stdint.h> #include "pin_name.h" #include "pinmux.h" #ifdef __cplusplus extern "C" { #endif #define CLOCK_GETTIME_USE_TIMER_ID 0 #define UART_TXD0 1 #define UART_RXD0 2 #define CONSOLE_TXD PAD_UART0_SIN #define CONSOLE_RXD PAD_UART0_SOUT #define CONSOLE_IDX 0 /* example pin manager */ #define EXAMPLE_USART_IDX 0 #define EXAMPLE_PIN_USART_TX PAD_UART0_SIN #define EXAMPLE_PIN_USART_RX PAD_UART0_SOUT #define EXAMPLE_PIN_USART_TX_FUNC 0 #define EXAMPLE_PIN_USART_RX_FUNC 0 #define EXAMPLE_GPIO_PIN PA1 #define EXAMPLE_BOARD_GPIO_PIN_NAME "A1" #define EXAMPLE_GPIO_PIN_FUNC 0 /* tests pin manager */ #define TEST_USART_IDX 0 #define TEST_PIN_USART_TX PAD_UART0_SIN #define TEST_PIN_USART_RX PAD_UART0_SOUT #define TEST_PIN_USART_TX_FUNC 0 #define TEST_PIN_USART_RX_FUNC 0 #define TEST_GPIO_PIN PA0 #define TEST_BOARD_GPIO_PIN_NAME "A0" #define TEST_GPIO_PIN_FUNC 0 #define UART_TXD2 3 #define UART_RXD2 4 #define UART_TXD3 5 #define UART_RXD3 6 #define UART_PINs { {PA0, PA1},\ {PA10, PA11},\ {PA23, PA22},\ {PA26, PA27} } #define GPIO_EXAMPLE_PORT PORTB #define GPIO_EXAMPLE_PIN PA1 #define CTS_GPIO_TEST_PORT PORTA #define CTS_GPIO_TEST_PIN PA0 #define EXAMPLE_BOARD_GPIO_PIN_NAME "A1" #define CTS_BOARD_GPIO_PIN_NAME "A0" #define SENSOR_UART_DIR PA3 #ifdef __cplusplus } #endif #endif /* _PIN_H_ */
YifuLiu/AliOS-Things
hardware/board/c906/config/pin.h
C
apache-2.0
1,828
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file core_rv64.h * @brief CSI RV32 Core Peripheral Access Layer Header File * @version V1.0 * @date 01. Sep 2018 ******************************************************************************/ #ifndef __CORE_RV32_H_GENERIC #define __CORE_RV32_H_GENERIC #include <stdint.h> #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * CSI definitions ******************************************************************************/ /** \ingroup RV32 @{ */ #ifndef __RV64 #define __RV64 (0x01U) #endif /** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all */ #define __FPU_USED 0U #if defined ( __GNUC__ ) #if defined (__VFP_FP__) && !defined(__SOFTFP__) #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)" #endif #endif #ifdef __cplusplus } #endif #endif /* __CORE_RV32_H_GENERIC */ #ifndef __CSI_GENERIC #ifndef __CORE_RV32_H_DEPENDANT #define __CORE_RV32_H_DEPENDANT #ifdef __cplusplus extern "C" { #endif /* check device defines and use defaults */ #ifndef __RV64_REV #define __RV64_REV 0x0000U #endif #ifndef __VIC_PRIO_BITS #define __VIC_PRIO_BITS 2U #endif #ifndef __Vendor_SysTickConfig #define __Vendor_SysTickConfig 1U #endif #ifndef __MPU_PRESENT #define __MPU_PRESENT 1U #endif #ifndef __ICACHE_PRESENT #define __ICACHE_PRESENT 1U #endif #ifndef __DCACHE_PRESENT #define __DCACHE_PRESENT 1U #endif #ifndef __L2CACHE_PRESENT #define __L2CACHE_PRESENT 1U #endif #include <csi_rv64_gcc.h> /* IO definitions (access restrictions to peripheral registers) */ /** \defgroup CSI_glob_defs CSI Global Defines <strong>IO Type Qualifiers</strong> are used \li to specify the access to peripheral variables. \li for automatic generation of peripheral register debug information. */ #ifdef __cplusplus #define __I volatile /*!< Defines 'read only' permissions */ #else #define __I volatile const /*!< Defines 'read only' permissions */ #endif #define __O volatile /*!< Defines 'write only' permissions */ #define __IO volatile /*!< Defines 'read / write' permissions */ /* following defines should be used for structure members */ #define __IM volatile const /*! Defines 'read only' structure member permissions */ #define __OM volatile /*! Defines 'write only' structure member permissions */ #define __IOM volatile /*! Defines 'read / write' structure member permissions */ /*@} end of group C910 */ /******************************************************************************* * Register Abstraction Core Register contain: - Core Register - Core CLINT Register ******************************************************************************/ /** \defgroup CSI_core_register Defines and Type Definitions \brief Type definitions and defines for CK80X processor based devices. */ /** \ingroup CSI_core_register \defgroup CSI_CORE Status and Control Registers \brief Core Register type definitions. @{ */ /** \ingroup CSI_core_register \defgroup CSI_CLINT Core-Local Interrupt Controller (CLINT) \brief Type definitions for the CLINT Registers @{ */ /** \brief Access to the structure of a vector interrupt controller. */ typedef struct { uint32_t RESERVED0; /*!< Offset: 0x000 (R/W) CLINT configure register */ __IOM uint32_t PLIC_PRIO[1023]; __IOM uint32_t PLIC_IP[32]; uint32_t RESERVED1[3972/4 - 1]; __IOM uint32_t PLIC_H0_MIE[32]; __IOM uint32_t PLIC_H0_SIE[32]; __IOM uint32_t PLIC_H1_MIE[32]; __IOM uint32_t PLIC_H1_SIE[32]; __IOM uint32_t PLIC_H2_MIE[32]; __IOM uint32_t PLIC_H2_SIE[32]; __IOM uint32_t PLIC_H3_MIE[32]; __IOM uint32_t PLIC_H3_SIE[32]; uint32_t RESERVED2[(0x01FFFFC-0x00023FC)/4 - 1]; __IOM uint32_t PLIC_PER; __IOM uint32_t PLIC_H0_MTH; __IOM uint32_t PLIC_H0_MCLAIM; uint32_t RESERVED3[0xFFC/4 - 1]; __IOM uint32_t PLIC_H0_STH; __IOM uint32_t PLIC_H0_SCLAIM; uint32_t RESERVED4[0xFFC/4 - 1]; __IOM uint32_t PLIC_H1_MTH; __IOM uint32_t PLIC_H1_MCLAIM; uint32_t RESERVED5[0xFFC/4 - 1]; __IOM uint32_t PLIC_H1_STH; __IOM uint32_t PLIC_H1_SCLAIM; uint32_t RESERVED6[0xFFC/4 - 1]; __IOM uint32_t PLIC_H2_MTH; __IOM uint32_t PLIC_H2_MCLAIM; uint32_t RESERVED7[0xFFC/4 - 1]; __IOM uint32_t PLIC_H2_STH; __IOM uint32_t PLIC_H2_SCLAIM; uint32_t RESERVED8[0xFFC/4 - 1]; __IOM uint32_t PLIC_H3_MTH; __IOM uint32_t PLIC_H3_MCLAIM; uint32_t RESERVED9[0xFFC/4 - 1]; __IOM uint32_t PLIC_H3_STH; __IOM uint32_t PLIC_H3_SCLAIM; uint32_t RESERVED10[0xFFC/4 - 1]; } PLIC_Type; /** \ingroup CSI_core_register \defgroup CSI_PMP Physical Memory Protection (PMP) \brief Type definitions for the PMP Registers @{ */ #define PMP_PMPCFG_R_Pos 0U /*!< PMP PMPCFG: R Position */ #define PMP_PMPCFG_R_Msk (0x1UL << PMP_PMPCFG_R_Pos) /*!< PMP PMPCFG: R Mask */ #define PMP_PMPCFG_W_Pos 1U /*!< PMP PMPCFG: W Position */ #define PMP_PMPCFG_W_Msk (0x1UL << PMP_PMPCFG_W_Pos) /*!< PMP PMPCFG: W Mask */ #define PMP_PMPCFG_X_Pos 2U /*!< PMP PMPCFG: X Position */ #define PMP_PMPCFG_X_Msk (0x1UL << PMP_PMPCFG_X_Pos) /*!< PMP PMPCFG: X Mask */ #define PMP_PMPCFG_A_Pos 3U /*!< PMP PMPCFG: A Position */ #define PMP_PMPCFG_A_Msk (0x3UL << PMP_PMPCFG_A_Pos) /*!< PMP PMPCFG: A Mask */ #define PMP_PMPCFG_L_Pos 7U /*!< PMP PMPCFG: L Position */ #define PMP_PMPCFG_L_Msk (0x1UL << PMP_PMPCFG_L_Pos) /*!< PMP PMPCFG: L Mask */ typedef enum { REGION_SIZE_4B = -1, REGION_SIZE_8B = 0, REGION_SIZE_16B = 1, REGION_SIZE_32B = 2, REGION_SIZE_64B = 3, REGION_SIZE_128B = 4, REGION_SIZE_256B = 5, REGION_SIZE_512B = 6, REGION_SIZE_1KB = 7, REGION_SIZE_2KB = 8, REGION_SIZE_4KB = 9, REGION_SIZE_8KB = 10, REGION_SIZE_16KB = 11, REGION_SIZE_32KB = 12, REGION_SIZE_64KB = 13, REGION_SIZE_128KB = 14, REGION_SIZE_256KB = 15, REGION_SIZE_512KB = 16, REGION_SIZE_1MB = 17, REGION_SIZE_2MB = 18, REGION_SIZE_4MB = 19, REGION_SIZE_8MB = 20, REGION_SIZE_16MB = 21, REGION_SIZE_32MB = 22, REGION_SIZE_64MB = 23, REGION_SIZE_128MB = 24, REGION_SIZE_256MB = 25, REGION_SIZE_512MB = 26, REGION_SIZE_1GB = 27, REGION_SIZE_2GB = 28, REGION_SIZE_4GB = 29, REGION_SIZE_8GB = 30, REGION_SIZE_16GB = 31 } region_size_e; typedef enum { ADDRESS_MATCHING_TOR = 1, ADDRESS_MATCHING_NAPOT = 3 } address_matching_e; typedef struct { uint32_t r: 1; /* readable enable */ uint32_t w: 1; /* writeable enable */ uint32_t x: 1; /* execable enable */ address_matching_e a: 2; /* address matching mode */ uint32_t reserved: 2; /* reserved */ uint32_t l: 1; /* lock enable */ } mpu_region_attr_t; /*@} end of group CSI_PMP */ /* CACHE Register Definitions */ #define CACHE_MHCR_WBR_Pos 8U /*!< CACHE MHCR: WBR Position */ #define CACHE_MHCR_WBR_Msk (0x1UL << CACHE_MHCR_WBR_Pos) /*!< CACHE MHCR: WBR Mask */ #define CACHE_MHCR_IBPE_Pos 7U /*!< CACHE MHCR: IBPE Position */ #define CACHE_MHCR_IBPE_Msk (0x1UL << CACHE_MHCR_IBPE_Pos) /*!< CACHE MHCR: IBPE Mask */ #define CACHE_MHCR_L0BTB_Pos 6U /*!< CACHE MHCR: L0BTB Position */ #define CACHE_MHCR_L0BTB_Msk (0x1UL << CACHE_MHCR_L0BTB_Pos) /*!< CACHE MHCR: BTB Mask */ #define CACHE_MHCR_BPE_Pos 5U /*!< CACHE MHCR: BPE Position */ #define CACHE_MHCR_BPE_Msk (0x1UL << CACHE_MHCR_BPE_Pos) /*!< CACHE MHCR: BPE Mask */ #define CACHE_MHCR_RS_Pos 4U /*!< CACHE MHCR: RS Position */ #define CACHE_MHCR_RS_Msk (0x1UL << CACHE_MHCR_RS_Pos) /*!< CACHE MHCR: RS Mask */ #define CACHE_MHCR_WB_Pos 3U /*!< CACHE MHCR: WB Position */ #define CACHE_MHCR_WB_Msk (0x1UL << CACHE_MHCR_WB_Pos) /*!< CACHE MHCR: WB Mask */ #define CACHE_MHCR_WA_Pos 2U /*!< CACHE MHCR: WA Position */ #define CACHE_MHCR_WA_Msk (0x1UL << CACHE_MHCR_WA_Pos) /*!< CACHE MHCR: WA Mask */ #define CACHE_MHCR_DE_Pos 1U /*!< CACHE MHCR: DE Position */ #define CACHE_MHCR_DE_Msk (0x1UL << CACHE_MHCR_DE_Pos) /*!< CACHE MHCR: DE Mask */ #define CACHE_MHCR_IE_Pos 0U /*!< CACHE MHCR: IE Position */ #define CACHE_MHCR_IE_Msk (0x1UL << CACHE_MHCR_IE_Pos) /*!< CACHE MHCR: IE Mask */ #define CACHE_INV_ADDR_Pos 5U #define CACHE_INV_ADDR_Msk (0xFFFFFFFFUL << CACHE_INV_ADDR_Pos) /*@} end of group CSI_CACHE */ /** \ingroup CSI_core_register \defgroup CSI_SysTick System Tick Timer (CORET) \brief Type definitions for the System Timer Registers. @{ */ /** \brief The data structure of the access system timer. */ typedef struct { __IOM uint32_t MSIP0; __IOM uint32_t MSIP1; __IOM uint32_t MSIP2; __IOM uint32_t MSIP3; uint32_t RESERVED0[(0x4004000-0x400000C)/4 - 1]; __IOM uint32_t MTIMECMPL0; __IOM uint32_t MTIMECMPH0; __IOM uint32_t MTIMECMPL1; __IOM uint32_t MTIMECMPH1; __IOM uint32_t MTIMECMPL2; __IOM uint32_t MTIMECMPH2; __IOM uint32_t MTIMECMPL3; __IOM uint32_t MTIMECMPH3; uint32_t RESERVED1[(0x400C000-0x400401C)/4 - 1]; __IOM uint32_t SSIP0; __IOM uint32_t SSIP1; __IOM uint32_t SSIP2; __IOM uint32_t SSIP3; uint32_t RESERVED2[(0x400D000-0x400C00C)/4 - 1]; __IOM uint32_t STIMECMPL0; __IOM uint32_t STIMECMPH0; __IOM uint32_t STIMECMPL1; __IOM uint32_t STIMECMPH1; __IOM uint32_t STIMECMPL2; __IOM uint32_t STIMECMPH2; __IOM uint32_t STIMECMPL3; __IOM uint32_t STIMECMPH3; } CORET_Type; /*@} end of group CSI_SysTick */ /** \ingroup CSI_core_register \defgroup CSI_core_bitfield Core register bit field macros \brief Macros for use with bit field definitions (xxx_Pos, xxx_Msk). @{ */ /** \brief Mask and shift a bit field value for use in a register bit range. \param[in] field Name of the register bit field. \param[in] value Value of the bit field. \return Masked and shifted value. */ #define _VAL2FLD(field, value) ((value << field ## _Pos) & field ## _Msk) /** \brief Mask and shift a register value to extract a bit filed value. \param[in] field Name of the register bit field. \param[in] value Value of register. \return Masked and shifted bit field value. */ #define _FLD2VAL(field, value) ((value & field ## _Msk) >> field ## _Pos) /*@} end of group CSI_core_bitfield */ /** \ingroup CSI_core_register \defgroup CSI_core_base Core Definitions \brief Definitions for base addresses, unions, and structures. @{ */ #define CORET_BASE (PLIC_BASE + 0x4000000UL) /*!< CORET Base Address */ #define PLIC_BASE (0x4000000000UL) /*!< PLIC Base Address */ #define CORET ((CORET_Type *) CORET_BASE ) /*!< SysTick configuration struct */ #define CLINT ((CLINT_Type *) CLINT_BASE ) /*!< CLINT configuration struct */ #define PLIC ((PLIC_Type *) PLIC_BASE ) /*!< PLIC configuration struct */ /*@} */ /******************************************************************************* * Hardware Abstraction Layer Core Function Interface contains: - Core VIC Functions - Core CORET Functions - Core Register Access Functions ******************************************************************************/ /** \defgroup CSI_Core_FunctionInterface Functions and Instructions Reference */ /* ########################## VIC functions #################################### */ /** \ingroup CSI_Core_FunctionInterface \defgroup CSI_Core_VICFunctions VIC Functions \brief Functions that manage interrupts and exceptions via the VIC. @{ */ /* The following MACROS handle generation of the register offset and byte masks */ #define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL) #define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 5UL) ) #define _IP2_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) ) /** \brief Enable External Interrupt \details Enable a device-specific interrupt in the VIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_enable_irq(int32_t IRQn) { PLIC->PLIC_H0_MIE[IRQn/32] = PLIC->PLIC_H0_MIE[IRQn/32] | (0x1 << (IRQn%32)); } /** \brief Disable External Interrupt \details Disable a device-specific interrupt in the VIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_disable_irq(int32_t IRQn) { PLIC->PLIC_H0_MIE[IRQn/32] = PLIC->PLIC_H0_MIE[IRQn/32] & (~(0x1 << (IRQn%32))); } /** \brief Enable External Secure Interrupt \details Enable a secure device-specific interrupt in the VIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_enable_sirq(int32_t IRQn) { csi_vic_enable_irq(IRQn); } /** \brief Disable External Secure Interrupt \details Disable a secure device-specific interrupt in the VIC interrupt controller. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_disable_sirq(int32_t IRQn) { csi_vic_disable_irq(IRQn); } /** \brief Check Interrupt is Enabled or not \details Read the enabled register in the VIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not enabled. \return 1 Interrupt status is enabled. */ __STATIC_INLINE uint32_t csi_vic_get_enabled_irq(int32_t IRQn) { return (uint32_t)((PLIC->PLIC_H0_MIE[IRQn/32] >> IRQn%32) & 0x1); } /** \brief Check Interrupt is Pending or not \details Read the pending register in the VIC and returns the pending bit for the specified interrupt. \param [in] IRQn Interrupt number. \return 0 Interrupt status is not pending. \return 1 Interrupt status is pending. */ __STATIC_INLINE uint32_t csi_vic_get_pending_irq(int32_t IRQn) { return (uint32_t)((PLIC->PLIC_IP[IRQn/32] >> IRQn%32) & 0x1); } /** \brief Set Pending Interrupt \details Set the pending bit of an external interrupt. \param [in] IRQn Interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_set_pending_irq(int32_t IRQn) { PLIC->PLIC_IP[IRQn/32] = PLIC->PLIC_IP[IRQn/32] | (0x1 << (IRQn%32)); } /** \brief Clear Pending Interrupt \details Clear the pending bit of an external interrupt. \param [in] IRQn External interrupt number. Value cannot be negative. */ __STATIC_INLINE void csi_vic_clear_pending_irq(int32_t IRQn) { PLIC->PLIC_H0_SCLAIM = IRQn; } /** \brief Set Interrupt Priority \details Set the priority of an interrupt. \note The priority cannot be set for every core interrupt. \param [in] IRQn Interrupt number. \param [in] priority Priority to set. */ __STATIC_INLINE void csi_vic_set_prio(int32_t IRQn, uint32_t priority) { PLIC->PLIC_PRIO[IRQn] = priority; } /** \brief Get Interrupt Priority \details Read the priority of an interrupt. The interrupt number can be positive to specify an external (device specific) interrupt, or negative to specify an internal (core) interrupt. \param [in] IRQn Interrupt number. \return Interrupt Priority. Value is aligned automatically to the implemented priority bits of the microcontroller. */ __STATIC_INLINE uint32_t csi_vic_get_prio(int32_t IRQn) { uint32_t prio = PLIC->PLIC_PRIO[IRQn]; return prio; } /** \brief Set interrupt handler \details Set the interrupt handler according to the interrupt num, the handler will be filled in irq vectors. \param [in] IRQn Interrupt number. \param [in] handler Interrupt handler. */ __STATIC_INLINE void csi_vic_set_vector(int32_t IRQn, uint64_t handler) { if (IRQn >= 0 && IRQn < 1024) { uint64_t *vectors = (uint64_t *)__get_MTVT(); vectors[IRQn] = handler; } } /** \brief Get interrupt handler \details Get the address of interrupt handler function. \param [in] IRQn Interrupt number. */ __STATIC_INLINE uint32_t csi_vic_get_vector(int32_t IRQn) { if (IRQn >= 0 && IRQn < 1024) { uint64_t *vectors = (uint64_t *)__get_MTVT(); return (uint32_t)vectors[IRQn]; } return 0; } /*@} end of CSI_Core_VICFunctions */ /* ########################## PMP functions #################################### */ /** \ingroup CSI_Core_FunctionInterface \defgroup CSI_Core_PMPFunctions PMP Functions \brief Functions that manage interrupts and exceptions via the VIC. @{ */ /** \brief configure memory protected region. \details \param [in] idx memory protected region (0, 1, 2, ..., 15). \param [in] base_addr base address must be aligned with page size. \param [in] size \ref region_size_e. memory protected region size. \param [in] attr \ref region_size_t. memory protected region attribute. \param [in] enable enable or disable memory protected region. */ __STATIC_INLINE void csi_mpu_config_region(uint32_t idx, uint32_t base_addr, region_size_e size, mpu_region_attr_t attr, uint32_t enable) { uint8_t pmpxcfg = 0; uint32_t addr = 0; if (idx > 15) { return; } if (!enable) { attr.a = 0; } if (attr.a == ADDRESS_MATCHING_TOR) { addr = base_addr >> 2; } else { if (size == REGION_SIZE_4B) { addr = base_addr >> 2; attr.a = 2; } else { addr = ((base_addr >> 2) & (0xFFFFFFFFU - ((1 << (size + 1)) - 1))) | ((1 << size) - 1); } } __set_PMPADDRx(idx, addr); pmpxcfg |= (attr.r << PMP_PMPCFG_R_Pos) | (attr.w << PMP_PMPCFG_W_Pos) | (attr.x << PMP_PMPCFG_X_Pos) | (attr.a << PMP_PMPCFG_A_Pos) | (attr.l << PMP_PMPCFG_L_Pos); __set_PMPxCFG(idx, pmpxcfg); } /** \brief disable mpu region by idx. \details \param [in] idx memory protected region (0, 1, 2, ..., 15). */ __STATIC_INLINE void csi_mpu_disable_region(uint32_t idx) { __set_PMPxCFG(idx, __get_PMPxCFG(idx) & (~PMP_PMPCFG_A_Msk)); } /*@} end of CSI_Core_PMPFunctions */ /* ################################## SysTick function ############################################ */ /** \ingroup CSI_Core_FunctionInterface \defgroup CSI_Core_SysTickFunctions SysTick Functions \brief Functions that configure the System. @{ */ /** \brief CORE timer Configuration \details Initializes the System Timer and its interrupt, and starts the System Tick Timer. Counter is in free running mode to generate periodic interrupts. \param [in] ticks Number of ticks between two interrupts. \param [in] IRQn core timer Interrupt number. \return 0 Function succeeded. \return 1 Function failed. \note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b> must contain a vendor-specific implementation of this function. */ __STATIC_INLINE uint32_t csi_coret_config(uint32_t ticks, int32_t IRQn) { uint64_t value = (((uint64_t)CORET->MTIMECMPH0) << 32) + (uint64_t)CORET->MTIMECMPL0; value = value + (uint64_t)ticks; CORET->MTIMECMPH0 = (uint32_t)(value >> 32); CORET->MTIMECMPL0 = (uint32_t)value; return (0UL); } /** \brief get CORE timer reload value \return CORE timer counter value. */ __STATIC_INLINE uint64_t csi_coret_get_load(void) { uint64_t value = (((uint64_t)CORET->MTIMECMPH0) << 32) + (uint64_t)CORET->MTIMECMPL0; return value; } /** \brief get CORE timer reload high value \return CORE timer counter value. */ __STATIC_INLINE uint32_t csi_coret_get_loadh(void) { uint64_t value = (((uint64_t)CORET->MTIMECMPH0) << 32) + (uint64_t)CORET->MTIMECMPL0; return (value >> 32) & 0xFFFFFFFF; } /** \brief get CORE timer counter value \return CORE timer counter value. */ __STATIC_INLINE uint64_t csi_coret_get_value(void) { uint64_t result; __ASM volatile("csrr %0, 0xc01" : "=r"(result)); return result; } /** \brief get CORE timer counter high value \return CORE timer counter value. */ __STATIC_INLINE uint32_t csi_coret_get_valueh(void) { uint64_t result; __ASM volatile("csrr %0, time" : "=r"(result)); return (result >> 32) & 0xFFFFFFFF; } /*@} end of CSI_core_DebugFunctions */ /* ########################## Cache functions #################################### */ /** \ingroup CSI_Core_FunctionInterface \defgroup CSI_Core_CacheFunctions Cache Functions \brief Functions that configure Instruction and Data cache. @{ */ /** \brief Enable I-Cache \details Turns on I-Cache */ __STATIC_INLINE void csi_icache_enable (void) { #if (__ICACHE_PRESENT == 1U) uint32_t cache; __DSB(); __ISB(); __ICACHE_IALL(); cache = __get_MHCR(); cache |= CACHE_MHCR_IE_Msk; __set_MHCR(cache); __DSB(); __ISB(); #endif } /** \brief Disable I-Cache \details Turns off I-Cache */ __STATIC_INLINE void csi_icache_disable (void) { #if (__ICACHE_PRESENT == 1U) uint32_t cache; __DSB(); __ISB(); cache = __get_MHCR(); cache &= ~CACHE_MHCR_IE_Msk; /* disable icache */ __set_MHCR(cache); __ICACHE_IALL(); /* invalidate all icache */ __DSB(); __ISB(); #endif } /** \brief Invalidate I-Cache \details Invalidates I-Cache */ __STATIC_INLINE void csi_icache_invalid (void) { #if (__ICACHE_PRESENT == 1U) __DSB(); __ISB(); __ICACHE_IALL(); /* invalidate all icache */ __DSB(); __ISB(); #endif } /** \brief Enable D-Cache \details Turns on D-Cache \note I-Cache also turns on. */ __STATIC_INLINE void csi_dcache_enable (void) { #if (__DCACHE_PRESENT == 1U) uint32_t cache; __DSB(); __ISB(); __DCACHE_IALL(); /* invalidate all dcache */ cache = __get_MHCR(); cache |= (CACHE_MHCR_DE_Msk | CACHE_MHCR_WB_Msk | CACHE_MHCR_WA_Msk | CACHE_MHCR_RS_Msk | CACHE_MHCR_BPE_Msk | CACHE_MHCR_L0BTB_Msk | CACHE_MHCR_IBPE_Msk | CACHE_MHCR_WBR_Msk); /* enable all Cache */ __set_MHCR(cache); __DSB(); __ISB(); #endif } /** \brief Disable D-Cache \details Turns off D-Cache \note I-Cache also turns off. */ __STATIC_INLINE void csi_dcache_disable (void) { #if (__DCACHE_PRESENT == 1U) uint32_t cache; __DSB(); __ISB(); cache = __get_MHCR(); cache &= ~(uint32_t)CACHE_MHCR_DE_Msk; /* disable all Cache */ __set_MHCR(cache); __DCACHE_IALL(); /* invalidate all Cache */ __DSB(); __ISB(); #endif } /** \brief Invalidate D-Cache \details Invalidates D-Cache \note I-Cache also invalid */ __STATIC_INLINE void csi_dcache_invalid (void) { #if (__DCACHE_PRESENT == 1U) __DSB(); __ISB(); __DCACHE_IALL(); /* invalidate all Cache */ __DSB(); __ISB(); #endif } /** \brief Clean D-Cache \details Cleans D-Cache \note I-Cache also cleans */ __STATIC_INLINE void csi_dcache_clean (void) { #if (__DCACHE_PRESENT == 1U) __DSB(); __ISB(); __DCACHE_CALL(); /* clean all Cache */ __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate D-Cache \details Cleans and Invalidates D-Cache \note I-Cache also flush. */ __STATIC_INLINE void csi_dcache_clean_invalid (void) { #if (__DCACHE_PRESENT == 1U) __DSB(); __ISB(); __DCACHE_CIALL(); /* clean and inv all Cache */ __DSB(); __ISB(); #endif } /** \brief Invalidate L2-Cache \details Invalidates L2-Cache \note */ __STATIC_INLINE void csi_l2cache_invalid (void) { #if (__L2CACHE_PRESENT == 1U) __DSB(); __ISB(); __L2CACHE_IALL(); /* invalidate l2 Cache */ __DSB(); __ISB(); #endif } /** \brief Clean L2-Cache \details Cleans L2-Cache \note */ __STATIC_INLINE void csi_l2cache_clean (void) { #if (__L2CACHE_PRESENT == 1U) __DSB(); __ISB(); __L2CACHE_CALL(); /* clean l2 Cache */ __DSB(); __ISB(); #endif } /** \brief Clean & Invalidate L2-Cache \details Cleans and Invalidates L2-Cache \note */ __STATIC_INLINE void csi_l2cache_clean_invalid (void) { #if (__L2CACHE_PRESENT == 1U) __DSB(); __ISB(); __L2CACHE_CIALL(); /* clean and inv l2 Cache */ __DSB(); __ISB(); #endif } /** \brief D-Cache Invalidate by address \details Invalidates D-Cache for the given address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void csi_dcache_invalid_range (uint64_t *addr, int64_t dsize) { #if (__DCACHE_PRESENT == 1U) int64_t op_size = dsize + (uint64_t)addr % 64; uint64_t op_addr = (uint64_t)addr; int64_t linesize = 64; __DSB(); while (op_size > 0) { __DCACHE_IPA(op_addr); op_addr += linesize; op_size -= linesize; } __DSB(); __ISB(); #endif } /** \brief D-Cache Clean by address \details Cleans D-Cache for the given address \param[in] addr address (aligned to 32-byte boundary) \param[in] dsize size of memory block (in number of bytes) */ __STATIC_INLINE void csi_dcache_clean_range (uint64_t *addr, int64_t dsize) { #if (__DCACHE_PRESENT == 1) int64_t op_size = dsize + (uint64_t)addr % 64; uint64_t op_addr = (uint64_t) addr & CACHE_INV_ADDR_Msk; int64_t linesize = 64; __DSB(); while (op_size > 0) { __DCACHE_CPA(op_addr); op_addr += linesize; op_size -= linesize; } __DSB(); __ISB(); #endif } /** \brief D-Cache Clean and Invalidate by address \details Cleans and invalidates D_Cache for the given address \param[in] addr address (aligned to 16-byte boundary) \param[in] dsize size of memory block (aligned to 16-byte boundary) */ __STATIC_INLINE void csi_dcache_clean_invalid_range (uint64_t *addr, int64_t dsize) { #if (__DCACHE_PRESENT == 1U) int64_t op_size = dsize + (uint64_t)addr % 64; uint64_t op_addr = (uint64_t) addr; int64_t linesize = 64; __DSB(); while (op_size > 0) { __DCACHE_CIPA(op_addr); op_addr += linesize; op_size -= linesize; } __DSB(); __ISB(); #endif } /** \brief setup cacheable range Cache \details setup Cache range */ __STATIC_INLINE void csi_cache_set_range (uint64_t index, uint64_t baseAddr, uint64_t size, uint64_t enable) { ; } /** \brief Enable cache profile \details Turns on Cache profile */ __STATIC_INLINE void csi_cache_enable_profile (void) { ; } /** \brief Disable cache profile \details Turns off Cache profile */ __STATIC_INLINE void csi_cache_disable_profile (void) { ; } /** \brief Reset cache profile \details Reset Cache profile */ __STATIC_INLINE void csi_cache_reset_profile (void) { ; } /** \brief cache access times \details Cache access times \note every 256 access add 1. \return cache access times, actual times should be multiplied by 256 */ __STATIC_INLINE uint64_t csi_cache_get_access_time (void) { return 0; } /** \brief cache miss times \details Cache miss times \note every 256 miss add 1. \return cache miss times, actual times should be multiplied by 256 */ __STATIC_INLINE uint64_t csi_cache_get_miss_time (void) { return 0; } /*@} end of CSI_Core_CacheFunctions */ /*@} end of CSI_core_DebugFunctions */ /* ################################## IRQ Functions ############################################ */ /** \brief Save the Irq context \details save the psr result before disable irq. */ __STATIC_INLINE uint64_t csi_irq_save(void) { uint64_t result; result = __get_MSTATUS(); __disable_irq(); return(result); } /** \brief Restore the Irq context \details restore saved primask state. \param [in] irq_state psr irq state. */ __STATIC_INLINE void csi_irq_restore(uint64_t irq_state) { __set_MSTATUS(irq_state); } /*@} end of IRQ Functions */ #ifdef __cplusplus } #endif #endif /* __CORE_RV32_H_DEPENDANT */ #endif /* __CSI_GENERIC */
YifuLiu/AliOS-Things
hardware/board/c906/csi_core/include/core_rv64.h
C
apache-2.0
30,846
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file csi_core.h * @brief CSI Core Layer Header File * @version V1.0 * @date 02. June 2017 ******************************************************************************/ #ifndef _CORE_H_ #define _CORE_H_ #include <stdint.h> #if defined(__CK801__) || defined(__E801__) #include <core_801.h> #elif defined(__CK802__) || defined(__E802__) || defined(__E802T__) || defined(__S802__) || defined(__S802T__) #include <core_802.h> #elif defined(__CK804__) || defined(__E804D__) || defined(__E804DT__) || defined(__E804F__) || defined(__E804FT__) || defined (__E804DF__) || defined(__E804DFT__) #include <core_804.h> #elif defined(__CK803__) || defined(__E803__) || defined(__E803T__) || defined(__S803__) || defined(__S803T__) #include <core_803.h> #elif defined(__CK805__) || defined(__I805__) || defined(__I805F__) #include <core_805.h> #elif defined(__CK610__) #include <core_ck610.h> #elif defined(__CK810__) || defined(__C810__) || defined(__C810T__) || defined(__C810V__) || defined(__C810VT__) #include <core_810.h> #elif defined(__CK807__) || defined(__C807__) || defined(__C807F__) || defined(__C807FV__) || defined(__R807__) #include <core_807.h> #elif defined(__riscv) && defined(CONFIG_CSKY_CORETIM) #include <core_rv32_old.h> #elif defined(__riscv) #include <core_rv64.h> #endif #ifdef __riscv #include <csi_rv64_gcc.h> #else #include <csi_gcc.h> #endif #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif /* _CORE_H_ */
YifuLiu/AliOS-Things
hardware/board/c906/csi_core/include/csi_core.h
C
apache-2.0
1,622
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited * * License-Identifier: Apache-2.0 * * 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. * */ /****************************************************************************** * @file csi_rv64_gcc.h * @brief CSI Header File for GCC. * @version V1.0 * @date 01. Sep 2018 ******************************************************************************/ #ifndef _CSI_RV32_GCC_H_ #define _CSI_RV32_GCC_H_ #include <stdlib.h> #ifndef __ASM #define __ASM __asm /*!< asm keyword for GNU Compiler */ #endif #ifndef __INLINE #define __INLINE inline /*!< inline keyword for GNU Compiler */ #endif #ifndef __ALWAYS_STATIC_INLINE #define __ALWAYS_STATIC_INLINE __attribute__((always_inline)) static inline #endif #ifndef __STATIC_INLINE #define __STATIC_INLINE static inline #endif /* ########################### Core Function Access ########################### */ /** \ingroup CSI_Core_FunctionInterface \defgroup CSI_Core_RegAccFunctions CSI Core Register Access Functions @{ */ /** \brief Enable IRQ Interrupts \details Enables IRQ interrupts by setting the IE-bit in the PSR. Can only be executed in Privileged modes. */ __ALWAYS_STATIC_INLINE void __enable_irq(void) { __ASM volatile("csrs mstatus, 8"); } /** \brief Disable IRQ Interrupts \details Disables IRQ interrupts by clearing the IE-bit in the PSR. Can only be executed in Privileged modes. */ __ALWAYS_STATIC_INLINE void __disable_irq(void) { __ASM volatile("csrc mstatus, 8"); } /** \brief Get MXSTATUS \details Returns the content of the MXSTATUS Register. \return MXSTATUS Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MXSTATUS(void) { uint64_t result; __ASM volatile("csrr %0, mxstatus" : "=r"(result)); return (result); } /** \brief Set MEPC \details Writes the given value to the MEPC Register. \param [in] mstatus MEPC Register value to set */ __ALWAYS_STATIC_INLINE void __set_MEPC(uint64_t mepc) { __ASM volatile("csrw mepc, %0" : : "r"(mepc)); } /** \brief Set MXSTATUS \details Writes the given value to the MXSTATUS Register. \param [in] mxstatus MXSTATUS Register value to set */ __ALWAYS_STATIC_INLINE void __set_MXSTATUS(uint64_t mxstatus) { __ASM volatile("csrw mxstatus, %0" : : "r"(mxstatus)); } /** \brief Get MSTATUS \details Returns the content of the MSTATUS Register. \return MSTATUS Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MSTATUS(void) { uint64_t result; __ASM volatile("csrr %0, mstatus" : "=r"(result)); return (result); } /** \brief Set MSTATUS \details Writes the given value to the MSTATUS Register. \param [in] mstatus MSTATUS Register value to set */ __ALWAYS_STATIC_INLINE void __set_MSTATUS(uint64_t mstatus) { __ASM volatile("csrw mstatus, %0" : : "r"(mstatus)); } /** \brief Get MHCR \details Returns the content of the MHCR Register. \return MHCR Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MHCR(void) { uint64_t result; __ASM volatile("csrr %0, mhcr" : "=r"(result)); return (result); } /** \brief Set MHCR \details Writes the given value to the MHCR Register. \param [in] mstatus MHCR Register value to set */ __ALWAYS_STATIC_INLINE void __set_MHCR(uint64_t mhcr) { __ASM volatile("csrw mhcr, %0" : : "r"(mhcr)); } /** \brief Get MISA Register \details Returns the content of the MISA Register. \return MISA Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MISA(void) { uint64_t result; __ASM volatile("csrr %0, misa" : "=r"(result)); return (result); } /** \brief Set MISA \details Writes the given value to the MISA Register. \param [in] misa MISA Register value to set */ __ALWAYS_STATIC_INLINE void __set_MISA(uint64_t misa) { __ASM volatile("csrw misa, %0" : : "r"(misa)); } /** \brief Get MIE Register \details Returns the content of the MIE Register. \return MIE Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MIE(void) { uint64_t result; __ASM volatile("csrr %0, mie" : "=r"(result)); return (result); } /** \brief Set MIE \details Writes the given value to the MIE Register. \param [in] mie MIE Register value to set */ __ALWAYS_STATIC_INLINE void __set_MIE(uint64_t mie) { __ASM volatile("csrw mie, %0" : : "r"(mie)); } /** \brief Get MTVEC Register \details Returns the content of the MTVEC Register. \return MTVEC Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MTVEC(void) { uint64_t result; __ASM volatile("csrr %0, mtvec" : "=r"(result)); return (result); } /** \brief Set MTVEC \details Writes the given value to the MTVEC Register. \param [in] mtvec MTVEC Register value to set */ __ALWAYS_STATIC_INLINE void __set_MTVEC(uint64_t mtvec) { __ASM volatile("csrw mtvec, %0" : : "r"(mtvec)); } /** \brief Set MTVT \details Writes the given value to the MTVT Register. \param [in] mtvt MTVT Register value to set */ __ALWAYS_STATIC_INLINE void __set_MTVT(uint64_t mtvt) { __ASM volatile("csrw mtvt, %0" : : "r"(mtvt)); } /** \brief Get MTVT Register \details Returns the content of the MTVT Register. \return MTVT Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MTVT(void) { uint64_t result; __ASM volatile("csrr %0, mtvt" : "=r"(result)); return (result); } /** \brief Get SP \details Returns the content of the SP Register. \return SP Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_SP(void) { uint64_t result; __ASM volatile("mv %0, sp" : "=r"(result)); return (result); } /** \brief Set SP \details Writes the given value to the SP Register. \param [in] sp SP Register value to set */ __ALWAYS_STATIC_INLINE void __set_SP(uint64_t sp) { __ASM volatile("mv sp, %0" : : "r"(sp): "sp"); } /** \brief Get MSCRATCH Register \details Returns the content of the MSCRATCH Register. \return MSCRATCH Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MSCRATCH(void) { uint64_t result; __ASM volatile("csrr %0, mscratch" : "=r"(result)); return (result); } /** \brief Set MSCRATCH \details Writes the given value to the MSCRATCH Register. \param [in] mscratch MSCRATCH Register value to set */ __ALWAYS_STATIC_INLINE void __set_MSCRATCH(uint64_t mscratch) { __ASM volatile("csrw mscratch, %0" : : "r"(mscratch)); } /** \brief Get MCAUSE Register \details Returns the content of the MCAUSE Register. \return MCAUSE Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MCAUSE(void) { uint64_t result; __ASM volatile("csrr %0, mcause" : "=r"(result)); return (result); } /** \brief Get MNXTI Register \details Returns the content of the MNXTI Register. \return MNXTI Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MNXTI(void) { uint64_t result; __ASM volatile("csrr %0, mnxti" : "=r"(result)); return (result); } /** \brief Set MNXTI \details Writes the given value to the MNXTI Register. \param [in] mnxti MNXTI Register value to set */ __ALWAYS_STATIC_INLINE void __set_MNXTI(uint64_t mnxti) { __ASM volatile("csrw mnxti, %0" : : "r"(mnxti)); } /** \brief Get MINTSTATUS Register \details Returns the content of the MINTSTATUS Register. \return MINTSTATUS Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MINTSTATUS(void) { uint64_t result; __ASM volatile("csrr %0, mintstatus" : "=r"(result)); return (result); } /** \brief Get MTVAL Register \details Returns the content of the MTVAL Register. \return MTVAL Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MTVAL(void) { uint64_t result; __ASM volatile("csrr %0, mtval" : "=r"(result)); return (result); } /** \brief Get MIP Register \details Returns the content of the MIP Register. \return MIP Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MIP(void) { uint64_t result; __ASM volatile("csrr %0, mip" : "=r"(result)); return (result); } /** \brief Set MIP \details Writes the given value to the MIP Register. \param [in] mip MIP Register value to set */ __ALWAYS_STATIC_INLINE void __set_MIP(uint64_t mip) { __ASM volatile("csrw mip, %0" : : "r"(mip)); } /** \brief Get MCYCLEL Register \details Returns the content of the MCYCLEL Register. \return MCYCLE Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MCYCLE(void) { uint64_t result; __ASM volatile("csrr %0, mcycle" : "=r"(result)); return (result); } /** \brief Get MCYCLEH Register \details Returns the content of the MCYCLEH Register. \return MCYCLEH Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MCYCLEH(void) { uint64_t result; __ASM volatile("csrr %0, mcycleh" : "=r"(result)); return (result); } /** \brief Get MINSTRET Register \details Returns the content of the MINSTRET Register. \return MINSTRET Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MINSTRET(void) { uint64_t result; __ASM volatile("csrr %0, minstret" : "=r"(result)); return (result); } /** \brief Get MINSTRETH Register \details Returns the content of the MINSTRETH Register. \return MINSTRETH Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MINSTRETH(void) { uint64_t result; __ASM volatile("csrr %0, minstreth" : "=r"(result)); return (result); } /** \brief Get MVENDORID Register \details Returns the content of the MVENDROID Register. \return MVENDORID Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MVENDORID(void) { uint64_t result; __ASM volatile("csrr %0, mvendorid" : "=r"(result)); return (result); } /** \brief Get MARCHID Register \details Returns the content of the MARCHID Register. \return MARCHID Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MARCHID(void) { uint64_t result; __ASM volatile("csrr %0, marchid" : "=r"(result)); return (result); } /** \brief Get MIMPID Register \details Returns the content of the MIMPID Register. \return MIMPID Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MIMPID(void) { uint64_t result; __ASM volatile("csrr %0, mimpid" : "=r"(result)); return (result); } /** \brief Get MHARTID Register \details Returns the content of the MHARTID Register. \return MHARTID Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_MHARTID(void) { uint64_t result; __ASM volatile("csrr %0, mhartid" : "=r"(result)); return (result); } /** \brief Get PMPCFGx Register \details Returns the content of the PMPCFGx Register. \return PMPCFGx Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_PMPCFG0(void) { uint64_t result; __ASM volatile("csrr %0, pmpcfg0" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPCFG1(void) { uint64_t result; __ASM volatile("csrr %0, pmpcfg1" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPCFG2(void) { uint64_t result; __ASM volatile("csrr %0, pmpcfg2" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPCFG3(void) { uint64_t result; __ASM volatile("csrr %0, pmpcfg3" : "=r"(result)); return (result); } /** \brief Get PMPxCFG Register by index \details Returns the content of the PMPxCFG Register. \param [in] idx PMP region index \return PMPxCFG Register value */ __STATIC_INLINE uint8_t __get_PMPxCFG(uint64_t idx) { uint64_t pmpcfgx = 0; if (idx < 4) { pmpcfgx = __get_PMPCFG0(); } else if (idx >=4 && idx < 8) { idx -= 4; pmpcfgx = __get_PMPCFG1(); } else if (idx >=8 && idx < 12) { idx -= 8; pmpcfgx = __get_PMPCFG2(); } else if (idx >=12 && idx < 16) { idx -= 12; pmpcfgx = __get_PMPCFG3(); } else { return 0; } return (uint8_t)((pmpcfgx & (0xFF << (idx << 3))) >> (idx << 3)); } /** \brief Set PMPCFGx \details Writes the given value to the PMPCFGx Register. \param [in] pmpcfg PMPCFGx Register value to set */ __ALWAYS_STATIC_INLINE void __set_PMPCFG0(uint64_t pmpcfg) { __ASM volatile("csrw pmpcfg0, %0" : : "r"(pmpcfg)); } __ALWAYS_STATIC_INLINE void __set_PMPCFG1(uint64_t pmpcfg) { __ASM volatile("csrw pmpcfg1, %0" : : "r"(pmpcfg)); } __ALWAYS_STATIC_INLINE void __set_PMPCFG2(uint64_t pmpcfg) { __ASM volatile("csrw pmpcfg2, %0" : : "r"(pmpcfg)); } __ALWAYS_STATIC_INLINE void __set_PMPCFG3(uint64_t pmpcfg) { __ASM volatile("csrw pmpcfg3, %0" : : "r"(pmpcfg)); } /** \brief Set PMPxCFG by index \details Writes the given value to the PMPxCFG Register. \param [in] idx PMPx region index \param [in] pmpxcfg PMPxCFG Register value to set */ __STATIC_INLINE void __set_PMPxCFG(uint64_t idx, uint8_t pmpxcfg) { uint64_t pmpcfgx = 0; if (idx < 4) { pmpcfgx = __get_PMPCFG0(); pmpcfgx = (pmpcfgx & ~(0xFF << (idx << 3))) | (pmpxcfg << (idx << 3)); __set_PMPCFG0(pmpcfgx); } else if (idx >=4 && idx < 8) { idx -= 4; pmpcfgx = __get_PMPCFG1(); pmpcfgx = (pmpcfgx & ~(0xFF << (idx << 3))) | (pmpxcfg << (idx << 3)); __set_PMPCFG1(pmpcfgx); } else if (idx >=8 && idx < 12) { idx -= 8; pmpcfgx = __get_PMPCFG2(); pmpcfgx = (pmpcfgx & ~(0xFF << (idx << 3))) | (pmpxcfg << (idx << 3)); __set_PMPCFG2(pmpcfgx); } else if (idx >=12 && idx < 16) { idx -= 12; pmpcfgx = __get_PMPCFG3(); pmpcfgx = (pmpcfgx & ~(0xFF << (idx << 3))) | (pmpxcfg << (idx << 3)); __set_PMPCFG3(pmpcfgx); } else { return; } } /** \brief Get PMPADDRx Register \details Returns the content of the PMPADDRx Register. \return PMPADDRx Register value */ __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR0(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr0" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR1(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr1" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR2(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr2" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR3(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr3" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR4(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr4" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR5(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr5" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR6(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr6" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR7(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr7" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR8(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr8" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR9(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr9" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR10(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr10" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR11(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr11" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR12(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr12" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR13(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr13" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR14(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr14" : "=r"(result)); return (result); } __ALWAYS_STATIC_INLINE uint64_t __get_PMPADDR15(void) { uint64_t result; __ASM volatile("csrr %0, pmpaddr15" : "=r"(result)); return (result); } /** \brief Get PMPADDRx Register by index \details Returns the content of the PMPADDRx Register. \param [in] idx PMP region index \return PMPADDRx Register value */ __STATIC_INLINE uint64_t __get_PMPADDRx(uint64_t idx) { switch (idx) { case 0: return __get_PMPADDR0(); case 1: return __get_PMPADDR1(); case 2: return __get_PMPADDR2(); case 3: return __get_PMPADDR3(); case 4: return __get_PMPADDR4(); case 5: return __get_PMPADDR5(); case 6: return __get_PMPADDR6(); case 7: return __get_PMPADDR7(); case 8: return __get_PMPADDR8(); case 9: return __get_PMPADDR9(); case 10: return __get_PMPADDR10(); case 11: return __get_PMPADDR11(); case 12: return __get_PMPADDR12(); case 13: return __get_PMPADDR13(); case 14: return __get_PMPADDR14(); case 15: return __get_PMPADDR15(); default: return 0; } } /** \brief Set PMPADDRx \details Writes the given value to the PMPADDRx Register. \param [in] pmpaddr PMPADDRx Register value to set */ __ALWAYS_STATIC_INLINE void __set_PMPADDR0(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr0, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR1(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr1, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR2(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr2, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR3(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr3, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR4(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr4, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR5(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr5, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR6(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr6, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR7(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr7, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR8(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr8, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR9(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr9, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR10(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr10, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR11(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr11, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR12(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr12, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR13(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr13, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR14(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr14, %0" : : "r"(pmpaddr)); } __ALWAYS_STATIC_INLINE void __set_PMPADDR15(uint64_t pmpaddr) { __ASM volatile("csrw pmpaddr15, %0" : : "r"(pmpaddr)); } /** \brief Set PMPADDRx by index \details Writes the given value to the PMPADDRx Register. \param [in] idx PMP region index \param [in] pmpaddr PMPADDRx Register value to set */ __STATIC_INLINE void __set_PMPADDRx(uint64_t idx, uint64_t pmpaddr) { switch (idx) { case 0: __set_PMPADDR0(pmpaddr); break; case 1: __set_PMPADDR1(pmpaddr); break; case 2: __set_PMPADDR2(pmpaddr); break; case 3: __set_PMPADDR3(pmpaddr); break; case 4: __set_PMPADDR4(pmpaddr); break; case 5: __set_PMPADDR5(pmpaddr); break; case 6: __set_PMPADDR6(pmpaddr); break; case 7: __set_PMPADDR7(pmpaddr); break; case 8: __set_PMPADDR8(pmpaddr); break; case 9: __set_PMPADDR9(pmpaddr); break; case 10: __set_PMPADDR10(pmpaddr); break; case 11: __set_PMPADDR11(pmpaddr); break; case 12: __set_PMPADDR12(pmpaddr); break; case 13: __set_PMPADDR13(pmpaddr); break; case 14: __set_PMPADDR14(pmpaddr); break; case 15: __set_PMPADDR15(pmpaddr); break; default: return; } } /** \brief Enable interrupts and exceptions \details Enables interrupts and exceptions by setting the IE-bit and EE-bit in the PSR. Can only be executed in Privileged modes. */ __ALWAYS_STATIC_INLINE void __enable_excp_irq(void) { __enable_irq(); } /** \brief Disable interrupts and exceptions \details Disables interrupts and exceptions by clearing the IE-bit and EE-bit in the PSR. Can only be executed in Privileged modes. */ __ALWAYS_STATIC_INLINE void __disable_excp_irq(void) { __disable_irq(); } #define __CSI_GCC_OUT_REG(r) "=r" (r) #define __CSI_GCC_USE_REG(r) "r" (r) /** \brief No Operation \details No Operation does nothing. This instruction can be used for code alignment purposes. */ __ALWAYS_STATIC_INLINE void __NOP(void) { __ASM volatile("nop"); } /** \brief return from M-MODE \details return from M-MODE. */ __ALWAYS_STATIC_INLINE void __MRET(void) { __ASM volatile("mret"); } /** \brief Wait For Interrupt \details Wait For Interrupt is a hint instruction that suspends execution until one of a number of events occurs. */ __ALWAYS_STATIC_INLINE void __WFI(void) { __ASM volatile("wfi"); } /** \brief Wait For Interrupt \details Wait For Interrupt is a hint instruction that suspends execution until one interrupt occurs. */ __ALWAYS_STATIC_INLINE void __WAIT(void) { __ASM volatile("wfi"); } /** \brief Doze For Interrupt \details Doze For Interrupt is a hint instruction that suspends execution until one interrupt occurs. */ __ALWAYS_STATIC_INLINE void __DOZE(void) { __ASM volatile("wfi"); } /** \brief Stop For Interrupt \details Stop For Interrupt is a hint instruction that suspends execution until one interrupt occurs. */ __ALWAYS_STATIC_INLINE void __STOP(void) { __ASM volatile("wfi"); } /** \brief Instruction Synchronization Barrier \details Instruction Synchronization Barrier flushes the pipeline in the processor, so that all instructions following the ISB are fetched from cache or memory, after the instruction has been completed. */ __ALWAYS_STATIC_INLINE void __ISB(void) { __ASM volatile("fence"); } /** \brief Data Synchronization Barrier \details Acts as a special kind of Data Memory Barrier. It completes when all explicit memory accesses before this instruction complete. */ __ALWAYS_STATIC_INLINE void __DSB(void) { __ASM volatile("fence"); } /** \brief Invalid all icache \details invalid all icache. */ __ALWAYS_STATIC_INLINE void __ICACHE_IALL(void) { __ASM volatile("icache.iall"); } /** \brief Invalid Icache by addr \details Invalid Icache by addr. \param [in] addr operate addr */ __ALWAYS_STATIC_INLINE void __ICACHE_IPA(uint64_t addr) { __ASM volatile("icache.ipa %0" : : "r"(addr)); } /** \brief Invalid all dcache \details invalid all dcache. */ __ALWAYS_STATIC_INLINE void __DCACHE_IALL(void) { __ASM volatile("dcache.iall"); } /** \brief Clear all dcache \details clear all dcache. */ __ALWAYS_STATIC_INLINE void __DCACHE_CALL(void) { __ASM volatile("dcache.call"); } /** \brief Clear&invalid all dcache \details clear & invalid all dcache. */ __ALWAYS_STATIC_INLINE void __DCACHE_CIALL(void) { __ASM volatile("dcache.ciall"); } #if (__L2CACHE_PRESENT == 1U) /** \brief Invalid L2 cache \details invalid L2 cache. */ __ALWAYS_STATIC_INLINE void __L2CACHE_IALL(void) { __ASM volatile("l2cache.iall"); } /** \brief Clear L2cache \details clear L2cache. */ __ALWAYS_STATIC_INLINE void __L2CACHE_CALL(void) { __ASM volatile("l2cache.call"); } /** \brief Clear&invalid L2cache \details clear & invalid L2cache. */ __ALWAYS_STATIC_INLINE void __L2CACHE_CIALL(void) { __ASM volatile("l2cache.ciall"); } #endif /** \brief Invalid Dcache by addr \details Invalid Dcache by addr. \param [in] addr operate addr */ __ALWAYS_STATIC_INLINE void __DCACHE_IPA(uint64_t addr) { __ASM volatile("dcache.ipa %0" : : "r"(addr)); } /** \brief Clear Dcache by addr \details Clear Dcache by addr. \param [in] addr operate addr */ __ALWAYS_STATIC_INLINE void __DCACHE_CPA(uint64_t addr) { __ASM volatile("dcache.cpa %0" : : "r"(addr)); } /** \brief Clear & Invalid Dcache by addr \details Clear & Invalid Dcache by addr. \param [in] addr operate addr */ __ALWAYS_STATIC_INLINE void __DCACHE_CIPA(uint64_t addr) { __ASM volatile("dcache.cipa %0" : : "r"(addr)); } /** \brief Data Memory Barrier \details Ensures the apparent order of the explicit memory operations before and after the instruction, without ensuring their completion. */ __ALWAYS_STATIC_INLINE void __DMB(void) { __ASM volatile("fence"); } /** \brief Reverse byte order (32 bit) \details Reverses the byte order in integer value. \param [in] value Value to reverse \return Reversed value */ __ALWAYS_STATIC_INLINE uint64_t __REV(uint64_t value) { return __builtin_bswap32(value); } /** \brief Reverse byte order (16 bit) \details Reverses the byte order in two unsigned short values. \param [in] value Value to reverse \return Reversed value */ __ALWAYS_STATIC_INLINE uint32_t __REV16(uint32_t value) { uint32_t result; result = ((value & 0xFF000000) >> 8) | ((value & 0x00FF0000) << 8) | ((value & 0x0000FF00) >> 8) | ((value & 0x000000FF) << 8); return (result); } /** \brief Reverse byte order in signed short value \details Reverses the byte order in a signed short value with sign extension to integer. \param [in] value Value to reverse \return Reversed value */ __ALWAYS_STATIC_INLINE int32_t __REVSH(int32_t value) { return (short)(((value & 0xFF00) >> 8) | ((value & 0x00FF) << 8)); } /** \brief Rotate Right in unsigned value (32 bit) \details Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits. \param [in] op1 Value to rotate \param [in] op2 Number of Bits to rotate \return Rotated value */ __ALWAYS_STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2) { return (op1 >> op2) | (op1 << (32U - op2)); } /** \brief Breakpoint \details Causes the processor to enter Debug state Debug tools can use this to investigate system state when the instruction at a particular address is reached. */ __ALWAYS_STATIC_INLINE void __BKPT(void) { __ASM volatile("ebreak"); } /** \brief Reverse bit order of value \details Reverses the bit order of the given value. \param [in] value Value to reverse \return Reversed value */ __ALWAYS_STATIC_INLINE uint32_t __RBIT(uint32_t value) { uint32_t result; int32_t s = 4 /*sizeof(v)*/ * 8 - 1; /* extra shift needed at end */ result = value; /* r will be reversed bits of v; first get LSB of v */ for (value >>= 1U; value; value >>= 1U) { result <<= 1U; result |= value & 1U; s--; } result <<= s; /* shift when v's highest bits are zero */ return (result); } /** \brief Count leading zeros \details Counts the number of leading zeros of a data value. \param [in] value Value to count the leading zeros \return number of leading zeros in value */ #define __CLZ __builtin_clz /** \details This function saturates a signed value. \param [in] x Value to be saturated \param [in] y Bit position to saturate to [1..32] \return Saturated value. */ __ALWAYS_STATIC_INLINE int32_t __SSAT(int32_t x, uint32_t y) { int32_t posMax, negMin; uint32_t i; posMax = 1; for (i = 0; i < (y - 1); i++) { posMax = posMax * 2; } if (x > 0) { posMax = (posMax - 1); if (x > posMax) { x = posMax; } // x &= (posMax * 2 + 1); } else { negMin = -posMax; if (x < negMin) { x = negMin; } // x &= (posMax * 2 - 1); } return (x); } /** \brief Unsigned Saturate \details Saturates an unsigned value. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ __ALWAYS_STATIC_INLINE uint32_t __USAT(uint32_t value, uint32_t sat) { uint32_t result; if ((((0xFFFFFFFF >> sat) << sat) & value) != 0) { result = 0xFFFFFFFF >> (32 - sat); } else { result = value; } return (result); } /** \brief Unsigned Saturate for internal use \details Saturates an unsigned value, should not call directly. \param [in] value Value to be saturated \param [in] sat Bit position to saturate to (0..31) \return Saturated value */ __ALWAYS_STATIC_INLINE uint32_t __IUSAT(uint32_t value, uint32_t sat) { uint32_t result; if (value & 0x80000000) { /* only overflow set bit-31 */ result = 0; } else if ((((0xFFFFFFFF >> sat) << sat) & value) != 0) { result = 0xFFFFFFFF >> (32 - sat); } else { result = value; } return (result); } /** \brief Rotate Right with Extend \details This function moves each bit of a bitstring right by one bit. The carry input is shifted in at the left end of the bitstring. \note carry input will always 0. \param [in] op1 Value to rotate \return Rotated value */ __ALWAYS_STATIC_INLINE uint32_t __RRX(uint32_t op1) { return 0; } /** \brief LDRT Unprivileged (8 bit) \details Executes a Unprivileged LDRT instruction for 8 bit value. \param [in] addr Pointer to location \return value of type uint8_t at (*ptr) */ __ALWAYS_STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *addr) { uint32_t result; __ASM volatile("lb %0, 0(%1)" : "=r"(result) : "r"(addr)); return ((uint8_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (16 bit) \details Executes a Unprivileged LDRT instruction for 16 bit values. \param [in] addr Pointer to location \return value of type uint16_t at (*ptr) */ __ALWAYS_STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *addr) { uint32_t result; __ASM volatile("lh %0, 0(%1)" : "=r"(result) : "r"(addr)); return ((uint16_t) result); /* Add explicit type cast here */ } /** \brief LDRT Unprivileged (32 bit) \details Executes a Unprivileged LDRT instruction for 32 bit values. \param [in] addr Pointer to location \return value of type uint32_t at (*ptr) */ __ALWAYS_STATIC_INLINE uint32_t __LDRT(volatile uint32_t *addr) { uint32_t result; __ASM volatile("lw %0, 0(%1)" : "=r"(result) : "r"(addr)); return (result); } /** \brief STRT Unprivileged (8 bit) \details Executes a Unprivileged STRT instruction for 8 bit values. \param [in] value Value to store \param [in] addr Pointer to location */ __ALWAYS_STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *addr) { __ASM volatile("sb %1, 0(%0)" :: "r"(addr), "r"((uint32_t)value) : "memory"); } /** \brief STRT Unprivileged (16 bit) \details Executes a Unprivileged STRT instruction for 16 bit values. \param [in] value Value to store \param [in] addr Pointer to location */ __ALWAYS_STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *addr) { __ASM volatile("sh %1, 0(%0)" :: "r"(addr), "r"((uint32_t)value) : "memory"); } /** \brief STRT Unprivileged (32 bit) \details Executes a Unprivileged STRT instruction for 32 bit values. \param [in] value Value to store \param [in] addr Pointer to location */ __ALWAYS_STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *addr) { __ASM volatile("sw %1, 0(%0)" :: "r"(addr), "r"(value) : "memory"); } /*@}*/ /* end of group CSI_Core_InstructionInterface */ /* ################### Compiler specific Intrinsics ########################### */ /** \defgroup CSI_SIMD_intrinsics CSI SIMD Intrinsics Access to dedicated SIMD instructions \n Single Instruction Multiple Data (SIMD) extensions are provided to simplify development of application software. SIMD extensions increase the processing capability without materially increasing the power consumption. The SIMD extensions are completely transparent to the operating system (OS), allowing existing OS ports to be used. @{ */ /** \brief Halfword packing instruction. Combines bits[15:0] of val1 with bits[31:16] of val2 levitated with the val3. \details Combine a halfword from one register with a halfword from another register. The second argument can be left-shifted before extraction of the halfword. \param [in] val1 first 16-bit operands \param [in] val2 second 16-bit operands \param [in] val3 value for left-shifting val2. Value range [0..31]. \return the combination of halfwords. \remark res[15:0] = val1[15:0] \n res[31:16] = val2[31:16] << val3 */ __ALWAYS_STATIC_INLINE uint32_t __PKHBT(uint32_t val1, uint32_t val2, uint32_t val3) { return ((((int32_t)(val1) << 0) & (int32_t)0x0000FFFF) | (((int32_t)(val2) << val3) & (int32_t)0xFFFF0000)); } /** \brief Halfword packing instruction. Combines bits[31:16] of val1 with bits[15:0] of val2 right-shifted with the val3. \details Combine a halfword from one register with a halfword from another register. The second argument can be right-shifted before extraction of the halfword. \param [in] val1 first 16-bit operands \param [in] val2 second 16-bit operands \param [in] val3 value for right-shifting val2. Value range [1..32]. \return the combination of halfwords. \remark res[15:0] = val2[15:0] >> val3 \n res[31:16] = val1[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __PKHTB(uint32_t val1, uint32_t val2, uint32_t val3) { return ((((int32_t)(val1) << 0) & (int32_t)0xFFFF0000) | (((int32_t)(val2) >> val3) & (int32_t)0x0000FFFF)); } /** \brief Dual 16-bit signed saturate. \details This function saturates a signed value. \param [in] x two signed 16-bit values to be saturated. \param [in] y bit position for saturation, an integral constant expression in the range 1 to 16. \return the sum of the absolute differences of the following bytes, added to the accumulation value:\n the signed saturation of the low halfword in val1, saturated to the bit position specified in val2 and returned in the low halfword of the return value.\n the signed saturation of the high halfword in val1, saturated to the bit position specified in val2 and returned in the high halfword of the return value. */ __ALWAYS_STATIC_INLINE uint32_t __SSAT16(int32_t x, const uint32_t y) { int32_t r = 0, s = 0; r = __SSAT((((int32_t)x << 16) >> 16), y) & (int32_t)0x0000FFFF; s = __SSAT((((int32_t)x) >> 16), y) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned saturate. \details This function enables you to saturate two signed 16-bit values to a selected unsigned range. \param [in] x two signed 16-bit values to be saturated. \param [in] y bit position for saturation, an integral constant expression in the range 1 to 16. \return the saturation of the two signed 16-bit values, as non-negative values: the saturation of the low halfword in val1, saturated to the bit position specified in val2 and returned in the low halfword of the return value.\n the saturation of the high halfword in val1, saturated to the bit position specified in val2 and returned in the high halfword of the return value. */ __ALWAYS_STATIC_INLINE uint32_t __USAT16(uint32_t x, const uint32_t y) { int32_t r = 0, s = 0; r = __IUSAT(((x << 16) >> 16), y) & 0x0000FFFF; s = __IUSAT(((x) >> 16), y) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Quad 8-bit saturating addition. \details This function enables you to perform four 8-bit integer additions, saturating the results to the 8-bit signed integer range -2^7 <= x <= 2^7 - 1. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the saturated addition of the first byte of each operand in the first byte of the return value.\n the saturated addition of the second byte of each operand in the second byte of the return value.\n the saturated addition of the third byte of each operand in the third byte of the return value.\n the saturated addition of the fourth byte of each operand in the fourth byte of the return value.\n The returned results are saturated to the 8-bit signed integer range -2^7 <= x <= 2^7 - 1. \remark res[7:0] = val1[7:0] + val2[7:0] \n res[15:8] = val1[15:8] + val2[15:8] \n res[23:16] = val1[23:16] + val2[23:16] \n res[31:24] = val1[31:24] + val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __QADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = __SSAT(((((int32_t)x << 24) >> 24) + (((int32_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF; s = __SSAT(((((int32_t)x << 16) >> 24) + (((int32_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF; t = __SSAT(((((int32_t)x << 8) >> 24) + (((int32_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF; u = __SSAT(((((int32_t)x) >> 24) + (((int32_t)y) >> 24)), 8) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned saturating addition. \details This function enables you to perform four unsigned 8-bit integer additions, saturating the results to the 8-bit unsigned integer range 0 < x < 2^8 - 1. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the saturated addition of the first byte of each operand in the first byte of the return value.\n the saturated addition of the second byte of each operand in the second byte of the return value.\n the saturated addition of the third byte of each operand in the third byte of the return value.\n the saturated addition of the fourth byte of each operand in the fourth byte of the return value.\n The returned results are saturated to the 8-bit signed integer range 0 <= x <= 2^8 - 1. \remark res[7:0] = val1[7:0] + val2[7:0] \n res[15:8] = val1[15:8] + val2[15:8] \n res[23:16] = val1[23:16] + val2[23:16] \n res[31:24] = val1[31:24] + val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __UQADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = __IUSAT((((x << 24) >> 24) + ((y << 24) >> 24)), 8) & 0x000000FF; s = __IUSAT((((x << 16) >> 24) + ((y << 16) >> 24)), 8) & 0x000000FF; t = __IUSAT((((x << 8) >> 24) + ((y << 8) >> 24)), 8) & 0x000000FF; u = __IUSAT((((x) >> 24) + ((y) >> 24)), 8) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Quad 8-bit signed addition. \details This function performs four 8-bit signed integer additions. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the addition of the first bytes from each operand, in the first byte of the return value.\n the addition of the second bytes of each operand, in the second byte of the return value.\n the addition of the third bytes of each operand, in the third byte of the return value.\n the addition of the fourth bytes of each operand, in the fourth byte of the return value. \remark res[7:0] = val1[7:0] + val2[7:0] \n res[15:8] = val1[15:8] + val2[15:8] \n res[23:16] = val1[23:16] + val2[23:16] \n res[31:24] = val1[31:24] + val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __SADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = ((((int32_t)x << 24) >> 24) + (((int32_t)y << 24) >> 24)) & (int32_t)0x000000FF; s = ((((int32_t)x << 16) >> 24) + (((int32_t)y << 16) >> 24)) & (int32_t)0x000000FF; t = ((((int32_t)x << 8) >> 24) + (((int32_t)y << 8) >> 24)) & (int32_t)0x000000FF; u = ((((int32_t)x) >> 24) + (((int32_t)y) >> 24)) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned addition. \details This function performs four unsigned 8-bit integer additions. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the addition of the first bytes from each operand, in the first byte of the return value.\n the addition of the second bytes of each operand, in the second byte of the return value.\n the addition of the third bytes of each operand, in the third byte of the return value.\n the addition of the fourth bytes of each operand, in the fourth byte of the return value. \remark res[7:0] = val1[7:0] + val2[7:0] \n res[15:8] = val1[15:8] + val2[15:8] \n res[23:16] = val1[23:16] + val2[23:16] \n res[31:24] = val1[31:24] + val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __UADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = (((x << 24) >> 24) + ((y << 24) >> 24)) & 0x000000FF; s = (((x << 16) >> 24) + ((y << 16) >> 24)) & 0x000000FF; t = (((x << 8) >> 24) + ((y << 8) >> 24)) & 0x000000FF; u = (((x) >> 24) + ((y) >> 24)) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Quad 8-bit saturating subtract. \details This function enables you to perform four 8-bit integer subtractions, saturating the results to the 8-bit signed integer range -2^7 <= x <= 2^7 - 1. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the subtraction of the first byte of each operand in the first byte of the return value.\n the subtraction of the second byte of each operand in the second byte of the return value.\n the subtraction of the third byte of each operand in the third byte of the return value.\n the subtraction of the fourth byte of each operand in the fourth byte of the return value.\n The returned results are saturated to the 8-bit signed integer range -2^7 <= x <= 2^7 - 1. \remark res[7:0] = val1[7:0] - val2[7:0] \n res[15:8] = val1[15:8] - val2[15:8] \n res[23:16] = val1[23:16] - val2[23:16] \n res[31:24] = val1[31:24] - val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __QSUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = __SSAT(((((int32_t)x << 24) >> 24) - (((int32_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF; s = __SSAT(((((int32_t)x << 16) >> 24) - (((int32_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF; t = __SSAT(((((int32_t)x << 8) >> 24) - (((int32_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF; u = __SSAT(((((int32_t)x) >> 24) - (((int32_t)y) >> 24)), 8) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned saturating subtraction. \details This function enables you to perform four unsigned 8-bit integer subtractions, saturating the results to the 8-bit unsigned integer range 0 < x < 2^8 - 1. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the subtraction of the first byte of each operand in the first byte of the return value.\n the subtraction of the second byte of each operand in the second byte of the return value.\n the subtraction of the third byte of each operand in the third byte of the return value.\n the subtraction of the fourth byte of each operand in the fourth byte of the return value.\n The returned results are saturated to the 8-bit unsigned integer range 0 <= x <= 2^8 - 1. \remark res[7:0] = val1[7:0] - val2[7:0] \n res[15:8] = val1[15:8] - val2[15:8] \n res[23:16] = val1[23:16] - val2[23:16] \n res[31:24] = val1[31:24] - val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __UQSUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = __IUSAT((((x << 24) >> 24) - ((y << 24) >> 24)), 8) & 0x000000FF; s = __IUSAT((((x << 16) >> 24) - ((y << 16) >> 24)), 8) & 0x000000FF; t = __IUSAT((((x << 8) >> 24) - ((y << 8) >> 24)), 8) & 0x000000FF; u = __IUSAT((((x) >> 24) - ((y) >> 24)), 8) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Quad 8-bit signed subtraction. \details This function enables you to perform four 8-bit signed integer subtractions. \param [in] x first four 8-bit operands of each subtraction. \param [in] y second four 8-bit operands of each subtraction. \return the subtraction of the first bytes from each operand, in the first byte of the return value.\n the subtraction of the second bytes of each operand, in the second byte of the return value.\n the subtraction of the third bytes of each operand, in the third byte of the return value.\n the subtraction of the fourth bytes of each operand, in the fourth byte of the return value. \remark res[7:0] = val1[7:0] - val2[7:0] \n res[15:8] = val1[15:8] - val2[15:8] \n res[23:16] = val1[23:16] - val2[23:16] \n res[31:24] = val1[31:24] - val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __SSUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = ((((int32_t)x << 24) >> 24) - (((int32_t)y << 24) >> 24)) & (int32_t)0x000000FF; s = ((((int32_t)x << 16) >> 24) - (((int32_t)y << 16) >> 24)) & (int32_t)0x000000FF; t = ((((int32_t)x << 8) >> 24) - (((int32_t)y << 8) >> 24)) & (int32_t)0x000000FF; u = ((((int32_t)x) >> 24) - (((int32_t)y) >> 24)) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned subtract. \details This function enables you to perform four 8-bit unsigned integer subtractions. \param [in] x first four 8-bit operands of each subtraction. \param [in] y second four 8-bit operands of each subtraction. \return the subtraction of the first bytes from each operand, in the first byte of the return value.\n the subtraction of the second bytes of each operand, in the second byte of the return value.\n the subtraction of the third bytes of each operand, in the third byte of the return value.\n the subtraction of the fourth bytes of each operand, in the fourth byte of the return value. \remark res[7:0] = val1[7:0] - val2[7:0] \n res[15:8] = val1[15:8] - val2[15:8] \n res[23:16] = val1[23:16] - val2[23:16] \n res[31:24] = val1[31:24] - val2[31:24] */ __ALWAYS_STATIC_INLINE uint32_t __USUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = (((x << 24) >> 24) - ((y << 24) >> 24)) & 0x000000FF; s = (((x << 16) >> 24) - ((y << 16) >> 24)) & 0x000000FF; t = (((x << 8) >> 24) - ((y << 8) >> 24)) & 0x000000FF; u = (((x) >> 24) - ((y) >> 24)) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Unsigned sum of quad 8-bit unsigned absolute difference. \details This function enables you to perform four unsigned 8-bit subtractions, and add the absolute values of the differences together, returning the result as a single unsigned integer. \param [in] x first four 8-bit operands of each subtraction. \param [in] y second four 8-bit operands of each subtraction. \return the subtraction of the first bytes from each operand, in the first byte of the return value.\n the subtraction of the second bytes of each operand, in the second byte of the return value.\n the subtraction of the third bytes of each operand, in the third byte of the return value.\n the subtraction of the fourth bytes of each operand, in the fourth byte of the return value.\n The sum is returned as a single unsigned integer. \remark absdiff1 = val1[7:0] - val2[7:0] \n absdiff2 = val1[15:8] - val2[15:8] \n absdiff3 = val1[23:16] - val2[23:16] \n absdiff4 = val1[31:24] - val2[31:24] \n res[31:0] = absdiff1 + absdiff2 + absdiff3 + absdiff4 */ __ALWAYS_STATIC_INLINE uint32_t __USAD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = (((x << 24) >> 24) - ((y << 24) >> 24)) & 0x000000FF; s = (((x << 16) >> 24) - ((y << 16) >> 24)) & 0x000000FF; t = (((x << 8) >> 24) - ((y << 8) >> 24)) & 0x000000FF; u = (((x) >> 24) - ((y) >> 24)) & 0x000000FF; return (u + t + s + r); } /** \brief Unsigned sum of quad 8-bit unsigned absolute difference with 32-bit accumulate. \details This function enables you to perform four unsigned 8-bit subtractions, and add the absolute values of the differences to a 32-bit accumulate operand. \param [in] x first four 8-bit operands of each subtraction. \param [in] y second four 8-bit operands of each subtraction. \param [in] sum accumulation value. \return the sum of the absolute differences of the following bytes, added to the accumulation value: the subtraction of the first bytes from each operand, in the first byte of the return value.\n the subtraction of the second bytes of each operand, in the second byte of the return value.\n the subtraction of the third bytes of each operand, in the third byte of the return value.\n the subtraction of the fourth bytes of each operand, in the fourth byte of the return value. \remark absdiff1 = val1[7:0] - val2[7:0] \n absdiff2 = val1[15:8] - val2[15:8] \n absdiff3 = val1[23:16] - val2[23:16] \n absdiff4 = val1[31:24] - val2[31:24] \n sum = absdiff1 + absdiff2 + absdiff3 + absdiff4 \n res[31:0] = sum[31:0] + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __USADA8(uint32_t x, uint32_t y, uint32_t sum) { int32_t r, s, t, u; #ifdef __cplusplus r = (abs((long long)((x << 24) >> 24) - ((y << 24) >> 24))) & 0x000000FF; s = (abs((long long)((x << 16) >> 24) - ((y << 16) >> 24))) & 0x000000FF; t = (abs((long long)((x << 8) >> 24) - ((y << 8) >> 24))) & 0x000000FF; u = (abs((long long)((x) >> 24) - ((y) >> 24))) & 0x000000FF; #else r = (abs(((x << 24) >> 24) - ((y << 24) >> 24))) & 0x000000FF; s = (abs(((x << 16) >> 24) - ((y << 16) >> 24))) & 0x000000FF; t = (abs(((x << 8) >> 24) - ((y << 8) >> 24))) & 0x000000FF; u = (abs(((x) >> 24) - ((y) >> 24))) & 0x000000FF; #endif return (u + t + s + r + sum); } /** \brief Dual 16-bit saturating addition. \details This function enables you to perform two 16-bit integer arithmetic additions in parallel, saturating the results to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the saturated addition of the low halfwords, in the low halfword of the return value.\n the saturated addition of the high halfwords, in the high halfword of the return value.\n The returned results are saturated to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \remark res[15:0] = val1[15:0] + val2[15:0] \n res[31:16] = val1[31:16] + val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __QADD16(uint32_t x, uint32_t y) { int32_t r = 0, s = 0; r = __SSAT(((((int32_t)x << 16) >> 16) + (((int32_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((int32_t)x) >> 16) + (((int32_t)y) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned saturating addition. \details This function enables you to perform two unsigned 16-bit integer additions, saturating the results to the 16-bit unsigned integer range 0 < x < 2^16 - 1. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the saturated addition of the low halfwords, in the low halfword of the return value.\n the saturated addition of the high halfwords, in the high halfword of the return value.\n The results are saturated to the 16-bit unsigned integer range 0 < x < 2^16 - 1. \remark res[15:0] = val1[15:0] + val2[15:0] \n res[31:16] = val1[31:16] + val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __UQADD16(uint32_t x, uint32_t y) { int32_t r = 0, s = 0; r = __IUSAT((((x << 16) >> 16) + ((y << 16) >> 16)), 16) & 0x0000FFFF; s = __IUSAT((((x) >> 16) + ((y) >> 16)), 16) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed addition. \details This function enables you to perform two 16-bit signed integer additions. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the addition of the low halfwords in the low halfword of the return value.\n the addition of the high halfwords in the high halfword of the return value. \remark res[15:0] = val1[15:0] + val2[15:0] \n res[31:16] = val1[31:16] + val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __SADD16(uint32_t x, uint32_t y) { int32_t r = 0, s = 0; r = ((((int32_t)x << 16) >> 16) + (((int32_t)y << 16) >> 16)) & (int32_t)0x0000FFFF; s = ((((int32_t)x) >> 16) + (((int32_t)y) >> 16)) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned addition \details This function enables you to perform two 16-bit unsigned integer additions. \param [in] x first two 16-bit summands for each addition. \param [in] y second two 16-bit summands for each addition. \return the addition of the low halfwords in the low halfword of the return value.\n the addition of the high halfwords in the high halfword of the return value. \remark res[15:0] = val1[15:0] + val2[15:0] \n res[31:16] = val1[31:16] + val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __UADD16(uint32_t x, uint32_t y) { int32_t r = 0, s = 0; r = (((x << 16) >> 16) + ((y << 16) >> 16)) & 0x0000FFFF; s = (((x) >> 16) + ((y) >> 16)) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed addition with halved results. \details This function enables you to perform two signed 16-bit integer additions, halving the results. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the halved addition of the low halfwords, in the low halfword of the return value.\n the halved addition of the high halfwords, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] + val2[15:0]) >> 1 \n res[31:16] = (val1[31:16] + val2[31:16]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHADD16(uint32_t x, uint32_t y) { int32_t r, s; r = (((((int32_t)x << 16) >> 16) + (((int32_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((int32_t)x) >> 16) + (((int32_t)y) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned addition with halved results. \details This function enables you to perform two unsigned 16-bit integer additions, halving the results. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the halved addition of the low halfwords, in the low halfword of the return value.\n the halved addition of the high halfwords, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] + val2[15:0]) >> 1 \n res[31:16] = (val1[31:16] + val2[31:16]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHADD16(uint32_t x, uint32_t y) { int32_t r, s; r = ((((x << 16) >> 16) + ((y << 16) >> 16)) >> 1) & 0x0000FFFF; s = ((((x) >> 16) + ((y) >> 16)) >> 1) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Quad 8-bit signed addition with halved results. \details This function enables you to perform four signed 8-bit integer additions, halving the results. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the halved addition of the first bytes from each operand, in the first byte of the return value.\n the halved addition of the second bytes from each operand, in the second byte of the return value.\n the halved addition of the third bytes from each operand, in the third byte of the return value.\n the halved addition of the fourth bytes from each operand, in the fourth byte of the return value. \remark res[7:0] = (val1[7:0] + val2[7:0] ) >> 1 \n res[15:8] = (val1[15:8] + val2[15:8] ) >> 1 \n res[23:16] = (val1[23:16] + val2[23:16]) >> 1 \n res[31:24] = (val1[31:24] + val2[31:24]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = (((((int32_t)x << 24) >> 24) + (((int32_t)y << 24) >> 24)) >> 1) & (int32_t)0x000000FF; s = (((((int32_t)x << 16) >> 24) + (((int32_t)y << 16) >> 24)) >> 1) & (int32_t)0x000000FF; t = (((((int32_t)x << 8) >> 24) + (((int32_t)y << 8) >> 24)) >> 1) & (int32_t)0x000000FF; u = (((((int32_t)x) >> 24) + (((int32_t)y) >> 24)) >> 1) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned addition with halved results. \details This function enables you to perform four unsigned 8-bit integer additions, halving the results. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the halved addition of the first bytes from each operand, in the first byte of the return value.\n the halved addition of the second bytes from each operand, in the second byte of the return value.\n the halved addition of the third bytes from each operand, in the third byte of the return value.\n the halved addition of the fourth bytes from each operand, in the fourth byte of the return value. \remark res[7:0] = (val1[7:0] + val2[7:0] ) >> 1 \n res[15:8] = (val1[15:8] + val2[15:8] ) >> 1 \n res[23:16] = (val1[23:16] + val2[23:16]) >> 1 \n res[31:24] = (val1[31:24] + val2[31:24]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHADD8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = ((((x << 24) >> 24) + ((y << 24) >> 24)) >> 1) & 0x000000FF; s = ((((x << 16) >> 24) + ((y << 16) >> 24)) >> 1) & 0x000000FF; t = ((((x << 8) >> 24) + ((y << 8) >> 24)) >> 1) & 0x000000FF; u = ((((x) >> 24) + ((y) >> 24)) >> 1) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Dual 16-bit saturating subtract. \details This function enables you to perform two 16-bit integer subtractions in parallel, saturating the results to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the saturated subtraction of the low halfwords, in the low halfword of the return value.\n the saturated subtraction of the high halfwords, in the high halfword of the return value.\n The returned results are saturated to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \remark res[15:0] = val1[15:0] - val2[15:0] \n res[31:16] = val1[31:16] - val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __QSUB16(uint32_t x, uint32_t y) { int32_t r, s; r = __SSAT(((((int32_t)x << 16) >> 16) - (((int32_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((int32_t)x) >> 16) - (((int32_t)y) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned saturating subtraction. \details This function enables you to perform two unsigned 16-bit integer subtractions, saturating the results to the 16-bit unsigned integer range 0 < x < 2^16 - 1. \param [in] x first two 16-bit operands for each subtraction. \param [in] y second two 16-bit operands for each subtraction. \return the saturated subtraction of the low halfwords, in the low halfword of the return value.\n the saturated subtraction of the high halfwords, in the high halfword of the return value.\n The returned results are saturated to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \remark res[15:0] = val1[15:0] - val2[15:0] \n res[31:16] = val1[31:16] - val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __UQSUB16(uint32_t x, uint32_t y) { int32_t r, s; r = __IUSAT((((x << 16) >> 16) - ((y << 16) >> 16)), 16) & 0x0000FFFF; s = __IUSAT((((x) >> 16) - ((y) >> 16)), 16) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed subtraction. \details This function enables you to perform two 16-bit signed integer subtractions. \param [in] x first two 16-bit operands of each subtraction. \param [in] y second two 16-bit operands of each subtraction. \return the subtraction of the low halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value. \n the subtraction of the high halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = val1[15:0] - val2[15:0] \n res[31:16] = val1[31:16] - val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __SSUB16(uint32_t x, uint32_t y) { int32_t r, s; r = ((((int32_t)x << 16) >> 16) - (((int32_t)y << 16) >> 16)) & (int32_t)0x0000FFFF; s = ((((int32_t)x) >> 16) - (((int32_t)y) >> 16)) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned subtract. \details This function enables you to perform two 16-bit unsigned integer subtractions. \param [in] x first two 16-bit operands of each subtraction. \param [in] y second two 16-bit operands of each subtraction. \return the subtraction of the low halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value. \n the subtraction of the high halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = val1[15:0] - val2[15:0] \n res[31:16] = val1[31:16] - val2[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __USUB16(uint32_t x, uint32_t y) { int32_t r, s; r = (((x << 16) >> 16) - ((y << 16) >> 16)) & 0x0000FFFF; s = (((x) >> 16) - ((y) >> 16)) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed subtraction with halved results. \details This function enables you to perform two signed 16-bit integer subtractions, halving the results. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the halved subtraction of the low halfwords, in the low halfword of the return value.\n the halved subtraction of the high halfwords, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] - val2[15:0]) >> 1 \n res[31:16] = (val1[31:16] - val2[31:16]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHSUB16(uint32_t x, uint32_t y) { int32_t r, s; r = (((((int32_t)x << 16) >> 16) - (((int32_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((int32_t)x) >> 16) - (((int32_t)y) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned subtraction with halved results. \details This function enables you to perform two unsigned 16-bit integer subtractions, halving the results. \param [in] x first two 16-bit summands. \param [in] y second two 16-bit summands. \return the halved subtraction of the low halfwords, in the low halfword of the return value.\n the halved subtraction of the high halfwords, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] - val2[15:0]) >> 1 \n res[31:16] = (val1[31:16] - val2[31:16]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHSUB16(uint32_t x, uint32_t y) { int32_t r, s; r = ((((x << 16) >> 16) - ((y << 16) >> 16)) >> 1) & 0x0000FFFF; s = ((((x) >> 16) - ((y) >> 16)) >> 1) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Quad 8-bit signed addition with halved results. \details This function enables you to perform four signed 8-bit integer subtractions, halving the results. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the halved subtraction of the first bytes from each operand, in the first byte of the return value.\n the halved subtraction of the second bytes from each operand, in the second byte of the return value.\n the halved subtraction of the third bytes from each operand, in the third byte of the return value.\n the halved subtraction of the fourth bytes from each operand, in the fourth byte of the return value. \remark res[7:0] = (val1[7:0] - val2[7:0] ) >> 1 \n res[15:8] = (val1[15:8] - val2[15:8] ) >> 1 \n res[23:16] = (val1[23:16] - val2[23:16]) >> 1 \n res[31:24] = (val1[31:24] - val2[31:24]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHSUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = (((((int32_t)x << 24) >> 24) - (((int32_t)y << 24) >> 24)) >> 1) & (int32_t)0x000000FF; s = (((((int32_t)x << 16) >> 24) - (((int32_t)y << 16) >> 24)) >> 1) & (int32_t)0x000000FF; t = (((((int32_t)x << 8) >> 24) - (((int32_t)y << 8) >> 24)) >> 1) & (int32_t)0x000000FF; u = (((((int32_t)x) >> 24) - (((int32_t)y) >> 24)) >> 1) & (int32_t)0x000000FF; return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r))); } /** \brief Quad 8-bit unsigned subtraction with halved results. \details This function enables you to perform four unsigned 8-bit integer subtractions, halving the results. \param [in] x first four 8-bit summands. \param [in] y second four 8-bit summands. \return the halved subtraction of the first bytes from each operand, in the first byte of the return value.\n the halved subtraction of the second bytes from each operand, in the second byte of the return value.\n the halved subtraction of the third bytes from each operand, in the third byte of the return value.\n the halved subtraction of the fourth bytes from each operand, in the fourth byte of the return value. \remark res[7:0] = (val1[7:0] - val2[7:0] ) >> 1 \n res[15:8] = (val1[15:8] - val2[15:8] ) >> 1 \n res[23:16] = (val1[23:16] - val2[23:16]) >> 1 \n res[31:24] = (val1[31:24] - val2[31:24]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHSUB8(uint32_t x, uint32_t y) { int32_t r, s, t, u; r = ((((x << 24) >> 24) - ((y << 24) >> 24)) >> 1) & 0x000000FF; s = ((((x << 16) >> 24) - ((y << 16) >> 24)) >> 1) & 0x000000FF; t = ((((x << 8) >> 24) - ((y << 8) >> 24)) >> 1) & 0x000000FF; u = ((((x) >> 24) - ((y) >> 24)) >> 1) & 0x000000FF; return ((u << 24) | (t << 16) | (s << 8) | (r)); } /** \brief Dual 16-bit add and subtract with exchange. \details This function enables you to exchange the halfwords of the one operand, then add the high halfwords and subtract the low halfwords, saturating the results to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \param [in] x first operand for the subtraction in the low halfword, and the first operand for the addition in the high halfword. \param [in] y second operand for the subtraction in the high halfword, and the second operand for the addition in the low halfword. \return the saturated subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the saturated addition of the high halfword in the first operand and the low halfword in the second operand, in the high halfword of the return value.\n The returned results are saturated to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \remark res[15:0] = val1[15:0] - val2[31:16] \n res[31:16] = val1[31:16] + val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __QASX(uint32_t x, uint32_t y) { int32_t r, s; r = __SSAT(((((int32_t)x << 16) >> 16) - (((int32_t)y) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((int32_t)x) >> 16) + (((int32_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned saturating addition and subtraction with exchange. \details This function enables you to exchange the halfwords of the second operand and perform one unsigned 16-bit integer addition and one unsigned 16-bit subtraction, saturating the results to the 16-bit unsigned integer range 0 <= x <= 2^16 - 1. \param [in] x first operand for the subtraction in the low halfword, and the first operand for the addition in the high halfword. \param [in] y second operand for the subtraction in the high halfword, and the second operand for the addition in the low halfword. \return the saturated subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the saturated addition of the high halfword in the first operand and the low halfword in the second operand, in the high halfword of the return value.\n The returned results are saturated to the 16-bit unsigned integer range 0 <= x <= 2^16 - 1. \remark res[15:0] = val1[15:0] - val2[31:16] \n res[31:16] = val1[31:16] + val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __UQASX(uint32_t x, uint32_t y) { int32_t r, s; r = __IUSAT((((x << 16) >> 16) - ((y) >> 16)), 16) & 0x0000FFFF; s = __IUSAT((((x) >> 16) + ((y << 16) >> 16)), 16) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit addition and subtraction with exchange. \details It enables you to exchange the halfwords of the second operand, add the high halfwords and subtract the low halfwords. \param [in] x first operand for the subtraction in the low halfword, and the first operand for the addition in the high halfword. \param [in] y second operand for the subtraction in the high halfword, and the second operand for the addition in the low halfword. \return the subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the addition of the high halfword in the first operand and the low halfword in the second operand, in the high halfword of the return value. \remark res[15:0] = val1[15:0] - val2[31:16] \n res[31:16] = val1[31:16] + val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __SASX(uint32_t x, uint32_t y) { int32_t r, s; r = ((((int32_t)x << 16) >> 16) - (((int32_t)y) >> 16)) & (int32_t)0x0000FFFF; s = ((((int32_t)x) >> 16) + (((int32_t)y << 16) >> 16)) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned addition and subtraction with exchange. \details This function enables you to exchange the two halfwords of the second operand, add the high halfwords and subtract the low halfwords. \param [in] x first operand for the subtraction in the low halfword, and the first operand for the addition in the high halfword. \param [in] y second operand for the subtraction in the high halfword, and the second operand for the addition in the low halfword. \return the subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the addition of the high halfword in the first operand and the low halfword in the second operand, in the high halfword of the return value. \remark res[15:0] = val1[15:0] - val2[31:16] \n res[31:16] = val1[31:16] + val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __UASX(uint32_t x, uint32_t y) { int32_t r, s; r = (((x << 16) >> 16) - ((y) >> 16)) & 0x0000FFFF; s = (((x) >> 16) + ((y << 16) >> 16)) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed addition and subtraction with halved results. \details This function enables you to exchange the two halfwords of one operand, perform one signed 16-bit integer addition and one signed 16-bit subtraction, and halve the results. \param [in] x first 16-bit operands. \param [in] y second 16-bit operands. \return the halved subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the halved addition of the low halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] - val2[31:16]) >> 1 \n res[31:16] = (val1[31:16] + val2[15:0]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHASX(uint32_t x, uint32_t y) { int32_t r, s; r = (((((int32_t)x << 16) >> 16) - (((int32_t)y) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((int32_t)x) >> 16) + (((int32_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned addition and subtraction with halved results and exchange. \details This function enables you to exchange the halfwords of the second operand, add the high halfwords and subtract the low halfwords, halving the results. \param [in] x first operand for the subtraction in the low halfword, and the first operand for the addition in the high halfword. \param [in] y second operand for the subtraction in the high halfword, and the second operand for the addition in the low halfword. \return the halved subtraction of the high halfword in the second operand from the low halfword in the first operand, in the low halfword of the return value.\n the halved addition of the low halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] - val2[31:16]) >> 1 \n res[31:16] = (val1[31:16] + val2[15:0]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHASX(uint32_t x, uint32_t y) { int32_t r, s; r = ((((x << 16) >> 16) - ((y) >> 16)) >> 1) & 0x0000FFFF; s = ((((x) >> 16) + ((y << 16) >> 16)) >> 1) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit subtract and add with exchange. \details This function enables you to exchange the halfwords of one operand, then subtract the high halfwords and add the low halfwords, saturating the results to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \param [in] x first operand for the addition in the low halfword, and the first operand for the subtraction in the high halfword. \param [in] y second operand for the addition in the high halfword, and the second operand for the subtraction in the low halfword. \return the saturated addition of the low halfword of the first operand and the high halfword of the second operand, in the low halfword of the return value.\n the saturated subtraction of the low halfword of the second operand from the high halfword of the first operand, in the high halfword of the return value.\n The returned results are saturated to the 16-bit signed integer range -2^15 <= x <= 2^15 - 1. \remark res[15:0] = val1[15:0] + val2[31:16] \n res[31:16] = val1[31:16] - val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __QSAX(uint32_t x, uint32_t y) { int32_t r, s; r = __SSAT(((((int32_t)x << 16) >> 16) + (((int32_t)y) >> 16)), 16) & (int32_t)0x0000FFFF; s = __SSAT(((((int32_t)x) >> 16) - (((int32_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned saturating subtraction and addition with exchange. \details This function enables you to exchange the halfwords of the second operand and perform one unsigned 16-bit integer subtraction and one unsigned 16-bit addition, saturating the results to the 16-bit unsigned integer range 0 <= x <= 2^16 - 1. \param [in] x first operand for the addition in the low halfword, and the first operand for the subtraction in the high halfword. \param [in] y second operand for the addition in the high halfword, and the second operand for the subtraction in the low halfword. \return the saturated addition of the low halfword of the first operand and the high halfword of the second operand, in the low halfword of the return value.\n the saturated subtraction of the low halfword of the second operand from the high halfword of the first operand, in the high halfword of the return value.\n The returned results are saturated to the 16-bit unsigned integer range 0 <= x <= 2^16 - 1. \remark res[15:0] = val1[15:0] + val2[31:16] \n res[31:16] = val1[31:16] - val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __UQSAX(uint32_t x, uint32_t y) { int32_t r, s; r = __IUSAT((((x << 16) >> 16) + ((y) >> 16)), 16) & 0x0000FFFF; s = __IUSAT((((x) >> 16) - ((y << 16) >> 16)), 16) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit unsigned subtract and add with exchange. \details This function enables you to exchange the halfwords of the second operand, subtract the high halfwords and add the low halfwords. \param [in] x first operand for the addition in the low halfword, and the first operand for the subtraction in the high halfword. \param [in] y second operand for the addition in the high halfword, and the second operand for the subtraction in the low halfword. \return the addition of the low halfword of the first operand and the high halfword of the second operand, in the low halfword of the return value.\n the subtraction of the low halfword of the second operand from the high halfword of the first operand, in the high halfword of the return value.\n \remark res[15:0] = val1[15:0] + val2[31:16] \n res[31:16] = val1[31:16] - val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __USAX(uint32_t x, uint32_t y) { int32_t r, s; r = (((x << 16) >> 16) + ((y) >> 16)) & 0x0000FFFF; s = (((x) >> 16) - ((y << 16) >> 16)) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed subtraction and addition with exchange. \details This function enables you to exchange the two halfwords of one operand and perform one 16-bit integer subtraction and one 16-bit addition. \param [in] x first operand for the addition in the low halfword, and the first operand for the subtraction in the high halfword. \param [in] y second operand for the addition in the high halfword, and the second operand for the subtraction in the low halfword. \return the addition of the low halfword of the first operand and the high halfword of the second operand, in the low halfword of the return value.\n the subtraction of the low halfword of the second operand from the high halfword of the first operand, in the high halfword of the return value.\n \remark res[15:0] = val1[15:0] + val2[31:16] \n res[31:16] = val1[31:16] - val2[15:0] */ __ALWAYS_STATIC_INLINE uint32_t __SSAX(uint32_t x, uint32_t y) { int32_t r, s; r = ((((int32_t)x << 16) >> 16) + (((int32_t)y) >> 16)) & (int32_t)0x0000FFFF; s = ((((int32_t)x) >> 16) - (((int32_t)y << 16) >> 16)) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit signed subtraction and addition with halved results. \details This function enables you to exchange the two halfwords of one operand, perform one signed 16-bit integer subtraction and one signed 16-bit addition, and halve the results. \param [in] x first 16-bit operands. \param [in] y second 16-bit operands. \return the halved addition of the low halfword in the first operand and the high halfword in the second operand, in the low halfword of the return value.\n the halved subtraction of the low halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] + val2[31:16]) >> 1 \n res[31:16] = (val1[31:16] - val2[15:0]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __SHSAX(uint32_t x, uint32_t y) { int32_t r, s; r = (((((int32_t)x << 16) >> 16) + (((int32_t)y) >> 16)) >> 1) & (int32_t)0x0000FFFF; s = (((((int32_t)x) >> 16) - (((int32_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF; return ((uint32_t)((s << 16) | (r))); } /** \brief Dual 16-bit unsigned subtraction and addition with halved results and exchange. \details This function enables you to exchange the halfwords of the second operand, subtract the high halfwords and add the low halfwords, halving the results. \param [in] x first operand for the addition in the low halfword, and the first operand for the subtraction in the high halfword. \param [in] y second operand for the addition in the high halfword, and the second operand for the subtraction in the low halfword. \return the halved addition of the low halfword in the first operand and the high halfword in the second operand, in the low halfword of the return value.\n the halved subtraction of the low halfword in the second operand from the high halfword in the first operand, in the high halfword of the return value. \remark res[15:0] = (val1[15:0] + val2[31:16]) >> 1 \n res[31:16] = (val1[31:16] - val2[15:0]) >> 1 */ __ALWAYS_STATIC_INLINE uint32_t __UHSAX(uint32_t x, uint32_t y) { int32_t r, s; r = ((((x << 16) >> 16) + ((y) >> 16)) >> 1) & 0x0000FFFF; s = ((((x) >> 16) - ((y << 16) >> 16)) >> 1) & 0x0000FFFF; return ((s << 16) | (r)); } /** \brief Dual 16-bit signed multiply with exchange returning difference. \details This function enables you to perform two 16-bit signed multiplications, subtracting one of the products from the other. The halfwords of the second operand are exchanged before performing the arithmetic. This produces top * bottom and bottom * top multiplication. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \return the difference of the products of the two 16-bit signed multiplications. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n res[31:0] = p1 - p2 */ __ALWAYS_STATIC_INLINE uint32_t __SMUSDX(uint32_t x, uint32_t y) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)))); } /** \brief Sum of dual 16-bit signed multiply with exchange. \details This function enables you to perform two 16-bit signed multiplications with exchanged halfwords of the second operand, adding the products together. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \return the sum of the products of the two 16-bit signed multiplications with exchanged halfwords of the second operand. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n res[31:0] = p1 + p2 */ __ALWAYS_STATIC_INLINE uint32_t __SMUADX(uint32_t x, uint32_t y) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)))); } /** \brief Saturating add. \details This function enables you to obtain the saturating add of two integers. \param [in] x first summand of the saturating add operation. \param [in] y second summand of the saturating add operation. \return the saturating addition of val1 and val2. \remark res[31:0] = SAT(val1 + SAT(val2)) */ __ALWAYS_STATIC_INLINE int32_t __QADD(int32_t x, int32_t y) { int32_t result; if (y >= 0) { if ((int32_t)((uint32_t)x + (uint32_t)y) >= x) { result = x + y; } else { result = 0x7FFFFFFF; } } else { if ((int32_t)((uint32_t)x + (uint32_t)y) < x) { result = x + y; } else { result = 0x80000000; } } return result; } /** \brief Saturating subtract. \details This function enables you to obtain the saturating add of two integers. \param [in] x first summand of the saturating add operation. \param [in] y second summand of the saturating add operation. \return the saturating addition of val1 and val2. \remark res[31:0] = SAT(val1 - SAT(val2)) */ __ALWAYS_STATIC_INLINE int32_t __QSUB(int32_t x, int32_t y) { int64_t tmp; int32_t result; tmp = (int64_t)x - (int64_t)y; if (tmp > 0x7fffffff) { tmp = 0x7fffffff; } else if (tmp < (-2147483647 - 1)) { tmp = -2147483647 - 1; } result = tmp; return result; } /** \brief Dual 16-bit signed multiply with single 32-bit accumulator. \details This function enables you to perform two signed 16-bit multiplications, adding both results to a 32-bit accumulate operand. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the product of each multiplication added to the accumulate value, as a 32-bit integer. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n res[31:0] = p1 + p2 + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __SMLAD(uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)) + (((int32_t)sum)))); } /** \brief Pre-exchanged dual 16-bit signed multiply with single 32-bit accumulator. \details This function enables you to perform two signed 16-bit multiplications with exchanged halfwords of the second operand, adding both results to a 32-bit accumulate operand. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the product of each multiplication with exchanged halfwords of the second operand added to the accumulate value, as a 32-bit integer. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n res[31:0] = p1 + p2 + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __SMLADX(uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)) + (((int32_t)sum)))); } /** \brief Dual 16-bit signed multiply with exchange subtract with 32-bit accumulate. \details This function enables you to perform two 16-bit signed multiplications, take the difference of the products, subtracting the high halfword product from the low halfword product, and add the difference to a 32-bit accumulate operand. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the difference of the product of each multiplication, added to the accumulate value. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n res[31:0] = p1 - p2 + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __SMLSD(uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)) + (((int32_t)sum)))); } /** \brief Dual 16-bit signed multiply with exchange subtract with 32-bit accumulate. \details This function enables you to exchange the halfwords in the second operand, then perform two 16-bit signed multiplications. The difference of the products is added to a 32-bit accumulate operand. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the difference of the product of each multiplication, added to the accumulate value. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n res[31:0] = p1 - p2 + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __SMLSDX(uint32_t x, uint32_t y, uint32_t sum) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)) + (((int32_t)sum)))); } /** \brief Dual 16-bit signed multiply with single 64-bit accumulator. \details This function enables you to perform two signed 16-bit multiplications, adding both results to a 64-bit accumulate operand. Overflow is only possible as a result of the 64-bit addition. This overflow is not detected if it occurs. Instead, the result wraps around modulo2^64. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the product of each multiplication added to the accumulate value. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n sum = p1 + p2 + val3[63:32][31:0] \n res[63:32] = sum[63:32] \n res[31:0] = sum[31:0] */ __ALWAYS_STATIC_INLINE uint64_t __SMLALD(uint32_t x, uint32_t y, uint64_t sum) { return ((uint64_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)) + (((uint64_t)sum)))); } /** \brief Dual 16-bit signed multiply with exchange with single 64-bit accumulator. \details This function enables you to exchange the halfwords of the second operand, and perform two signed 16-bit multiplications, adding both results to a 64-bit accumulate operand. Overflow is only possible as a result of the 64-bit addition. This overflow is not detected if it occurs. Instead, the result wraps around modulo2^64. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the product of each multiplication added to the accumulate value. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n sum = p1 + p2 + val3[63:32][31:0] \n res[63:32] = sum[63:32] \n res[31:0] = sum[31:0] */ __ALWAYS_STATIC_INLINE uint64_t __SMLALDX(uint32_t x, uint32_t y, uint64_t sum) { return ((uint64_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)) + (((uint64_t)sum)))); } /** \brief dual 16-bit signed multiply subtract with 64-bit accumulate. \details This function It enables you to perform two 16-bit signed multiplications, take the difference of the products, subtracting the high halfword product from the low halfword product, and add the difference to a 64-bit accumulate operand. Overflow cannot occur during the multiplications or the subtraction. Overflow can occur as a result of the 64-bit addition, and this overflow is not detected. Instead, the result wraps round to modulo2^64. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the difference of the product of each multiplication, added to the accumulate value. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n res[63:32][31:0] = p1 - p2 + val3[63:32][31:0] */ __ALWAYS_STATIC_INLINE uint64_t __SMLSLD(uint32_t x, uint32_t y, uint64_t sum) { return ((uint64_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)) + (((uint64_t)sum)))); } /** \brief Dual 16-bit signed multiply with exchange subtract with 64-bit accumulate. \details This function enables you to exchange the halfwords of the second operand, perform two 16-bit multiplications, adding the difference of the products to a 64-bit accumulate operand. Overflow cannot occur during the multiplications or the subtraction. Overflow can occur as a result of the 64-bit addition, and this overflow is not detected. Instead, the result wraps round to modulo2^64. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \param [in] sum accumulate value. \return the difference of the product of each multiplication, added to the accumulate value. \remark p1 = val1[15:0] * val2[31:16] \n p2 = val1[31:16] * val2[15:0] \n res[63:32][31:0] = p1 - p2 + val3[63:32][31:0] */ __ALWAYS_STATIC_INLINE uint64_t __SMLSLDX(uint32_t x, uint32_t y, uint64_t sum) { return ((uint64_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y << 16) >> 16)) + (((uint64_t)sum)))); } /** \brief 32-bit signed multiply with 32-bit truncated accumulator. \details This function enables you to perform a signed 32-bit multiplications, adding the most significant 32 bits of the 64-bit result to a 32-bit accumulate operand. \param [in] x first operand for multiplication. \param [in] y second operand for multiplication. \param [in] sum accumulate value. \return the product of multiplication (most significant 32 bits) is added to the accumulate value, as a 32-bit integer. \remark p = val1 * val2 \n res[31:0] = p[63:32] + val3[31:0] */ __ALWAYS_STATIC_INLINE uint32_t __SMMLA(int32_t x, int32_t y, int32_t sum) { return (uint32_t)((int32_t)((int64_t)((int64_t)x * (int64_t)y) >> 32) + sum); } /** \brief Sum of dual 16-bit signed multiply. \details This function enables you to perform two 16-bit signed multiplications, adding the products together. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \return the sum of the products of the two 16-bit signed multiplications. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n res[31:0] = p1 + p2 */ __ALWAYS_STATIC_INLINE uint32_t __SMUAD(uint32_t x, uint32_t y) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) + ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)))); } /** \brief Dual 16-bit signed multiply returning difference. \details This function enables you to perform two 16-bit signed multiplications, taking the difference of the products by subtracting the high halfword product from the low halfword product. \param [in] x first 16-bit operands for each multiplication. \param [in] y second 16-bit operands for each multiplication. \return the difference of the products of the two 16-bit signed multiplications. \remark p1 = val1[15:0] * val2[15:0] \n p2 = val1[31:16] * val2[31:16] \n res[31:0] = p1 - p2 */ __ALWAYS_STATIC_INLINE uint32_t __SMUSD(uint32_t x, uint32_t y) { return ((uint32_t)(((((int32_t)x << 16) >> 16) * (((int32_t)y << 16) >> 16)) - ((((int32_t)x) >> 16) * (((int32_t)y) >> 16)))); } /** \brief Dual extracted 8-bit to 16-bit signed addition. \details This function enables you to extract two 8-bit values from the second operand (at bit positions [7:0] and [23:16]), sign-extend them to 16-bits each, and add the results to the first operand. \param [in] x values added to the sign-extended to 16-bit values. \param [in] y two 8-bit values to be extracted and sign-extended. \return the addition of val1 and val2, where the 8-bit values in val2[7:0] and val2[23:16] have been extracted and sign-extended prior to the addition. \remark res[15:0] = val1[15:0] + SignExtended(val2[7:0]) \n res[31:16] = val1[31:16] + SignExtended(val2[23:16]) */ __ALWAYS_STATIC_INLINE uint32_t __SXTAB16(uint32_t x, uint32_t y) { return ((uint32_t)((((((int32_t)y << 24) >> 24) + (((int32_t)x << 16) >> 16)) & (int32_t)0x0000FFFF) | (((((int32_t)y << 8) >> 8) + (((int32_t)x >> 16) << 16)) & (int32_t)0xFFFF0000))); } /** \brief Extracted 16-bit to 32-bit unsigned addition. \details This function enables you to extract two 8-bit values from one operand, zero-extend them to 16 bits each, and add the results to two 16-bit values from another operand. \param [in] x values added to the zero-extended to 16-bit values. \param [in] y two 8-bit values to be extracted and zero-extended. \return the addition of val1 and val2, where the 8-bit values in val2[7:0] and val2[23:16] have been extracted and zero-extended prior to the addition. \remark res[15:0] = ZeroExt(val2[7:0] to 16 bits) + val1[15:0] \n res[31:16] = ZeroExt(val2[31:16] to 16 bits) + val1[31:16] */ __ALWAYS_STATIC_INLINE uint32_t __UXTAB16(uint32_t x, uint32_t y) { return ((uint32_t)(((((y << 24) >> 24) + ((x << 16) >> 16)) & 0x0000FFFF) | ((((y << 8) >> 8) + ((x >> 16) << 16)) & 0xFFFF0000))); } /** \brief Dual extract 8-bits and sign extend each to 16-bits. \details This function enables you to extract two 8-bit values from an operand and sign-extend them to 16 bits each. \param [in] x two 8-bit values in val[7:0] and val[23:16] to be sign-extended. \return the 8-bit values sign-extended to 16-bit values.\n sign-extended value of val[7:0] in the low halfword of the return value.\n sign-extended value of val[23:16] in the high halfword of the return value. \remark res[15:0] = SignExtended(val[7:0]) \n res[31:16] = SignExtended(val[23:16]) */ __ALWAYS_STATIC_INLINE uint32_t __SXTB16(uint32_t x) { return ((uint32_t)(((((int32_t)x << 24) >> 24) & (int32_t)0x0000FFFF) | ((((int32_t)x << 8) >> 8) & (int32_t)0xFFFF0000))); } /** \brief Dual extract 8-bits and zero-extend to 16-bits. \details This function enables you to extract two 8-bit values from an operand and zero-extend them to 16 bits each. \param [in] x two 8-bit values in val[7:0] and val[23:16] to be zero-extended. \return the 8-bit values sign-extended to 16-bit values.\n sign-extended value of val[7:0] in the low halfword of the return value.\n sign-extended value of val[23:16] in the high halfword of the return value. \remark res[15:0] = SignExtended(val[7:0]) \n res[31:16] = SignExtended(val[23:16]) */ __ALWAYS_STATIC_INLINE uint32_t __UXTB16(uint32_t x) { return ((uint32_t)((((x << 24) >> 24) & 0x0000FFFF) | (((x << 8) >> 8) & 0xFFFF0000))); } #endif /* _CSI_RV32_GCC_H_ */
YifuLiu/AliOS-Things
hardware/board/c906/csi_core/include/csi_rv64_gcc.h
C
apache-2.0
106,704
#include "board.h" #include <k_api.h> static ktask_t *g_main_task; #define OS_MAIN_TASK_STACK (2*1024) #define OS_MAIN_TASK_PRI 32 extern int aos_maintask(void); int main(void) { krhino_init(); /*main task to run */ krhino_task_dyn_create(&g_main_task, "main_task", 0, OS_MAIN_TASK_PRI, 0, OS_MAIN_TASK_STACK, (task_entry_t)aos_maintask, 1); /*kernel start schedule!*/ krhino_start(); while (1) { krhino_task_sleep(100); } /*never run here*/ return 0; }
YifuLiu/AliOS-Things
hardware/board/c906/startup/startup_c.c
C
apache-2.0
505
#include <k_api.h> #include "cmsis.h" #include "cmsis_os.h" #include "hal_timer.h" #include "hal_trace.h" #include "hal_gpio.h" #include "aos/hal/uart.h" #if (RHINO_CONFIG_HW_COUNT > 0) #include "haas1000.h" #endif #define SYSTICK_USE_FASTTIMER uart_dev_t uart_0; extern void haas_wifi_init(); #if (RHINO_CONFIG_HW_COUNT > 0) void soc_hw_timer_init(void) { /* Enable DWT */ CoreDebug->DEMCR |= ((1 << CoreDebug_DEMCR_TRCENA_Pos)); DWT->CYCCNT = 0; /* Enable CPU cycle counter */ DWT->CTRL |= ((1 << DWT_CTRL_CYCCNTENA_Pos)); } hr_timer_t soc_hr_hw_cnt_get(void) { return DWT->CYCCNT; } uint64_t soc_hr_hw_freq_get(void) { return hal_sys_timer_calc_cpu_freq(5, 0); } lr_timer_t soc_lr_hw_cnt_get(void) { return (lr_timer_t)hal_sys_timer_get(); } float soc_hr_hw_freq_mhz(void) { return (hal_sys_timer_calc_cpu_freq(5, 0)/1000000); } #endif /* RHINO_CONFIG_HW_COUNT */ #if (RHINO_CONFIG_INTRPT_STACK_OVF_CHECK > 0) void soc_intrpt_stack_ovf_check(void) { } #endif #if (RHINO_CONFIG_DYNTICKLESS > 0) void soc_tick_interrupt_set(tick_t next_ticks,tick_t elapsed_ticks) { } tick_t soc_elapsed_ticks_get(void) { return 0; } #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) #define RHINO_HEAP_BLK_SIZE (0x680000) __SRAM_EXT_BSS uint32_t heap_blk0[RHINO_HEAP_BLK_SIZE/sizeof(uint32_t)] = {0}; //__SRAM_EXT_BSS uint32_t heap_blk1[RHINO_HEAP_BLK_SIZE/sizeof(uint32_t)] = {0}; k_mm_region_t g_mm_region[] = { {(uint8_t *)heap_blk0, RHINO_HEAP_BLK_SIZE} //{(uint8_t *)heap_blk1, RHINO_HEAP_BLK_SIZE} }; int g_region_num = sizeof(g_mm_region) / sizeof(k_mm_region_t); void soc_sys_mem_init(void) { } #endif void soc_err_proc(kstat_t err) { } krhino_err_proc_t g_err_proc = soc_err_proc; #define OS_CLOCK OS_CLOCK_NOMINAL #define SYS_TICK_LOAD ((uint32_t)((((float)OS_CLOCK*(float)RHINO_CONFIG_TICKS_PER_SECOND))/(float)1E6+0.5f)) __STATIC_INLINE uint32_t SysTick_Config_Alt(uint32_t ticks) { if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); /* Reload value impossible */ } SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */ NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */ SysTick->VAL = 0UL; /* Load the SysTick Counter Value */ SysTick->CTRL = SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */ return (0UL); /* Function successful */ } void SysTick_Handler(void) { krhino_intrpt_enter(); krhino_tick_proc(); krhino_intrpt_exit(); } void soc_systick_init(void) { #ifdef SYSTICK_USE_FASTTIMER hal_systick_timer_open(RHINO_CONFIG_TICKS_PER_SECOND, SysTick_Handler); #else SysTick_Config_Alt(SYS_TICK_LOAD); #endif } void soc_systick_start(void) { #ifdef SYSTICK_USE_FASTTIMER hal_systick_timer_start(); #else SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; #endif } void soc_systick_stop(void) { #ifdef SYSTICK_USE_FASTTIMER hal_systick_timer_stop(); #else SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; #endif } void board_stduart_init() { uart_0.port = 0; uart_0.config.baud_rate = 1500000; uart_0.config.data_width = DATA_WIDTH_8BIT; uart_0.config.flow_control = FLOW_CONTROL_DISABLED; uart_0.config.mode = MODE_TX_RX; uart_0.config.parity = NO_PARITY; uart_0.config.stop_bits = STOP_BITS_1; hal_uart_init(&uart_0); } void board_dma_init() { } void board_gpio_init() { } void board_tick_init() { } void board_kinit_init() { } void board_flash_init() { } void board_network_init() { haas_wifi_init(); }
YifuLiu/AliOS-Things
hardware/board/haas100/config/board.c
C
apache-2.0
3,899
#ifndef BOARD_H #define BOARD_H #if (CONFIG_A7_DSP_ENABLE == 1) #define DEBUG_LASTWORD_RAM_ADDR 0x20166000 #else #define DEBUG_LASTWORD_RAM_ADDR 0x201e6000 #endif void soc_systick_start(void); void soc_systick_stop(void); #endif /* BOARD_H */
YifuLiu/AliOS-Things
hardware/board/haas100/config/board.h
C
apache-2.0
246
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <k_api.h> #include "hal_trace.h" #include "hal_gpio.h" #include "hal_sleep.h" #include "hal_timer.h" #include "hwtimer_list.h" #include "board.h" #include "watchdog.h" #ifdef AOS_COMP_OSAL_POSIX #include "posix/pthread.h" extern pthread_key_list_t pthread_key_list_head; #endif #if RHINO_CONFIG_USER_HOOK extern const k_mm_region_t g_mm_region[]; extern int g_region_num; static int mem_in_heap(uint32_t addr) { int i; for(i = 0; i < g_region_num; i++){ if(addr > (uint32_t)g_mm_region[i].start && addr < (uint32_t)g_mm_region[i].start + g_mm_region[i].len){ return 1; } } return 0; } void krhino_tick_hook(void) { static unsigned int idx = 0; if((idx % (RHINO_CONFIG_TICKS_PER_SECOND / 2) ) == 0) { watchdog_feeddog(); } idx ++; } HWTIMER_ID krhino_sleep_timer; void krhino_sleep(void) { hal_sleep_enter_sleep(); } static int idle_sleep = 1; // swd will set it void krhino_idle_hook_onoff(int onoff) { idle_sleep = onoff; } void krhino_idle_hook(void) { uint32_t suspend_time; enum E_HWTIMER_T ret; uint32_t sleep_ms; if (idle_sleep == 0) return ; if ((hal_sleep_light_sleep() == HAL_SLEEP_STATUS_DEEP)) { tick_t tick = krhino_next_sleep_ticks_get(); sleep_ms = krhino_ticks_to_ms(tick); if (sleep_ms > 60*1000) sleep_ms = 60*1000; ret = hwtimer_start(krhino_sleep_timer, MS_TO_HWTICKS(sleep_ms)); if (ret == E_HWTIMER_OK) { soc_systick_stop(); suspend_time = hal_sys_timer_get(); krhino_sleep(); hwtimer_stop(krhino_sleep_timer); suspend_time = TICKS_TO_MS(hal_sys_timer_get() - suspend_time); soc_systick_start(); tick_list_update(krhino_ms_to_ticks(suspend_time)); } } } void aos_trace_crash_notify() { abort(); } void krhino_idle_pre_hook(void) { hal_trace_crash_dump_register(HAL_TRACE_CRASH_DUMP_MODULE_SYS, aos_trace_crash_notify); krhino_sleep_timer = hwtimer_alloc(NULL, NULL); ASSERT(krhino_sleep_timer, "IdleTask: Failed to alloc sleep timer"); } void krhino_start_hook(void) { } void krhino_task_create_hook(ktask_t *task) { } void krhino_task_del_hook(ktask_t *task, res_free_t *arg) { /*free task->task_sem_obj*/ void * task_sem = task->task_sem_obj; g_sched_lock[cpu_cur_get()]++; if(task_sem) { krhino_task_sem_del(task); if(mem_in_heap((uint32_t)task_sem)){ aos_free(task_sem); } task->task_sem_obj = NULL; } g_sched_lock[cpu_cur_get()]--; return; } void krhino_init_hook(void) { } void krhino_task_switch_hook(ktask_t *orgin, ktask_t *dest) { } void krhino_mm_alloc_hook(void *mem, size_t size) { } void krhino_task_abort_hook(ktask_t *task) { } #endif
YifuLiu/AliOS-Things
hardware/board/haas100/config/k_config.c
C
apache-2.0
2,898
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_CONFIG_H #define K_CONFIG_H /* kernel feature conf */ #ifndef RHINO_CONFIG_SEM #define RHINO_CONFIG_SEM 1 #endif #ifndef RHINO_CONFIG_QUEUE #define RHINO_CONFIG_QUEUE 1 #endif #ifndef RHINO_CONFIG_TASK_SEM #define RHINO_CONFIG_TASK_SEM 1 #endif #ifndef RHINO_CONFIG_EVENT_FLAG #define RHINO_CONFIG_EVENT_FLAG 1 #endif #ifndef RHINO_CONFIG_TIMER #define RHINO_CONFIG_TIMER 1 #endif #ifndef RHINO_CONFIG_BUF_QUEUE #define RHINO_CONFIG_BUF_QUEUE 1 #endif /* kernel task conf */ #ifndef RHINO_CONFIG_TASK_INFO #define RHINO_CONFIG_TASK_INFO 1 #endif #ifndef RHINO_CONFIG_TASK_DEL #define RHINO_CONFIG_TASK_DEL 1 #endif #ifndef RHINO_CONFIG_TASK_STACK_OVF_CHECK #define RHINO_CONFIG_TASK_STACK_OVF_CHECK 1 #endif #ifndef RHINO_CONFIG_SCHED_RR #define RHINO_CONFIG_SCHED_RR 1 #endif #ifndef RHINO_CONFIG_TIME_SLICE_DEFAULT #define RHINO_CONFIG_TIME_SLICE_DEFAULT 50 #endif #ifndef RHINO_CONFIG_PRI_MAX #define RHINO_CONFIG_PRI_MAX 62 #endif #ifndef RHINO_CONFIG_USER_PRI_MAX #define RHINO_CONFIG_USER_PRI_MAX (RHINO_CONFIG_PRI_MAX - 2) #endif /* kernel workqueue conf */ //#ifndef RHINO_CONFIG_WORKQUEUE #define RHINO_CONFIG_WORKQUEUE 1 //#endif #ifndef RHINO_CONFIG_WORKQUEUE_STACK_SIZE #define RHINO_CONFIG_WORKQUEUE_STACK_SIZE 768 #endif /* kernel timer&tick conf */ #ifndef RHINO_CONFIG_TICKS_PER_SECOND #define RHINO_CONFIG_TICKS_PER_SECOND 1000 #endif /*must reserve enough stack size for timer cb will consume*/ #ifndef RHINO_CONFIG_TIMER_TASK_STACK_SIZE #define RHINO_CONFIG_TIMER_TASK_STACK_SIZE 2048 #endif #ifndef RHINO_CONFIG_TIMER_TASK_PRI #define RHINO_CONFIG_TIMER_TASK_PRI 5 #endif /* kernel intrpt conf */ #ifndef RHINO_CONFIG_INTRPT_STACK_OVF_CHECK #define RHINO_CONFIG_INTRPT_STACK_OVF_CHECK 0 #endif /* kernel dyn alloc conf */ #ifndef RHINO_CONFIG_KOBJ_DYN_ALLOC #define RHINO_CONFIG_KOBJ_DYN_ALLOC 1 #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) #ifndef RHINO_CONFIG_K_DYN_TASK_STACK #define RHINO_CONFIG_K_DYN_TASK_STACK 256 #endif #ifndef RHINO_CONFIG_K_DYN_MEM_TASK_PRI #define RHINO_CONFIG_K_DYN_MEM_TASK_PRI 6 #endif #endif /* kernel idle conf */ #ifndef RHINO_CONFIG_IDLE_TASK_STACK_SIZE #define RHINO_CONFIG_IDLE_TASK_STACK_SIZE 1024 #endif /* kernel hook conf */ #ifndef RHINO_CONFIG_USER_HOOK #define RHINO_CONFIG_USER_HOOK 1 #endif #ifndef RHINO_CONFIG_CPU_NUM #define RHINO_CONFIG_CPU_NUM 1 #endif /*task user info index start*/ #ifndef RHINO_CONFIG_TASK_INFO_NUM #define RHINO_CONFIG_TASK_INFO_NUM 5 #endif #ifndef PTHREAD_CONFIG_USER_INFO_POS #define PTHREAD_CONFIG_USER_INFO_POS 0 #endif #ifndef RHINO_TASK_HOOK_USER_INFO_POS #define RHINO_TASK_HOOK_USER_INFO_POS 1 #endif #ifndef RHINO_CLI_CONSOLE_USER_INFO_POS #define RHINO_CLI_CONSOLE_USER_INFO_POS 2 #endif #ifndef RHINO_ERRNO_USER_INFO_POS #define RHINO_ERRNO_USER_INFO_POS 3 #endif /*task user info index end*/ #ifndef RHINO_CONFIG_SYS_STATS #define RHINO_CONFIG_SYS_STATS 1 #endif #ifndef RHINO_CONFIG_HW_COUNT #define RHINO_CONFIG_HW_COUNT 1 #endif #ifndef RHINO_CONFIG_MM_TRACE_LVL #define RHINO_CONFIG_MM_TRACE_LVL 0 #endif #ifndef RHINO_CONFIG_CLI_AS_NMI #define RHINO_CONFIG_CLI_AS_NMI 0 #endif #if (RHINO_CONFIG_CLI_AS_NMI > 0) #ifndef RHINO_CONFIG_NMI_OFFSET #define RHINO_CONFIG_NMI_OFFSET 40 #endif #endif #endif /* K_CONFIG_H */
YifuLiu/AliOS-Things
hardware/board/haas100/config/k_config.h
C
apache-2.0
3,701
#ifndef NET_CONFIG_H #define NET_CONFIG_H #endif
YifuLiu/AliOS-Things
hardware/board/haas100/config/net_config.h
C
apache-2.0
51
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <aos/flashpart_core.h> #include <aos/hal/flash.h> static int flash_partitions_init(void) { static aos_flashpart_t partitions[] = { { .dev = { .id = HAL_PARTITION_BOOTLOADER, }, .flash_id = 0, .block_start = 0x0, .block_count = 0x10, }, { .dev = { .id = HAL_PARTITION_PARAMETER_3, }, .flash_id = 0, .block_start = 0x10, .block_count = 0x2, }, { .dev = { .id = HAL_PARTITION_BOOT1, }, .flash_id = 0, .block_start = 0x12, .block_count = 0x18, }, { .dev = { .id = HAL_PARTITION_APPLICATION, }, .flash_id = 0, .block_start = 0x2A, .block_count = 0x578, }, { .dev = { .id = HAL_PARTITION_BOOT1_REDUND, }, .flash_id = 0, .block_start = 0x5A2, .block_count = 0x18, }, { .dev = { .id = HAL_PARTITION_OTA_TEMP, }, .flash_id = 0, .block_start = 0x5BA, .block_count = 0x578, }, { .dev = { .id = HAL_PARTITION_LITTLEFS, }, .flash_id = 0, .block_start = 0xB32, .block_count = 0x4AE, }, { .dev = { .id = HAL_PARTITION_PARAMETER_4, }, .flash_id = 0, .block_start = 0xFE0, .block_count = 0x10, }, { .dev = { .id = HAL_PARTITION_PARAMETER_1, }, .flash_id = 0, .block_start = 0xFF0, .block_count = 0x1, }, { .dev = { .id = HAL_PARTITION_PARAMETER_2, }, .flash_id = 0, .block_start = 0xFF1, .block_count = 0xD, }, { .dev = { .id = HAL_PARTITION_ENV, }, .flash_id = 0, .block_start = 0xFFE, .block_count = 0x2, }, { .dev = { .id = HAL_PARTITION_ENV_REDUND, }, .flash_id = 0, .block_start = 0xFFE, .block_count = 0x2, }, }; for (size_t i = 0; i < sizeof(partitions) / sizeof(partitions[0]); i++) { int ret; ret = aos_flashpart_register(&partitions[i]); if (ret) { for (size_t j = 0; j < i; j++) (void)aos_flashpart_unregister(partitions[j].dev.id); return ret; } } return 0; } LEVEL1_DRIVER_ENTRY(flash_partitions_init)
YifuLiu/AliOS-Things
hardware/board/haas100/config/partition_conf.c
C
apache-2.0
2,637
/* Note: this is legacy partition definition, and will be removed with flash hal apis in future.*/ #include <stddef.h> #include "aos/hal/flash.h" /* Logic partition on flash devices */ const hal_logic_partition_t hal_partitions[] = { [HAL_PARTITION_BOOTLOADER] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot1", .partition_start_addr = 0x0, .partition_length = 0x10000, //64k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_PARAMETER_3] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot_info", .partition_start_addr = 0x10000, //boot information need protect .partition_length = 0x2000, //8k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_BOOT1] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot2A", .partition_start_addr = 0x12000, .partition_length = 0x18000, //64k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_APPLICATION] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "RTOSA", .partition_start_addr = 0x2A000, .partition_length = 0x578000, //5.5M bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_BOOT1_REDUND] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot2B", .partition_start_addr = 0x5A2000, .partition_length = 0x18000, //64k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_OTA_TEMP] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "RTOSB", .partition_start_addr = 0x5BA000, .partition_length = 0x578000, //5.5M bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_LITTLEFS] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "littleFS", //for little fs module .partition_start_addr = 0xB32000, .partition_length = 0x4AE000, .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_PARAMETER_4] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot1_sec", .partition_start_addr = 0xFE0000, .partition_length = 0x10000, //64k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_PARAMETER_1] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "boot2_info", .partition_start_addr = 0xFF0000, .partition_length = 0x1000, //4k bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_PARAMETER_2] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "KV", //for KV module .partition_start_addr = 0xFF1000, .partition_length = 0xD000, //K bytes .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_ENV] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "factory", .partition_start_addr = 0xFFE000, .partition_length = 0x2000, .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, [HAL_PARTITION_ENV_REDUND] = { .partition_owner = HAL_FLASH_EMBEDDED, .partition_description = "factory_backup", .partition_start_addr = 0xFFE000, .partition_length = 0x2000, .partition_options = PAR_OPT_READ_EN | PAR_OPT_WRITE_EN, }, }; /* Declare a constant to indicate the defined partitions amount */ const size_t hal_partitions_amount = (sizeof(hal_partitions)/sizeof(hal_logic_partition_t));
YifuLiu/AliOS-Things
hardware/board/haas100/config/partition_conf_legacy.c
C
apache-2.0
4,108
/* * Copyright (C) 2020-2023 Alibaba Group Holding Limited */ #ifndef _SAL_CONFIG_MODULE #define _SAL_CONFIG_MODULE #include "aos/hal/spi.h" typedef struct { spi_dev_t spi_dev; } sal_device_config_t; #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/atcmd_config_module.h
C
apache-2.0
227
/* * Copyright (C) 2020-2022 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include "aos/kernel.h" #include "sys/socket.h" #include <uservice/uservice.h> #include <uservice/eventid.h> #include "ulog/ulog.h" #include "ch395_spi.h" #include "ch395_cmd.h" #define TAG "ch395_cmd" #define SPI_TIME_OUT 1000 #define TCP_MSS_MAX_VALUE 1460 #define TCP_MSS_MIN_VALUE 60 #define TCP_TTL_MAX_VALUE 128 #define MAX_BUF_NUM 48 #define IPV4_ADDR_STR_LEN 15 static int8_t guc_module_initflag = 0; static spi_dev_t g_st_spi_info = {0}; static aos_mutex_t gst_spi_op_mutex = {0}; int32_t ch395_str_to_ip4addr(int8_t *str, uint8_t *paddr) { uint32_t i = 0; uint32_t len = 0; uint32_t ipaddr = 0; if (NULL == str || NULL == paddr) { LOGE(TAG, "%s %d Invalid input", __func__, __LINE__); return -1; } len = strlen(str); if (len > IPV4_ADDR_STR_LEN) { LOGE(TAG, "%s %d Invalid input %s ", __func__, __LINE__, str); return -1; } ipaddr = ipaddr_addr(str); if (ipaddr == -1) { LOGE(TAG, "%s %d Invalid ip str %s", __func__, __LINE__, str); return -1; } ipaddr = ntohl(ipaddr); paddr[0] = (uint8_t)((ipaddr & 0xFF000000) >> 24); paddr[1] = (uint8_t)((ipaddr & 0x00FF0000) >> 16); paddr[2] = (uint8_t)((ipaddr & 0x0000FF00) >> 8); paddr[3] = (uint8_t)(ipaddr & 0x000000FF); return 0; } int32_t ch395_module_init(spi_dev_t *pstspiinfo) { int32_t ret = 0; if (NULL == pstspiinfo) { LOGE(TAG, "%s %d invalid input \r\n", __FILE__, __LINE__); return -1; } if (guc_module_initflag) { return 0; } ret = hal_ch395_spi_init(pstspiinfo); if (ret) { LOGE(TAG, "spi init fail 0x%x, port %d, spi role %d, firstbit %d, work_mode %d, freq %d", ret, pstspiinfo->port, pstspiinfo->config.role, pstspiinfo->config.firstbit, pstspiinfo->config.mode, pstspiinfo->config.freq); return -1; } ret = aos_mutex_new(&gst_spi_op_mutex); if (ret) { LOGE(TAG, "Failed to new a mutex 0x%x", ret); return -1; } memset(&g_st_spi_info, 0, sizeof(g_st_spi_info)); memcpy(&g_st_spi_info, pstspiinfo, sizeof(g_st_spi_info)); guc_module_initflag = 1; return 0; } static int32_t ch395_spi_data_write(uint8_t *pdata, uint32_t len) { int32_t ret = 0; if (NULL == pdata || 0 == len) { LOGE(TAG, "invalid input"); return -1; } if (guc_module_initflag == 0) { LOGE(TAG, "ch395 spi bus haven't init yet"); return -1; } aos_mutex_lock(&gst_spi_op_mutex, AOS_WAIT_FOREVER); ret = hal_spi_send_ch395(&g_st_spi_info, pdata, len, SPI_TIME_OUT); aos_mutex_unlock(&gst_spi_op_mutex); if (ret) { LOGE(TAG, "spi cmd write fail %d", ret); return -1; } return 0; } static int32_t ch395_spi_send_and_recv(uint8_t *txdata, uint32_t txlen, uint8_t *rxdata, uint32_t rxlen) { int32_t ret = 0; uint32_t i = 0; if (NULL == txdata || 0 == txlen || NULL == rxdata || 0 == rxlen) { LOGE(TAG, "invalid input"); return -1; } if (guc_module_initflag == 0) { LOGE(TAG, "ch395 spi bus haven't init yet"); return -1; } aos_mutex_lock(&gst_spi_op_mutex, AOS_WAIT_FOREVER); ret = hal_spi_send_and_recv_ch395_normal(&g_st_spi_info, txdata, txlen, rxdata, rxlen, SPI_TIME_OUT); aos_mutex_unlock(&gst_spi_op_mutex); if (ret) { LOGE(TAG, "===hal spi send and recv 0x%x len %d fail ret 0x%x==\r\n", txdata[0], txlen, ret); return -1; } return 0; } static int32_t ch395_spi_cmd_query(uint8_t cmd, uint8_t *pvalue) { int32_t ret = 0; uint8_t data = 0; if (NULL == pvalue) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_send_and_recv(&cmd, sizeof(cmd), &data, sizeof(data)); if (ret) { LOGE(TAG, "spi send and recv fail %d, cmd %d", ret, cmd); return -1; } *pvalue = data; return 0; } static int32_t ch395_get_cmd_status(uint8_t *pstatus) { int32_t ret = 0; uint8_t cmd = CMD01_GET_CMD_STATUS; uint8_t value = 0; if (NULL == pstatus) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_cmd_query(cmd, &value); if (ret) { LOGE(TAG, "get cmd status fail %d ret", cmd); return -1; } *pstatus = value; return 0; } int32_t ch395_chip_exist_check(void) { uint8_t cmd[2] = {CMD11_CHECK_EXIST, 0x5A}; uint8_t readdata = 0; int32_t ret = 0; if (guc_module_initflag == 0) { LOGE(TAG, "ch395 spi bus haven't init yet"); return -1; } aos_mutex_lock(&gst_spi_op_mutex, AOS_WAIT_FOREVER); ret = hal_spi_send_and_recv_ch395_exist(&g_st_spi_info, cmd, sizeof(cmd), &readdata, sizeof(readdata), SPI_TIME_OUT); aos_mutex_unlock(&gst_spi_op_mutex); if (ret) { LOGE(TAG, "===hal spi send and recv 0x%x len %d fail ret 0x%x==\r\n", cmd[0], sizeof(cmd), ret); return -1; } if (readdata != 0xA5) { LOGE(TAG, "testdata 0x%x, readdata 0x%x ,chip not exist", cmd[1], readdata); return -1; } return 0; } int32_t ch395_chip_reset(void) { int32_t ret = 0; uint8_t cmd = CMD00_RESET_ALL; ret = ch395_spi_data_write(&cmd, sizeof(cmd)); if (ret) { LOGE(TAG, "send chip reset cmd fail "); return -1; } /*wait 50ms ,make sure reset operation can finish*/ aos_msleep(50); return 0; } int32_t ch395_enter_sleep(void) { int32_t ret = 0; uint8_t cmd = CMD00_ENTER_SLEEP; ret = ch395_spi_data_write(&cmd, sizeof(cmd)); if (ret) { LOGE(TAG, "send chip reset cmd fail "); return -1; } /*when exite sleep mode should cost several ms (less than 10ms)*/ return 0; } int32_t ch395_get_version(uint8_t *pchip_ver, uint8_t *pfirm_ver) { int32_t ret = 0; uint8_t ver = 0; if (NULL == pchip_ver || NULL == pfirm_ver) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_cmd_query(CMD01_GET_IC_VER, &ver); if (ret) { LOGE(TAG, "Fail to get version cmd 0x%x ret %d", CMD01_GET_IC_VER, ret); return -1; } *pfirm_ver = ver & 0x0F; *pchip_ver = (ver & 0xF0) >> 4; return 0; } int32_t ch395_set_phy_state(uint8_t state) { int32_t ret = 0; uint8_t data[2] = {0}; if (state != PHY_DISCONN && state != PHY_10M_FLL && state != PHY_10M_HALF && state != PHY_100M_FLL && state != PHY_100M_HALF && state != PHY_AUTO) { LOGE(TAG, "Invalid input 0x%x ", state); return -1; } data[0] = CMD10_SET_PHY; data[1] = state; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "send phy state fail cmd 0x%x state 0x%x", data[0], data[1]); return -1; } return 0; } int32_t ch395_get_phy_status(uint8_t *pstate) { int32_t ret = 0; if (NULL == pstate) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_cmd_query(CMD01_GET_PHY_STATUS, pstate); if (ret) { LOGE(TAG, "Fail to get phy status %d", ret); return -1; } return 0; } int32_t ch395_set_mac_addr(uint8_t mac[6]) { int32_t ret = 0; uint8_t data[7] = {0}; data[0] = CMD60_SET_MAC_ADDR; memcpy(&data[1], mac, 6); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write cmd 0x%x and mac fail ,ret %d", CMD60_SET_MAC_ADDR, ret); return -1; } /*it will save mac info at eerpom , it will take 100 ms*/ aos_msleep(100); return 0; } int32_t ch395_get_mac_addr(uint8_t mac[6]) { int32_t ret = 0; uint8_t cmd = CMD06_GET_MAC_ADDR; ret = ch395_spi_send_and_recv(&cmd, sizeof(cmd), mac, 6); if (ret) { LOGE(TAG, "spi send and recv fail %d, recv data len %d", ret, 6); return -1; } return 0; } int32_t ch395_set_mac_filt(uint8_t filt_type, uint32_t hash0, uint32_t hash1) { int32_t ret = 0; uint8_t data[10] = {0}; data[0] = CMD90_SET_MAC_FILT; data[1] = filt_type; data[2] = (uint8_t)hash0; data[3] = (uint8_t)(hash0 >> 8); data[4] = (uint8_t)(hash0 >> 16); data[5] = (uint8_t)(hash0 >> 24); data[6] = (uint8_t)hash1; data[7] = (uint8_t)(hash1 >> 8); data[8] = (uint8_t)(hash1 >> 16); data[9] = (uint8_t)(hash1 >> 24); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "fail to send mac filt data"); return -1; } return 0; } int32_t ch395_set_ip_addr(uint8_t ip[4]) { int32_t ret = 0; uint8_t data[5] = {0}; data[0] = CMD40_SET_IP_ADDR; memcpy(&data[1], ip, 4); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write ip addr ret %d", ret); return -1; } return 0; } int32_t ch395_set_gw_ip_addr(uint8_t ip[4]) { int32_t ret = 0; uint8_t data[5] = {0}; data[0] = CMD40_SET_GWIP_ADDR; memcpy(&data[1], ip, 4); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write gateway ip addr ret %d", ret); return -1; } return 0; } int32_t ch395_set_ip_mask_addr(uint8_t ip[4]) { int32_t ret = 0; uint8_t data[5] = {0}; data[0] = CMD40_SET_MASK_ADDR; memcpy(&data[1], ip, 4); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write mask ip addr ret %d", ret); return -1; } return 0; } int32_t ch395_get_global_int_status(uint8_t *pstatus) { int32_t ret = 0; if (NULL == pstatus) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_cmd_query(CMD01_GET_GLOB_INT_STATUS, pstatus); if (ret) { LOGE(TAG, "Fail to get interrup status"); return -1; } return 0; } int32_t ch395_get_global_all_int_status(uint16_t *pstatus) { int32_t ret = 0; uint8_t recvdata[2] = {0}; uint8_t cmd = CMD02_GET_GLOB_INT_STATUS_ALL; if (NULL == pstatus) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_send_and_recv(&cmd, sizeof(cmd), (uint8_t *)recvdata, sizeof(recvdata)); if (ret) { LOGE(TAG, "spi send and recv fail %d", ret); return -1; } *pstatus = (uint16_t)(recvdata[1] << 8) + recvdata[0]; return 0; } /*only works in tcp mode, biggest value is 20 */ int32_t ch395_tcp_retran_count_set(uint8_t count) { int32_t ret = 0; uint8_t data[2] = {0}; data[1] = count; if (data[1] > 20) { LOGE(TAG, "Invalid input %d , set it to 20", data[1]); data[1] = 20; } data[0] = CMD10_SET_RETRAN_COUNT; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to set retran data"); return -1; } return 0; } /*period time is ms */ int32_t ch395_tcp_retry_period_set(uint16_t time) { int32_t ret = 0; uint8_t data[3] = {0}; if (time > 1000) { LOGE(TAG, "Invalid input %d ", time); return -1; } data[0] = CMD20_SET_RETRAN_PERIOD; data[1] = (uint8_t)time; data[2] = (uint8_t)(time >> 8); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to set retran data"); return -1; } return 0; } int32_t ch395_get_remote_ip_port(uint8_t sock, uint8_t ip[4], uint16_t *pport) { int32_t ret = 0; uint8_t send_data[2] = {0}; uint8_t recv_data[6] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pport) { LOGE(TAG, "Invalid input sock %d pport %p ", sock, pport); return -1; } send_data[0] = CMD06_GET_REMOT_IPP_SN; send_data[1] = sock; ret = ch395_spi_send_and_recv(send_data, sizeof(send_data), recv_data, sizeof(recv_data)); if (ret) { LOGE(TAG, "Fail to get sock %d remote port and ip", sock); return -1; } memcpy(ip, recv_data, 4); *pport = recv_data[4] + (uint16_t)(recv_data[5] << 8); return 0; } int32_t ch395_clear_sock_recv_buff(uint8_t sock) { int32_t ret = 0; uint8_t data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD10_CLEAR_RECV_BUF_SN; data[1] = sock; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_get_sock_tcp_status(uint8_t sock, uint8_t *psock_status, uint8_t *ptcp_status) { int32_t ret = 0; uint8_t data[2] = {0}; uint8_t recv_data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == psock_status || NULL == ptcp_status) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD12_GET_SOCKET_STATUS_SN; data[1] = sock; ret = ch395_spi_send_and_recv(data, sizeof(data), recv_data, sizeof(recv_data)); if (ret) { LOGE(TAG, "Fail to get sock %d tcp status", sock); return -1; } *psock_status = recv_data[0]; *ptcp_status = recv_data[1]; return 0; } int32_t ch395_get_sock_int_status(uint8_t sock, uint8_t *pinterrupt) { int32_t ret = 0; uint8_t send_data[2] = {0}; uint8_t data = 0; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pinterrupt) { LOGE(TAG, "Invalid input %d", sock); return -1; } send_data[0] = CMD11_GET_INT_STATUS_SN; send_data[1] = sock; ret = ch395_spi_send_and_recv(send_data, sizeof(send_data), &data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to get sock %d interupt status", sock); return -1; } *pinterrupt = data; return 0; } int32_t ch395_set_sock_dest_ip(uint8_t sock, uint8_t *pdst_ip) { int32_t ret = 0; uint8_t data[6] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pdst_ip) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD50_SET_IP_ADDR_SN; data[1] = sock; memcpy(&data[2], pdst_ip, 4); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_set_sock_dest_port(uint8_t sock, uint16_t dest_port) { int32_t ret = 0; uint8_t data[4] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD30_SET_DES_PORT_SN; data[1] = sock; data[2] = (uint8_t)dest_port; data[3] = (uint8_t)(dest_port >> 8); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_set_sock_src_port(uint8_t sock, uint16_t src_port) { int32_t ret = 0; uint8_t data[4] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD30_SET_SOUR_PORT_SN; data[1] = sock; data[2] = (uint8_t)src_port; data[3] = (uint8_t)(src_port >> 8); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_set_sock_proto_type(uint8_t sock, uint8_t proto_type) { int32_t ret = 0; uint8_t data[3] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || proto_type > PROTO_TYPE_TCP) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD20_SET_PROTO_TYPE_SN; data[1] = sock; data[2] = proto_type; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_socket_open(uint8_t sock) { int32_t ret = 0; int32_t retry = 0; uint8_t status = 0; uint8_t data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD1W_OPEN_SOCKET_SN; data[1] = sock; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } /*check cmd status GET_CMD_STATUS, CMD_ERR_SUCCESS means successed*/ do { retry++; status = 0; /*need to wait data free interrupt*/ ret = ch395_get_cmd_status(&status); if (ret == 0 && (status != CH395_ERR_BUSY)) { break; } aos_msleep(2); } while (retry < 20); if (retry <= 20) { return 0; } return -1; } int32_t ch395_socket_close(uint8_t sock) { int32_t ret = 0; int32_t retry = 0; uint8_t status = 0; uint8_t data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD1W_CLOSE_SOCKET_SN; data[1] = sock; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } /*need to check cmd status*/ do { retry++; status = 0; /*need to wait data free interrupt*/ ret = ch395_get_cmd_status(&status); if (ret == 0 && (status != CH395_ERR_BUSY)) { break; } aos_msleep(2); } while (retry < 20); if (retry <= 20) { return 0; } return -1; } int32_t ch395_socket_tcp_connect(uint8_t sock) { int32_t ret = 0; int32_t retry = 0; uint8_t status = 0; uint8_t data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD1W_TCP_CONNECT_SN; data[1] = sock; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } /*need to check cmd status*/ do { retry++; status = 0; /*need to wait data free interrupt*/ ret = ch395_get_cmd_status(&status); if (ret == 0 && (status != CMD_ERR_SUCCESS)) { break; } aos_msleep(2); } while (retry < 20); if (retry >= 20) { LOGE(TAG, "Fail to execute cmd tcp connect"); return -1; } return 0; } int32_t ch395_socket_tcp_disconnect(uint8_t sock) { int32_t ret = 0; uint32_t retry = 0; uint8_t status = 0; uint8_t data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid input %d", sock); return -1; } data[0] = CMD1W_TCP_CONNECT_SN; data[1] = sock; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } /*need to check cmd status*/ do { retry++; status = 0; /*need to wait data free interrupt*/ ret = ch395_get_cmd_status(&status); if (ret == 0 && (status != CH395_ERR_BUSY)) { break; } aos_msleep(2); } while (retry < 20); if (retry >= 20) { LOGE(TAG, "Fail to execute cmd tcp disconnect"); return -1; } return 0; } int32_t ch395_socket_data_send(uint8_t sock, uint16_t datalen, uint8_t *pdata) { int32_t ret = 0; uint8_t *psend_data = NULL; uint32_t sendlen = 0; int32_t retry = 0; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pdata) { LOGE(TAG, "Invalid input %d", sock); return -1; } sendlen = datalen + 4; psend_data = malloc(sendlen); if (NULL == psend_data) { LOGE(TAG, "%s %d fail to malloc %d data", __FILE__, __LINE__, sendlen); return -1; } memset(psend_data, 0, sendlen); psend_data[0] = CMD30_WRITE_SEND_BUF_SN; psend_data[1] = sock; psend_data[2] = (uint8_t) (datalen); psend_data[3] = (uint8_t) (datalen >> 8); memcpy(&psend_data[4], pdata, datalen); aos_mutex_lock(&gst_spi_op_mutex, AOS_WAIT_FOREVER); ret = hal_spi_send_ch395_sockdata(&g_st_spi_info, psend_data, sendlen, SPI_TIME_OUT); aos_mutex_unlock(&gst_spi_op_mutex); free(psend_data); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sendlen); return -1; } return 0; } int32_t ch395_socket_recv_data_len(uint8_t sock, uint16_t *pdatalen) { int32_t ret = 0; uint8_t send_data[2] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pdatalen) { LOGE(TAG, "Invalid input %d", sock); return -1; } send_data[0] = CMD12_GET_RECV_LEN_SN; send_data[1] = sock; ret = ch395_spi_send_and_recv(send_data, sizeof(send_data), pdatalen, sizeof(uint16_t)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } int32_t ch395_socket_recv_data(uint8_t sock, uint16_t datalen, uint8_t *pdata) { int32_t ret = 0; uint8_t send_data[4] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || NULL == pdata || datalen == 0) { LOGE(TAG, "Invalid input %d datalen %d", sock, datalen); return -1; } send_data[0] = CMD30_READ_RECV_BUF_SN; send_data[1] = sock; send_data[2] = (uint8_t)datalen; send_data[3] = (uint8_t)(datalen >> 8); ret = ch395_spi_send_and_recv(send_data, sizeof(send_data), pdata, datalen); if (ret) { LOGE(TAG, "Fail to send data 0x%x", sock); return -1; } return 0; } /* * Input : enable : 1 enable PING : 0 disable PING */ int32_t ch395_ping_enable(uint8_t enable) { int32_t ret = 0; uint8_t cmd_data[2] = {0}; if (enable != 0 && enable != 1) { LOGE(TAG, "Invalid inpute %d", enable); return -1; } cmd_data[0] = CMD01_PING_ENABLE; cmd_data[1] = enable; ret = ch395_spi_data_write(cmd_data, sizeof(cmd_data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", enable); return -1; } return 0; } /* * Input : enable : 1 enable dhcp : 0 disable dhcp */ int32_t ch395_dhcp_enable(uint8_t enable) { int32_t ret = 0; uint8_t status = 0; uint8_t i = 0; uint8_t cmd_data[2] = {0}; /*should do it after chip is enabled*/ if (enable != 0 && enable != 1) { LOGE(TAG, "Invalid inpute %d", enable); return -1; } cmd_data[0] = CMD10_DHCP_ENABLE; cmd_data[1] = enable; ret = ch395_spi_data_write(cmd_data, sizeof(cmd_data)); if (ret) { LOGE(TAG, "Fail to send data 0x%x", enable); return -1; } aos_msleep(20); /*check cmd status*/ while (1) { ret = ch395_get_cmd_status(&status); if (ret == 0 && (status != CH395_ERR_BUSY)) { break; } if (i++ > 200) { return -1; } /* we should wait more than 2 ms to get cmd status*/ } LOGI(TAG, "dhcp enable %d execute successed ", enable); return 0; } int32_t ch395_dhcp_get_status(uint8_t *pstatus) { int32_t ret = 0; if (NULL == pstatus) { LOGE(TAG, "Invalid inpute "); return -1; } ret = ch395_spi_cmd_query(CMD01_GET_DHCP_STATUS, pstatus); if (ret) { LOGE(TAG, "Fail to get dhcp status ret %d", ret); return -1; } return 0; } int32_t ch395_get_ip_interface(ch395_int_t *pst_inf) { int32_t ret = 0; uint8_t cmd = CMD014_GET_IP_INF; if (NULL == pst_inf) { LOGE(TAG, "Invalid input"); return -1; } ret = ch395_spi_send_and_recv(&cmd, sizeof(cmd), pst_inf, sizeof(ch395_int_t)); if (ret) { LOGE(TAG, "Fail to read interface info data"); return -1; } return 0; } /*should be set before ch395 init*/ int32_t ch395_set_tcp_mss(uint16_t mss) { int32_t ret = 0; uint8_t data[3] = {0}; if (mss > TCP_MSS_MAX_VALUE || mss < TCP_MSS_MIN_VALUE) { LOGE(TAG, "Invalid Input %d", mss); return -1; } data[0] = CMD20_SET_TCP_MSS; data[1] = (uint8_t)mss; data[2] = (uint8_t)(mss >> 8); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write mss value %d", mss); return -1; } return 0; } int32_t ch395_set_func_param(uint32_t param) { int32_t ret = 0; uint8_t data[5] = {0}; data[0] = CMD40_SET_FUN_PARA; data[1] = (uint8_t)param; data[2] = (uint8_t)(param >> 8); data[3] = (uint8_t)(param >> 16); data[4] = (uint8_t)(param >> 24); ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to set func param value %d", param); return -1; } return 0; } int32_t ch395_set_sock_ttl(uint8_t sock, uint8_t ttl) { int32_t ret = 0; uint8_t data[3] = {0}; /*should be called after sock is opened*/ if (ttl > TCP_TTL_MAX_VALUE || sock >= MAX_SURPPORT_SOCK_NUM) { LOGE(TAG, "Invalid Input ttl %d, sock %d", ttl, sock); return -1; } data[0] = CMD20_SET_TTL; data[1] = sock; data[2] = ttl; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write sock %d ttl %d", sock, ttl); return -1; } return 0; } /* There is 48 blocks in ch395. Each Block size is 512 bytes. * The default config is : * sock 0 recv buf 0 8 * send buf 8 4 * sock 1 recv buf 12 8 * send buf 20 4 * sock 2 recv buf 24 8 * send buf 32 4 * sock 3 recv buf 36 8 * send buf 44 4 * other recv buf NULL 0 * send buf NULL 0 */ int32_t ch395_sock_set_recv_buf(uint8_t sock, uint8_t startblk, uint8_t blknum) { int32_t ret = 0; uint8_t data[4] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || startblk >= MAX_BUF_NUM || blknum >= MAX_BUF_NUM) { LOGE(TAG, "Invalid input sock %d, startblk %d, blknum %d", sock, startblk, blknum); return -1; } data[0] = CMD30_SET_RECV_BUF; data[1] = sock; data[2] = startblk; data[3] = blknum; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write sock %d startblk %d blknum %d", sock, startblk, blknum); return -1; } return 0; } int32_t ch395_sock_set_send_buf(uint8_t sock, uint8_t startblk, uint8_t blknum) { int32_t ret = 0; uint8_t data[4] = {0}; if (sock >= MAX_SURPPORT_SOCK_NUM || startblk >= MAX_BUF_NUM || blknum >= MAX_BUF_NUM) { LOGE(TAG, "Invalid input sock %d, startblk %d, blknum %d", sock, startblk, blknum); return -1; } data[0] = CMD30_SET_SEND_BUF; data[1] = sock; data[2] = startblk; data[3] = blknum; ret = ch395_spi_data_write(data, sizeof(data)); if (ret) { LOGE(TAG, "Fail to write sock %d startblk %d blknum %d", sock, startblk, blknum); return -1; } return 0; } int32_t ch395_dev_init(void) { int32_t ret = 0; uint8_t status = CH395_ERR_UNKNOW; uint8_t cmd = CMD0W_INIT_CH395; uint8_t i = 0; ret = ch395_spi_data_write(&cmd, 1); if (ret) { LOGE(TAG, "write init cmd fail %d ", ret); return -1; } /*should wait 350ms after init cmd*/ aos_msleep(200); /*check cmd excute status*/ while (1) { ret = ch395_get_cmd_status(&status); if (ret == 0 && status != CH395_ERR_BUSY) { break; } if (i++ > 200) { return -1; } /* we should wait more than 2 ms to get cmd status*/ aos_msleep(2); } return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/ch395_cmd.c
C
apache-2.0
27,920
/* * Copyright (C) 2020-2022 Alibaba Group Holding Limited * * SPDX-License-Identifier: Apache-2.0 */ #ifndef CH395_CMD_H #define CH395_CMD_H #ifdef __cplusplus extern "C" { #endif /* ********************************************************************************************************************* */ /* 命令代码 */ /* 一个命令操作顺序包含: 一个命令码(对于串口方式,命令码之前还需要两个同步码), 若干个输入数据(可以是0个), 若干个输出数据(可以是0个) 命令码起名规则: CMDxy_NAME 其中的x和y都是数字, x说明最少输入数据个数(字节数), y说明最少输出数据个数(字节数), y如果是W表示需要等待命令执行成功 有些命令能够实现0到多个字节的数据块读写, 数据块本身的字节数未包含在上述x或y之内 */ /* ********************************************************************************************************************* */ #define CMD01_GET_IC_VER 0x01 /* 获取芯片以及固件版本号 */ /* 输出: 版本号( 位7为0, 位6为1, 位5~位0为版本号 ) */ /* CH3395返回版本号的值为041H即版本号为01H */ #define CMD31_SET_BAUDRATE 0x02 /* 串口方式: 设置串口通讯波特率(上电或者复位后的默认波特率为9600bps */ /* 输入: 3字节波特率,第字节在前 */ /* 输出: 操作状态( CMD_RET_SUCCESS, 其它值说明操作未完成 ) */ #define CMD00_ENTER_SLEEP 0x03 /* 进入睡眠状态 */ #define CMD00_RESET_ALL 0x05 /* 执行硬件复位 */ #define CMD11_CHECK_EXIST 0x06 /* 测试通讯接口以及工作状态 */ /* 输入: 任意数据 */ /* 输出: 输入数据的按位取反 */ #define CMD02_GET_GLOB_INT_STATUS_ALL 0x19 /* 获取全局中断状态,V44版本以后的程序由于增加了socket数量需要用此命令获取全部的中断 */ /*输出:全局中断状态,参考全局中断状态定义 */ #define CMD10_SET_PHY 0x20 /* 设置PHY,默认为Auto,自动协商 */ /* 输入:PHY参数,参考PHY参数定义 */ #define CMD60_SET_MAC_ADDR 0x21 /* 设置MAC地址 必须在CMD00H_INIT_CH395之前设置完毕 */ /* 输入:6字节的MAC地址 */ #define CMD40_SET_IP_ADDR 0x22 /* 设置IP地址 必须在CMD00H_INIT_CH395之前设置完毕 */ /* 输入:4字节的IP地址 */ #define CMD40_SET_GWIP_ADDR 0x23 /* 设置网关IP地址 必须在CMD00H_INIT_CH395之前设置完毕 */ /* 输入:4字节的网关IP地址 */ #define CMD40_SET_MASK_ADDR 0x24 /* 设置子网掩码, 必须在CMD00H_INIT_CH395之前设置完毕 */ /* 输入:4字节的子网掩码 */ #define CMD90_SET_MAC_FILT 0x25 /* 设置MAC过滤 可以进行广播,多播等过滤 */ /* 输入:9字节参数,第1字节为过滤类型,参考过滤类型定义,*/ /* 第2至第5字节为HASH0,第6至第9字节为HASH1 */ #define CMD01_GET_PHY_STATUS 0x26 /* 获取PHY当前状态,如断开连接,10/100M FULL/HALF */ /* 输出:当前PHY状态,状态定义请参考PHY参数定义 */ #define CMD0W_INIT_CH395 0x27 /* 初始化CH395 */ /* 此命令执行时间大约200MS,需要等待此命令执行成功,才可以发下一条命令 */ #define CMD08_GET_UNREACH_IPPORT 0x28 /* 获取不可达信息 */ /* 输出:8字节,第1字节为不可达类型,参考不可达类型定义 */ /* 第2字节协议不可达协议码 */ /* 第3,4字节不可达端口 */ /* 第5-8字不可达IP */ #define CMD01_GET_GLOB_INT_STATUS 0x29 /* 获取全局中断状态,最大值为1S,不可以设置为0 */ /* 输出:全局中断状态,参考全局中断状态定义 */ #define CMD10_SET_RETRAN_COUNT 0x2A /* 重试次数,仅在TCP模式下有效 */ /* 输入:重试次数 */ #define CMD20_SET_RETRAN_PERIOD 0x2B /* 重试周期,最大值为20,仅在TCP模式下有效,不可以设置为0 */ /* 输入:重试周期 */ #define CMD01_GET_CMD_STATUS 0x2C /* 获取命令执行状态 */ /* 输出:命令执行状态,参考命令执行状态定义 */ #define CMD06_GET_REMOT_IPP_SN 0x2D /* 获取远端的端口以及IP地址,该命令在TCP服务器模式下使用 */ /* 输出:6字节,第1-4字节为远端的IP地址,第5-6字节为远端的端口号 */ #define CMD10_CLEAR_RECV_BUF_SN 0x2E /* 清除接收缓冲区 */ /* 输入:第1字节为socket的索引值 */ #define CMD12_GET_SOCKET_STATUS_SN 0x2F /* 获取socket n状态 */ /* 输入:socket的索引值,*/ /* 输出:第1字节:socket n 打开或者关闭 第2字节:TCP状态,仅在TCP模式且第1字节为打开状态下有意义 */ #define CMD11_GET_INT_STATUS_SN 0x30 /* 获取socket n的中断状态 */ /* 输入: socket的索引值*/ /* 输出:全局中断状态,参考全局中断状态定义 */ #define CMD50_SET_IP_ADDR_SN 0x31 /* 设置socket n的目的IP地址 */ /* 输入:第1字节为socket的索引值,第2至5字节为IP地址 */ #define CMD30_SET_DES_PORT_SN 0x32 /* 设置socket n的目的端口 */ /* 输入:第1字节为socket的索引值,第2至3字节为目的端口 */ #define CMD30_SET_SOUR_PORT_SN 0x33 /* 设置socket n的源端口 */ /* 输入:第1字节为socket的索引值,第2至3字节为源端口 */ #define CMD20_SET_PROTO_TYPE_SN 0x34 /* 设置socket n的协议类型 */ /* 输入:第1字节为socket的索引值,第2协议类型,参考协议类型定义 */ #define CMD1W_OPEN_SOCKET_SN 0x35 /* 打开socket n */ /* 输入:第1字节为socket的索引值,此命令需要等待命令执行成功 */ #define CMD1W_TCP_LISTEN_SN 0x36 /* socket n监听,收到此命令,socket n进入服务器模式,仅对TCP模式有效 */ /* 输入:第1字节为socket的索引值,此命令需要等待命令执行成功 */ #define CMD1W_TCP_CONNECT_SN 0x37 /* socket n连接,收到此命令,socket n进入客户端模式,仅对TCP模式有效 */ /* 输入:第1字节为socket的索引值,此命令需要等待命令执行成功 */ #define CMD1W_TCP_DISNCONNECT_SN 0x38 /* socket n断开连接,收到此命令,socket n断开已有连接,仅对TCP模式有效 */ /* 输入:第1字节为socket的索引值,此命令需要等待命令执行成功 */ #define CMD30_WRITE_SEND_BUF_SN 0x39 /* 向socket n缓冲区写入数据 */ /* 输入:第1字节为socket的索引值,第2至3字节为长度 */ #define CMD12_GET_RECV_LEN_SN 0x3B /* 获取socket n接收数据的长度 */ /* 输入:socket的索引值 */ /* 输出:2字节的接收长度 */ #define CMD30_READ_RECV_BUF_SN 0x3C /* 读取socket n接收缓冲区数据 */ /* 输入:第1字节为socket的索引值,第2至3字节为读取的长度n,低位在前 */ /* 输出:n个数据 */ #define CMD1W_CLOSE_SOCKET_SN 0x3D /* 关闭socket n */ /* 输入:socket的索引值 */ #define CMD20_SET_IPRAW_PRO_SN 0x3E /* 在IP RAW下,设置socket n的IP包协议类型 */ /* 输入:第1字节为socket的索引值,第2字节为IP RAW协议类型 */ #define CMD01_PING_ENABLE 0x3F /* 开启/关闭PING */ /* 输入:1字节,0为关闭PING,1为开启PING,默认开启 */ #define CMD06_GET_MAC_ADDR 0x40 /* 获取MAC地址 */ /* 输出:6字节的MAC地址 */ #define CMD10_DHCP_ENABLE 0x41 /* DHCP使能 */ /* 输入:1字节,1启动DHCP,0关闭DHCP */ #define CMD01_GET_DHCP_STATUS 0x42 /* 获取DHCP状态 */ /* 输出: 1字节状态码,0表示成功,其他值失败 */ #define CMD014_GET_IP_INF 0x43 /* IP,子网掩码,网关 */ /* 输出:20字节,分别为4字节IP,4字节网关,4字节掩码,4字节的DNS1,4字节的DNS2 */ #define CMD00_PPPOE_SET_USER_NAME 0x44 /* 设置PPPOE用户名 */ /* 输入:N个字节,0为结束符 */ #define CMD00_PPPOE_SET_PASSWORD 0x45 /* 设置密码 */ /* 输入:N个字节,0为结束符 */ #define CMD10_PPPOE_ENABLE 0x46 /* PPPOE使能 */ /* 输入:1字节,1启动PPPOE,0关闭PPPOE */ #define CMD01_GET_PPPOE_STATUS 0x47 /* 获取pppoe状态 */ /* 输出: 1字节状态码,0表示成功,其他值失败 */ #define CMD20_SET_TCP_MSS 0x50 /* 设置TCP MSS */ /* 输入:TCP MSS,低位在前 */ #define CMD20_SET_TTL 0x51 /* 设置TTL,TTL最大值为128 */ /* 输入:第1字节为socket的索引值,第2字节为TTL值,最大为128 */ #define CMD30_SET_RECV_BUF 0x52 /* 设置SOCKET接收缓冲区 */ /* 输入:第1字节为socket的索引值,第2字节为起始块索引,第3字节为块数 */ #define CMD30_SET_SEND_BUF 0x53 /* 设置SOCKET发送缓冲区 */ /* 输入:第1字节为socket的索引值,第2字节为起始块索引,第3字节为块数 */ #define CMD10_SET_MAC_RECV_BUF 0x54 /* 设置MAC接收缓冲区 */ /* 输入:输入1字节的MAC接收缓冲区的大小,16字节为单位 */ #define CMD40_SET_FUN_PARA 0x55 /* 设置功能参数 */ /* 输入:4字节的启动参数 */ #define CMD40_SET_KEEP_LIVE_IDLE 0x56 /* 设置KEEPLIVE空闲 */ /*输入:4字节的保活定时器空闲时间参数,低位在前 */ #define CMD40_SET_KEEP_LIVE_INTVL 0x57 /* 设置间隔时间 */ /*输入:4字节的保活定时器超时间隔,低位在前 */ #define CMD10_SET_KEEP_LIVE_CNT 0x58 /* 重试次数 */ /*输入:1字节重试次数 */ #define CMD20_SET_KEEP_LIVE_SN 0X59 /* 设置socket nkeeplive功能*/ /*输入:1个字节Socket索引,1个字节设置 */ #define CMD00_EEPROM_ERASE 0xE9 /* 擦除EEPROM*/ #define CMD30_EEPROM_WRITE 0xEA /* 写EEPROM */ /* 输入:2字节地址,1字节长度,长度必须小于64字节 */ #define CMD30_EEPROM_READ 0xEB /* 读EEPROM */ /* 输入:2字节地址,1字节长度,长度必须小于64字节 */ #define CMD10_READ_GPIO_REG 0xEC /* 读GPIO寄存器 */ /* 输入:第1个字节为REG地址,关于地址请参考相关宏定义 */ #define CMD20_WRITE_GPIO_REG 0xED /* 写GPIO寄存器 */ /* 输入:第1个字节为REG地址,关于地址请参考相关宏定义 */ /* 第2个字节为数据 */ /* 协议类型 */ #define PROTO_TYPE_IP_RAW 0 /* IP层原始数据 */ #define PROTO_TYPE_MAC_RAW 1 /* MAC层原始数据 */ #define PROTO_TYPE_UDP 2 /* UDP协议类型 */ #define PROTO_TYPE_TCP 3 /* TCP协议类型 */ /* PHY 命令参数/状态 */ #define PHY_DISCONN (1<<0) /* PHY断开 */ #define PHY_10M_FLL (1<<1) /* 10M全双工 */ #define PHY_10M_HALF (1<<2) /* 10M半双工 */ #define PHY_100M_FLL (1<<3) /* 100M全双工 */ #define PHY_100M_HALF (1<<4) /* 100M半双工 */ #define PHY_AUTO (1<<5) /* PHY自动模式,CMD10H_SET_PHY */ /*CH395 MAC过滤*/ #define MAC_FILT_RECV_BORADPKT (1<<0) /* 使能接收广播包 */ #define MAC_FILT_RECV_ALL (1<<1) /* 使能接收所有数据包 */ #define MAC_FILT_RECV_MULTIPKT (1<<2) /* 使能接收多播包 */ #define MAC_FILT_RECV_ENABLE (1<<3) /* 使能接收 */ #define MAC_FILT_SEND_ENABLE (1<<4) /* 使能发送 */ /* 中断状态 */ /* 以下为GLOB_INT会产生的状态 */ #define GINT_STAT_UNREACH (1<<0) /* 不可达中断 */ #define GINT_STAT_IP_CONFLI (1<<1) /* IP冲突 */ #define GINT_STAT_PHY_CHANGE (1<<2) /* PHY状态改变 */ #define GINT_STAT_DHCP (1<<3) /* DHCP/PPPOE 状态改变 */ #define GINT_STAT_SOCK0 (1<<4) /* socket0 产生中断 */ #define GINT_STAT_SOCK1 (1<<5) /* socket1 产生中断 */ #define GINT_STAT_SOCK2 (1<<6) /* socket2 产生中断 */ #define GINT_STAT_SOCK3 (1<<7) /* socket3 产生中断 */ #define GINT_STAT_SOCK4 (1<<8) /* scoket4 产生中断 */ #define GINT_STAT_SOCK5 (1<<9) /* scoket5 产生中断 */ #define GINT_STAT_SOCK6 (1<<10) /* scoket6 产生中断 */ #define GINT_STAT_SOCK7 (1<<11) /* scoket7 产生中断 */ /*以下为Sn_INT会产生的状态*/ #define SINT_STAT_SENBUF_FREE (1<<0) /* 发送缓冲区空闲 */ #define SINT_STAT_SEND_OK (1<<1) /* 发送成功 */ #define SINT_STAT_RECV (1<<2) /* socket端口接收到数据或者接收缓冲区不为空 */ #define SINT_STAT_CONNECT (1<<3) /* 连接成功,TCP模式下产生此中断 */ #define SINT_STAT_DISCONNECT (1<<4) /* 连接断开,TCP模式下产生此中断 */ #define SINT_STAT_TIM_OUT (1<<6) /* ARP和TCP模式下会发生此中断 */ /* 获取命令状态 */ #define CMD_ERR_SUCCESS 0x00 /* 命令操作成功 */ #define CMD_RET_ABORT 0x5F /* 命令操作失败 */ #define CH395_ERR_BUSY 0x10 /* 忙状态,表示当前正在执行命令 */ #define CH395_ERR_MEM 0x11 /* 内存错误 */ #define CH395_ERR_BUF 0x12 /* 缓冲区错误 */ #define CH395_ERR_TIMEOUT 0x13 /* 超时 */ #define CH395_ERR_RTE 0x14 /* 路由错误*/ #define CH395_ERR_ABRT 0x15 /* 连接停止*/ #define CH395_ERR_RST 0x16 /* 连接复位 */ #define CH395_ERR_CLSD 0x17 /* 连接关闭/socket 在关闭状态 */ #define CH395_ERR_CONN 0x18 /* 无连接 */ #define CH395_ERR_VAL 0x19 /* 错误的值 */ #define CH395_ERR_ARG 0x1a /* 错误的参数 */ #define CH395_ERR_USE 0x1b /* 已经被使用 */ #define CH395_ERR_IF 0x1c /* MAC错误 */ #define CH395_ERR_ISCONN 0x1d /* 已连接 */ #define CH395_ERR_OPEN 0X20 /* 已经打开 */ #define CH395_ERR_UNKNOW 0xFA /* 未知错误 */ /* PPP状态 */ #define CH395_PPP_SUCCESS 0 /* 成功 */ #define CH395_PPPERR_PARM 1 /* 无效参数 */ #define CH395_PPPERR_OPEN 2 /* 无法打开PPP会话 */ #define CH395_PPPERR_DEVICE 3 /* 无效的PPP设备 */ #define CH395_PPPERR_ALLOC 4 /* 资源分配失败 */ #define CH395_PPPERR_USER 5 /* 用户中断 */ #define CH395_PPPERR_CONNECT 6 /* 连接断开 */ #define CH395_PPPERR_AUTHFAIL 7 /* 挑战鉴别失败 */ #define CH395_PPPERR_PROTOCOL 8 /* 握手协议失败 */ #define CH395_PPPERR_TIME_OUT 9 /* 超时失败 */ #define CH395_PPPERR_CLOSE 10 /* 关闭失败 */ /* 不可达代码 */ #define UNREACH_CODE_HOST 0 /* 主机不可达 */ #define UNREACH_CODE_NET 1 /* 网络不可达 */ #define UNREACH_CODE_PROTOCOL 2 /* 协议不可达 */ #define UNREACH_CODE_PROT 3 /* 端口不可达 */ /*其他值请参考RFC792文档*/ /* 命令包头 */ #define SER_SYNC_CODE1 0x57 /* 串口命令同步码1 */ #define SER_SYNC_CODE2 0xAB /* 串口命令同步码2 */ /* TCP状态 */ #define TCP_CLOSED 0 #define TCP_LISTEN 1 #define TCP_SYN_SENT 2 #define TCP_SYN_RCVD 3 #define TCP_ESTABLISHED 4 #define TCP_FIN_WAIT_1 5 #define TCP_FIN_WAIT_2 6 #define TCP_CLOSE_WAIT 7 #define TCP_CLOSING 8 #define TCP_LAST_ACK 9 #define TCP_TIME_WAIT 10 /* GPIO寄存器地址 */ #define GPIO_DIR_REG 0x80 /* 寄存器方向寄存器,1:输出;0:输入 */ #define GPIO_IN_REG 0x81 /* GPIO输入寄存器 */ #define GPIO_OUT_REG 0x82 /* GPIO输出寄存器 */ #define GPIO_CLR_REG 0x83 /* GPIO输出清除: 0=keep, 1=clear */ #define GPIO_PU_REG 0x84 /* GPIO上拉使能寄存器 */ #define GPIO_PD_REG 0x85 /* GPIO下拉使能寄存器 */ /* 功能参数 */ #define FUN_PARA_FLAG_TCP_SERVER (1<<1) /* tcp server 多连接模式标志,0X44版本及以后支持 */ #define FUN_PARA_FLAG_LOW_PWR (1<<2) /* 低耗能模式 */ #define SOCK_CTRL_FLAG_SOCKET_CLOSE (1<<3) /* CH395不主动关闭Socket */ #define SOCK_DISABLE_SEND_OK_INT (1<<4) /* send ok中断控制位,为1表示关闭send ok中断 */ #define MAX_SURPPORT_SOCK_NUM 4 /*default is 4, max is 8*/ typedef struct { uint8_t ipaddr[4]; uint8_t gateway[4]; uint8_t ip_mask[4]; uint8_t ip_dns1[4]; uint8_t ip_dns2[4]; } ch395_int_t; typedef struct { ch395_int_t ip_info; uint8_t mac_addr[6]; uint8_t phystate; uint8_t mac_filt; uint16_t retran_count; uint16_t retran_period; uint8_t int_mode; uint16_t unreach_port; uint8_t unreach_ip[4]; } st_ch395_info_t; #ifdef __cplusplus } #endif #endif /* CH395_CMD_H */
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/ch395_cmd.h
C
apache-2.0
29,239
/* * Copyright (C) 2020-2022 Alibaba Group Holding Limited */ #include <string.h> #include "k_api.h" #include "aos/kernel.h" #include "lwip/err.h" #include "lwip/netif.h" #include "lwip/tcpip.h" #include "lwip/ip_addr.h" #include "netif/etharp.h" #include "uservice/uservice.h" #include "uservice/eventid.h" #include "ulog/ulog.h" #include <netmgr_ethernet.h> #include "ch395_spi.h" #include "ch395_cmd.h" /* Private typedef -----------------------------------------------------------*/ typedef struct { ip4_addr_t ip; ip4_addr_t netmask; ip4_addr_t gw; } tcpip_ip_info_t; /* Private define ------------------------------------------------------------*/ /* Stack size of the interface thread */ #define CH395_TASK_PRIO 20 #define CH395_TASK_SIZE (6 * 1024) #define CH395_MAX_DATA_SIZE 1514 /*max size is 1514 */ #define CH395_MIN_DATA_SZIE 60 /*min size is 64 include 4 bytes crc*/ /* Define those to better describe your network interface. */ #define IFNAME0 'e' #define IFNAME1 'n' #define TAG "ch395_lwip" static struct netif eth_lwip_netif; static tcpip_ip_info_t eth_ip_info = {0}; static aos_task_t gst_ch395_lwip_int_task = {0}; static aos_task_t gst_ch395_input_task = {0}; static aos_sem_t gst_ch395_recv_sem = {0}; static st_ch395_info_t gst_lwipch395info = { .phystate = PHY_DISCONN, }; static aos_mutex_t eth_mutex; static int fake_recv_count = 0; static bool bypass_fake_linkup = false; static void ch395_lwip_inter_proc(void); static int ch395_eth_sock_macraw(void); static void dump_ch395_packet(char *buf, int len) { int i = 0; for (i = 0; i < len; i++) { printf("0x%02x ", buf[i]); if ((i + 1) % 32 == 0) { printf("\r\n"); } } printf("\r\n"); } static err_t low_level_output(struct netif *netif, struct pbuf *p) { struct pbuf *q = NULL; uint8_t *data = NULL; uint32_t datalen = 0; int32_t ret = 0; uint32_t first_copy = 0; uint32_t copylen = 0; void *src_buf = NULL; data = aos_malloc(CH395_MAX_DATA_SIZE); memset(data, 0, CH395_MAX_DATA_SIZE); for (q = p; q != NULL; q = q->next) { src_buf = q->payload; copylen = q->len; if (first_copy == 0) { src_buf = (char *)src_buf + ETH_PAD_SIZE; copylen = copylen - ETH_PAD_SIZE; first_copy = 1; } if (datalen + copylen >= CH395_MAX_DATA_SIZE) { aos_free(data); return ERR_BUF; } memcpy(&data[datalen], src_buf, copylen); datalen = datalen + copylen; } if (datalen < CH395_MIN_DATA_SZIE) { datalen = CH395_MIN_DATA_SZIE; } /*for 4-byte alignment, 14 bytes ethernet header will cost 16 bytes; so just we jump over the first two bytes */ (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_socket_data_send(0, datalen, data); (void)aos_mutex_unlock(&eth_mutex); aos_free(data); if (ret) { printf("ch395 lwip low level output len %d fail", datalen); return ERR_IF; } return ERR_OK; } /** * @brief Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * * @param netif the lwip network interface structure for this ethernetif * @return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ static struct pbuf *low_level_input(struct netif *netif, uint8_t *data, uint32_t datalen) { struct pbuf *p = NULL, *q = NULL; uint8_t *buffer = data; uint32_t bufferoffset = 0; uint32_t copylen = 0; uint32_t leftlen = datalen; uint32_t first_copy = 0; uint32_t pbuf_len = 0; void *dest_buf = NULL; /* We allocate a pbuf chain of pbufs from the Lwip buffer pool */ p = pbuf_alloc(PBUF_RAW, datalen + ETH_PAD_SIZE, PBUF_POOL); if (NULL == p) { return NULL; } for (q = p; q != NULL; q = q->next) { dest_buf = q->payload; pbuf_len = q->len; if (first_copy == 0) { dest_buf = (char *)dest_buf + ETH_PAD_SIZE; pbuf_len = pbuf_len - ETH_PAD_SIZE; first_copy = 1; } if (q->len > leftlen) { copylen = leftlen; } else { copylen = pbuf_len; } memcpy(dest_buf, &buffer[bufferoffset], copylen); bufferoffset = bufferoffset + copylen; leftlen = leftlen - copylen; } return p; } extern void ch395_device_dereset(void); static int reset_ch395(void) { int ret; printf("CH395 resetting...\r\n"); ch395_device_dereset(); /* ret = ch395_chip_reset(); if (ret) { printf("eth reset fail %d\r\n", ret); return -1; } */ aos_msleep(100); ret = ch395_set_func_param(SOCK_CTRL_FLAG_SOCKET_CLOSE); if (ret) { printf("eth init fail : ch395 set func param fail %d\r\n", ret); return -1; } ret = ch395_dev_init(); if (ret) { printf("eth init fail : ch395 init fail %d\r\n", ret); return -1; } ret = ch395_eth_sock_macraw(); if (ret) { printf("eth fail to set socket 0 macraw mode %d\r\n", ret); return -1; } ret = ch395_ping_enable(1); if (ret) { printf("eth init fail : ch395 ping enable fail %d\r\n", ret); } printf("CH395 reset done...\r\n"); return 0; } static void ethernetif_input(void const *argument) { struct pbuf *p; int ret = 0; uint8_t sock = 0; uint16_t recv_len = 0; uint8_t *precv_data = NULL; struct netif *netif = (struct netif *)argument; /* then we need to recv the data */ precv_data = aos_malloc(CH395_MAX_DATA_SIZE); if (NULL == precv_data) { LOGE(TAG, "Fail to malloc %d ", recv_len); return; } while (1) { ret = aos_sem_wait(&gst_ch395_recv_sem, AOS_WAIT_FOREVER); if (ret) { LOGE(TAG, "Fail to wait socket %d recv sem4 ", sock); continue; } (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_socket_recv_data_len(sock, &recv_len); (void)aos_mutex_unlock(&eth_mutex); if (ret) { LOGE(TAG, "Fail to get sock %d recv length", sock); continue; } if (recv_len == 0 || recv_len > CH395_MAX_DATA_SIZE) { sem_count_t sem_count; if (recv_len == 0) { fake_recv_count += 1; LOGE(TAG, "sock %d no data need to recv", sock); } else { fake_recv_count += 4; LOGE(TAG, "sock %d frame over sized", sock); } (void)krhino_sem_count_get((ksem_t *)gst_ch395_recv_sem, &sem_count); (void)krhino_sem_count_set((ksem_t *)gst_ch395_recv_sem, 0); printf("ch395 recv sem count %lu\r\n", (unsigned long)sem_count); if (fake_recv_count >= 4) { (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); // gst_lwipch395info.phystate = PHY_DISCONN; // event_publish(EVENT_ETHERNET_LINK_DOWN, NULL); bypass_fake_linkup = true; (void)reset_ch395(); (void)aos_mutex_unlock(&eth_mutex); fake_recv_count = 0; } continue; } fake_recv_count = 0; memset(precv_data, 0, CH395_MAX_DATA_SIZE); (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_socket_recv_data(sock, recv_len, precv_data); (void)aos_mutex_unlock(&eth_mutex); if (ret) { LOGE(TAG, "sock %d recv data fail len %d", sock, recv_len); continue; } p = low_level_input(netif, precv_data, recv_len); if (p != NULL) { if (netif->input(p, netif) != ERR_OK) { pbuf_free(p); } } } /*shoudn't reach here incase memory leak */ aos_free(precv_data); } static int low_level_init(struct netif *netif) { unsigned char macaddress[6] = {0}; int ret = 0; ret = ch395_get_mac_addr(macaddress); if (ret) { printf("eth fail to get mac addr ret %d \r\n", ret); return -1; } /* set netif MAC hardware address length */ netif->hwaddr_len = ETH_HWADDR_LEN; /* set netif MAC hardware address */ netif->hwaddr[0] = macaddress[0]; netif->hwaddr[1] = macaddress[1]; netif->hwaddr[2] = macaddress[2]; netif->hwaddr[3] = macaddress[3]; netif->hwaddr[4] = macaddress[4]; netif->hwaddr[5] = macaddress[5]; /* set netif maximum transfer unit */ netif->mtu = 1500; /* Accept broadcast address and ARP traffic */ netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; ret = aos_sem_new(&gst_ch395_recv_sem, 0); if (ret) { printf("creat to new ch395 lwip send sem4 0x%x\r\n", ret); return -1; } ret = aos_task_new_ext(&gst_ch395_input_task, "ch395_input", ethernetif_input, netif, CH395_TASK_SIZE, CH395_TASK_PRIO); if (ret) { printf("fail to start ch395 lwip input task 0x%x\r\n", ret); aos_sem_free(&gst_ch395_recv_sem); return -1; } ret = aos_task_new_ext(&gst_ch395_lwip_int_task, "ch395_irq", ch395_lwip_inter_proc, NULL, CH395_TASK_SIZE, CH395_TASK_PRIO - 4); if (ret) { LOGE(TAG, "Fail to start chip interrupt proc task 0x%x", ret); aos_task_delete(&gst_ch395_input_task); aos_sem_free(&gst_ch395_recv_sem); return -1; } return 0; } /** * @brief Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * * This function should be passed as a parameter to netif_add(). * * @param netif the lwip network interface structure for this ethernetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ static err_t ethernetif_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "haas_aos"; #endif /* LWIP_NETIF_HOSTNAME */ netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; /* set netif maximum transfer unit */ netif->mtu = 1500; /* Accept broadcast address and ARP traffic */ netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; netif->output = etharp_output; netif->linkoutput = low_level_output; /* initialize the hardware */ if (low_level_init(netif) != 0) { printf("ch395 lwip low level init fail\r\n"); return ERR_IF; } return ERR_OK; } void post_ip_addr(tcpip_ip_info_t ip) { /* post ip, mask and gateway in dhcp mode */ printf("************************************************** \r\n"); printf("DHCP Enable \r\n"); printf("ip = %s \r\n", ip4addr_ntoa(&eth_ip_info.ip)); printf("mask = %s \r\n", ip4addr_ntoa(&eth_ip_info.netmask)); printf("gateway = %s \r\n", ip4addr_ntoa(&eth_ip_info.gw)); printf("************************************************** \r\n"); } static void tcpip_dhcpc_cb(struct netif *pstnetif) { uint8_t ip_addr[4] = {0}; uint8_t mask_addr[4] = {0}; uint8_t gw_addr[4] = {0}; int32_t ret = 0; if (!ip4_addr_cmp(ip_2_ip4(&pstnetif->ip_addr), IP4_ADDR_ANY4)) { // check whether IP is changed if (!ip4_addr_cmp(ip_2_ip4(&pstnetif->ip_addr), &eth_ip_info.ip) || !ip4_addr_cmp(ip_2_ip4(&pstnetif->netmask), &eth_ip_info.netmask) || !ip4_addr_cmp(ip_2_ip4(&pstnetif->gw), &eth_ip_info.gw)) { ip4_addr_set(&eth_ip_info.ip, ip_2_ip4(&pstnetif->ip_addr)); ip4_addr_set(&eth_ip_info.netmask, ip_2_ip4(&pstnetif->netmask)); ip4_addr_set(&eth_ip_info.gw, ip_2_ip4(&pstnetif->gw)); /* post the dhcp ip address */ post_ip_addr(eth_ip_info); /*set ip addr for ch395*/ memcpy(ip_addr, &eth_ip_info.ip.addr, sizeof(ip_addr)); memcpy(mask_addr, &eth_ip_info.netmask.addr, sizeof(ip_addr)); memcpy(gw_addr, &eth_ip_info.gw.addr, sizeof(ip_addr)); printf("\r\nip: %d:%d:%d:%d mask: %d:%d:%d:%d gw:%d:%d:%d:%d \r\n", ip_addr[0], ip_addr[1], ip_addr[2], ip_addr[3], mask_addr[0], mask_addr[1], mask_addr[2], mask_addr[3], gw_addr[0], gw_addr[1], gw_addr[2], gw_addr[3]); ret = ch395_set_ip_addr(ip_addr); if (ret) { printf("set ip addr fail \r\n"); } ret = ch395_set_gw_ip_addr(gw_addr); if (ret) { printf("set gateway ip addr fail \r\n"); } ch395_set_ip_mask_addr(mask_addr); if (ret) { printf("set ip mask addr fail \r\n"); } } event_publish(EVENT_NETMGR_DHCP_SUCCESS, NULL); } return; } err_t tcpip_dhcpc_start(struct netif *pstnetif) { int ret = 0; /*at first try to enable dhcp*/ if (NULL == pstnetif) { printf("input netif is NULL \r\n"); return -1; } if (netif_is_up(pstnetif)) { if (dhcp_start(pstnetif) != ERR_OK) { LOG("dhcp client start failed"); return -1; } } netif_set_status_callback(pstnetif, tcpip_dhcpc_cb); return 0; } static void tcpip_init_done(void *arg) { #if LWIP_IPV4 ip4_addr_t ipaddr, netmask, gw; memset(&ipaddr, 0, sizeof(ipaddr)); memset(&netmask, 0, sizeof(netmask)); memset(&gw, 0, sizeof(gw)); netif_add(&eth_lwip_netif, &ipaddr, &netmask, &gw, NULL, ethernetif_init, tcpip_input); #endif netif_set_default(&eth_lwip_netif); netif_set_up(&eth_lwip_netif); } /* should be called after dhcp is done */ static int ch395_eth_sock_macraw(void) { int ret = 0; ret = ch395_set_sock_proto_type(0, PROTO_TYPE_MAC_RAW); if (ret) { LOGE(TAG, "Fail to set sock 0 macraw mode fail"); return -1; } ret = ch395_socket_open(0); if (ret) { LOGE(TAG, "ch395 lwip fail to open socket 0 macraw mode"); return -1; } return 0; } static void ch395_lwip_sock_interrupt_proc(uint8_t sockindex) { uint8_t sock_int_socket = 0; uint16_t recv_len = 0; uint8_t *precv_data = NULL; int32_t ret = 0; /* get sock interrupt status */ (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_get_sock_int_status(sockindex, &sock_int_socket); (void)aos_mutex_unlock(&eth_mutex); /* send done proc */ if (sock_int_socket & SINT_STAT_SENBUF_FREE) { // LOGI(TAG, "sock %d send data done ", sockindex); /*it means send ok */ } if (sock_int_socket & SINT_STAT_SEND_OK) { /*only one buf is ok, so do nothing for now*/ } if (sock_int_socket & SINT_STAT_CONNECT) { /*the interrup only happened in tcp mode , in socket 0 macraw mode nothing todo */ } if (sock_int_socket & SINT_STAT_DISCONNECT) { /*the interrup only happened in tcp mode , in socket 0 macraw mode nothing todo */ } if (sock_int_socket & SINT_STAT_TIM_OUT) { /*the interrup only happened in tcp mode , in socket 0 macraw mode nothing todo */ } if (sock_int_socket & SINT_STAT_RECV) { // LOGI(TAG, "sock %d recv data ", sockindex); /*get recv data length*/ /*signal recv sem4*/ if (aos_sem_is_valid(&gst_ch395_recv_sem)) { aos_sem_signal(&gst_ch395_recv_sem); } } } static void ch395_lwip_inter_proc(void) { uint16_t ch395_int_status; uint8_t dhcp_status = 0; uint8_t phy_status = 0; uint32_t retry = 0; int32_t ret = 0; ip4_addr_t ipaddr = {0}; ip4_addr_t netmask = {0}; ip4_addr_t gw = {0}; while (1) { /*every 50 ms proc the chip interrupt*/ aos_msleep(5); ch395_int_status = 0; (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_get_global_all_int_status(&ch395_int_status); (void)aos_mutex_unlock(&eth_mutex); if (ch395_int_status & GINT_STAT_UNREACH) { /* nothing to do for now*/ LOGI(TAG, "recv unreach interrupt, nothing to do for now"); } if (ch395_int_status & GINT_STAT_IP_CONFLI) { LOGI(TAG, "recv ip confict interrupt, nothing to do for now"); } if (ch395_int_status & GINT_STAT_PHY_CHANGE) { /*get phy status*/ (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_get_phy_status(&phy_status); if (ret != 0) { LOGE(TAG, "Fail to get phy status"); } else if (phy_status == PHY_DISCONN) { bypass_fake_linkup = false; if (gst_lwipch395info.phystate != PHY_DISCONN) { LOGI(TAG, "eth link down"); gst_lwipch395info.phystate = phy_status; event_publish(EVENT_ETHERNET_LINK_DOWN, NULL); } else { LOGE(TAG, "eth fake link down"); } } else { if (gst_lwipch395info.phystate == PHY_DISCONN) { /*start up to dhcp*/ LOGI(TAG, "eth link up"); gst_lwipch395info.phystate = phy_status; event_publish(EVENT_ETHERNET_LINK_UP, &eth_lwip_netif); } else { if (bypass_fake_linkup) { bypass_fake_linkup = false; } else { LOGE(TAG, "eth fake link up"); // gst_lwipch395info.phystate = PHY_DISCONN; // event_publish(EVENT_ETHERNET_LINK_DOWN, NULL); bypass_fake_linkup = true; (void)reset_ch395(); (void)aos_mutex_unlock(&eth_mutex); continue; } } } (void)aos_mutex_unlock(&eth_mutex); } /* dhcp/pppoe interrup proc */ if (ch395_int_status & GINT_STAT_DHCP) { (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_dhcp_get_status(&dhcp_status); (void)aos_mutex_unlock(&eth_mutex); if (ret) { LOGE(TAG, "Fail to dhcp result"); continue; } if (dhcp_status == 0) { /*try to get ip interface */ do { memset(&gst_lwipch395info.ip_info, 0, sizeof(gst_lwipch395info.ip_info)); (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); ret = ch395_get_ip_interface(&gst_lwipch395info.ip_info); (void)aos_mutex_unlock(&eth_mutex); if (ret) { LOGE(TAG, "Fail to get eth interface ip info"); continue; } if (gst_lwipch395info.ip_info.ipaddr[0] != 0 && gst_lwipch395info.ip_info.ipaddr[1] != 0) { /* Post got ip event */ LOGI(TAG, "get ip info %d.%d.%d.%d gateway %d.%d.%d.%d mask %d.%d.%d.%d dns1 %d.%d.%d.%d dns2 %d.%d.%d.%d\r\n", gst_lwipch395info.ip_info.ipaddr[0], gst_lwipch395info.ip_info.ipaddr[1], gst_lwipch395info.ip_info.ipaddr[2], gst_lwipch395info.ip_info.ipaddr[3], gst_lwipch395info.ip_info.gateway[0], gst_lwipch395info.ip_info.gateway[1], gst_lwipch395info.ip_info.gateway[2], gst_lwipch395info.ip_info.gateway[3], gst_lwipch395info.ip_info.ip_mask[0], gst_lwipch395info.ip_info.ip_mask[1], gst_lwipch395info.ip_info.ip_mask[2], gst_lwipch395info.ip_info.ip_mask[3], gst_lwipch395info.ip_info.ip_dns1[0], gst_lwipch395info.ip_info.ip_dns1[1], gst_lwipch395info.ip_info.ip_dns1[2], gst_lwipch395info.ip_info.ip_dns1[3], gst_lwipch395info.ip_info.ip_dns2[0], gst_lwipch395info.ip_info.ip_dns2[1], gst_lwipch395info.ip_info.ip_dns2[2], gst_lwipch395info.ip_info.ip_dns2[3]); memcpy(&ipaddr.addr, gst_lwipch395info.ip_info.ipaddr, 4); memcpy(&netmask.addr, gst_lwipch395info.ip_info.ip_mask, 4); memcpy(&gw.addr, gst_lwipch395info.ip_info.gateway, 4); netif_set_addr(&eth_lwip_netif, &ipaddr, &netmask, &gw); tcpip_dhcpc_cb(&eth_lwip_netif); break; } aos_msleep(1000); retry++; } while (retry < 10); } else { // LOGD(TAG, "dhcp time out, cannot get ip addr, it will go on dhcp after 16 second"); } } if (ch395_int_status & GINT_STAT_SOCK0) { ch395_lwip_sock_interrupt_proc(0); } } } void eth_ch395_reset(void) { (void)aos_mutex_lock(&eth_mutex, AOS_WAIT_FOREVER); if (netmgr_eth_get_stat() == CONN_STATE_NETWORK_CONNECTED) { gst_lwipch395info.phystate = PHY_DISCONN; event_publish(EVENT_ETHERNET_LINK_DOWN, NULL); bypass_fake_linkup = false; (void)reset_ch395(); } (void)aos_mutex_unlock(&eth_mutex); } int eth_lwip_tcpip_init(void) { int ret = 0; unsigned char chip_ver = 0; unsigned char soft_ver = 0; spi_dev_t eth_spi_dev = {0}; ret = aos_mutex_new(&eth_mutex); if (ret) { printf("eth_mutex init fail %d\r\n", ret); return -1; } eth_spi_dev.port = 0; eth_spi_dev.config.data_size = SPI_DATA_SIZE_8BIT; eth_spi_dev.config.mode = SPI_WORK_MODE_3; eth_spi_dev.config.cs = SPI_CS_DIS; eth_spi_dev.config.freq = 2000000; eth_spi_dev.config.role = SPI_ROLE_MASTER; eth_spi_dev.config.firstbit = SPI_FIRSTBIT_MSB; eth_spi_dev.config.t_mode = SPI_TRANSFER_NORMAL; ret = ch395_module_init(&eth_spi_dev); if (ret) { printf("spi init fail 0x%x, port %d, spi role %d, firstbit %d, work_mode %d, freq %d\r\n", ret, eth_spi_dev.port, eth_spi_dev.config.role, eth_spi_dev.config.firstbit, eth_spi_dev.config.mode, eth_spi_dev.config.freq); return -1; } ret = ch395_get_version(&chip_ver, &soft_ver); if (ret || chip_ver != 0x4) { printf("Fail to get chip ver: 0x%x soft ver 0x%x ret : 0x%x\r\n", chip_ver, soft_ver, ret); return -1; } ret = ch395_set_func_param(SOCK_CTRL_FLAG_SOCKET_CLOSE); if (ret) { printf("eth init fail : ch395 set func param fail %d\r\n", ret); return -1; } ret = ch395_dev_init(); if (ret) { printf("eth init fail : ch395 init fail %d\r\n", ret); return -1; } ret = ch395_eth_sock_macraw(); if (ret) { printf("eth fail to set socket 0 macraw mode %d\r\n", ret); return -1; } ret = ch395_ping_enable(1); if (ret) { printf("eth init fail : ch395 ping enable fail %d\r\n", ret); } tcpip_init_done(NULL); return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/ch395_lwip.c
C
apache-2.0
23,442
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "k_api.h" //#include "aos/kernel.h" #include "ch395_spi.h" #include "hal_iomux.h" #include "hal_spi.h" #include "hal_trace.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" #include "hal_cache.h" #include "cmsis_os.h" #include "cmsis.h" #define SPI_DMA_MAX 4095 osSemaphoreDef(ch395_spi1_dma_semaphore); osMutexDef(ch395_spi1_mutex); static void spi1_dma_irq(uint32_t error); typedef struct { enum HAL_IOMUX_PIN_T spi_pin_DI0; enum HAL_IOMUX_PIN_T spi_pin_CLK; enum HAL_IOMUX_PIN_T spi_pin_CS0; enum HAL_IOMUX_PIN_T spi_pin_DIO; enum HAL_IOMUX_FUNCTION_T spi_fun_DI0; enum HAL_IOMUX_FUNCTION_T spi_fun_CLK; enum HAL_IOMUX_FUNCTION_T spi_fun_CS0; enum HAL_IOMUX_FUNCTION_T spi_fun_DIO; osSemaphoreId spi_dma_semaphore; osMutexId spi_mutex_id; int (*spi_open)(const struct HAL_SPI_CFG_T *cfg); int (*spi_dma_send)(const void *data, uint32_t len, HAL_SPI_DMA_HANDLER_T handler); int (*spi_dma_recv)(const void *cmd, void *data, uint32_t len, HAL_SPI_DMA_HANDLER_T handler); int (*spi_send)(const void *data, uint32_t len); int (*spi_recv)(const void *cmd, void *data, uint32_t len); void (*spi_dma_irq)(uint32_t error); int (*spi_close)(uint32_t cs); } spi_ctx_obj_t; static spi_ctx_obj_t spi_ctx[1] = { { .spi_pin_DI0 = HAL_IOMUX_PIN_P3_4, .spi_pin_CLK = HAL_IOMUX_PIN_P3_7, .spi_pin_CS0 = HAL_IOMUX_PIN_P3_6, .spi_pin_DIO = HAL_IOMUX_PIN_P3_5, .spi_fun_DI0 = HAL_IOMUX_FUNC_SPILCD_DI0, .spi_fun_CLK = HAL_IOMUX_FUNC_SPILCD_CLK, .spi_fun_CS0 = HAL_IOMUX_FUNC_AS_GPIO, .spi_fun_DIO = HAL_IOMUX_FUNC_SPILCD_DIO, .spi_dma_semaphore = NULL, .spi_mutex_id = 0, .spi_open = hal_spilcd_open, .spi_dma_send = hal_spilcd_dma_send, .spi_dma_recv = hal_spilcd_dma_recv, .spi_send = hal_spilcd_send, .spi_recv = hal_spilcd_recv, .spi_dma_irq = spi1_dma_irq, .spi_close = hal_spilcd_close } }; void ch395_device_dereset(void) { /*dereset the ch395 chip*/ hal_gpio_pin_set_dir(HAL_IOMUX_PIN_P3_3, HAL_GPIO_DIR_OUT, 0); aos_msleep(1000); hal_gpio_pin_set_dir(HAL_IOMUX_PIN_P3_3, HAL_GPIO_DIR_OUT, 1); aos_msleep(50); } /** * Initialises the SPI interface for a given SPI device * * @param[in] spi the spi device * * @return 0 : on success, EIO : if the SPI device could not be initialised */ int32_t hal_ch395_spi_init(spi_dev_t *spi) { int ret = -1; spi_config_t cfg_spi = spi->config; if (spi->port >= (sizeof(spi_ctx) / sizeof(spi_ctx_obj_t))) { return -1; } static struct HAL_IOMUX_PIN_FUNCTION_MAP pinmux_spi[] = { {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, {0, 0, HAL_IOMUX_PIN_VOLTAGE_VIO, HAL_IOMUX_PIN_NOPULL}, }; pinmux_spi[0].pin = spi_ctx[spi->port].spi_pin_DI0; pinmux_spi[1].pin = spi_ctx[spi->port].spi_pin_CLK; pinmux_spi[2].pin = spi_ctx[spi->port].spi_pin_CS0; pinmux_spi[3].pin = spi_ctx[spi->port].spi_pin_DIO; pinmux_spi[0].function = spi_ctx[spi->port].spi_fun_DI0; pinmux_spi[1].function = spi_ctx[spi->port].spi_fun_CLK; pinmux_spi[2].function = spi_ctx[spi->port].spi_fun_CS0; pinmux_spi[3].function = spi_ctx[spi->port].spi_fun_DIO; hal_iomux_init(pinmux_spi, ARRAY_SIZE(pinmux_spi)); struct HAL_SPI_CFG_T spi_cfg; switch (cfg_spi.mode) { case SPI_WORK_MODE_0: spi_cfg.clk_delay_half = false; spi_cfg.clk_polarity = false; break; case SPI_WORK_MODE_1: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = false; break; case SPI_WORK_MODE_2: spi_cfg.clk_delay_half = false; spi_cfg.clk_polarity = true; break; case SPI_WORK_MODE_3: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = true; break; default: spi_cfg.clk_delay_half = true; spi_cfg.clk_polarity = true; } spi_cfg.slave = 0; if (cfg_spi.t_mode == SPI_TRANSFER_DMA) { spi_cfg.dma_rx = true; spi_cfg.dma_tx = true; } else { spi_cfg.dma_rx = false; spi_cfg.dma_tx = false; } spi_cfg.rate = cfg_spi.freq; if (spi_cfg.rate > 26000000) spi_cfg.rate = 26000000; spi_cfg.cs = 0; spi_cfg.rx_bits = cfg_spi.data_size; spi_cfg.tx_bits = cfg_spi.data_size; spi_cfg.rx_frame_bits = 0; ret = spi_ctx[spi->port].spi_open(&spi_cfg); if (ret != 0) { TRACE("spi %d open error", spi->port); return ret; } TRACE("spi %d open succ", spi->port); /*if cs use as gpio ,pull up at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } if (!spi_ctx[spi->port].spi_dma_semaphore) { spi_ctx[spi->port].spi_dma_semaphore = osSemaphoreCreate(osSemaphore(ch395_spi1_dma_semaphore), 0); } if (!spi_ctx[spi->port].spi_dma_semaphore) { TRACE("spi%d_dma_semaphore create failed!", spi->port); return -1; } if (!spi_ctx[spi->port].spi_mutex_id) { spi_ctx[spi->port].spi_mutex_id = osMutexCreate((osMutex(ch395_spi1_mutex))); } if (!spi_ctx[spi->port].spi_mutex_id) { TRACE("spi%d_mutex create failed!", spi->port); return -1; } return ret; } static void spi1_dma_irq(uint32_t error) { if (osOK != osSemaphoreRelease(spi_ctx[0].spi_dma_semaphore)) { TRACE("spi0dmairq osSemaphoreRelease failed!"); } } /** * Spi send * * @param[in] spi the spi device * @param[in] data spi send data * @param[in] size spi send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0 : on success, EIO : if the SPI device could not be initialised */ int32_t hal_spi_send_ch395(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; uint32_t len = size; uint32_t i = 0; uint8_t *buf = data; osStatus status = osErrorOS; if (NULL == spi || NULL == data || 0 == size) { TRACE("spi input para err"); return -3; } status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); return -2; } hal_cache_sync(HAL_CACHE_ID_D_CACHE); /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } /* send cmd at first */ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(data, 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(data, 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, size); goto OUT; } /* send cmd param */ if (size > 1) { if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(data + 1, size - 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(data + 1, size - 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, size); goto OUT; } } OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); return ret; } /** * Spi send * * @param[in] spi the spi device * @param[in] data spi send data * @param[in] size spi send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @return 0 : on success, EIO : if the SPI device could not be initialised */ int32_t hal_spi_send_ch395_sockdata(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; uint32_t len = size; uint32_t i = 0; uint8_t *buf = data; osStatus status = osErrorOS; if (NULL == spi || NULL == data || size <=4 ) { TRACE("spi input para err"); return -3; } status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); return -2; } hal_cache_sync(HAL_CACHE_ID_D_CACHE); /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } /* send cmd at first */ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(data, 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(data, 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, size); goto OUT; } /* send cmd param : sock + datalen */ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(data + 1, 3, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(data + 1, 3); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, size); goto OUT; } /* send sock data */ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(data + 4, size - 4, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(data + 4, size - 4); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, size); goto OUT; } OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); return ret; } //full duplex recev int32_t hal_spi_send_and_recv_ch395_normal(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { int32_t ret = 0; uint32_t len = rx_size; uint32_t remainder = 0; osStatus status = 0; uint8_t *cmd; if (NULL == spi || NULL == tx_data || 0 == tx_size || NULL == rx_data || 0 == rx_size) { TRACE("spi input para err"); return -3; } cmd = (uint8_t *)malloc(len); if (cmd == NULL) { TRACE("%s malloc size %d error\r", __FUNCTION__, len); return -1; } memset(cmd, 0, len); status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); free(cmd); return -2; } /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } hal_cache_sync(HAL_CACHE_ID_D_CACHE); /* send cmd at first */ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(tx_data, 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(tx_data, 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, tx_size); goto OUT; } /* send cmd param */ if (tx_size > 1) { if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(tx_data + 1, tx_size - 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(tx_data + 1, tx_size - 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, tx_size); goto OUT; } } /*then recv data*/ do { remainder = len <= SPI_DMA_MAX ? len : SPI_DMA_MAX; hal_cache_sync(HAL_CACHE_ID_I_CACHE);//PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_recv(cmd, rx_data, remainder, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("SPI Read timeout!"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_recv(cmd, rx_data, remainder); } len -= remainder; rx_data += remainder; if (ret) { TRACE("spi mode %d recv fail %d, size %d", spi->config.t_mode, ret, rx_size); goto OUT; } } while (len); OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); free(cmd); return ret; } int32_t hal_spi_send_and_recv_ch395_exist(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout) { int32_t ret = 0; uint32_t len = rx_size; uint32_t remainder = 0; osStatus status = osOK; if (NULL == spi || NULL == tx_data || 2 != tx_size || NULL == rx_data || 1 != rx_size) { TRACE("spi input para err"); return -3; } status = osMutexWait(spi_ctx[spi->port].spi_mutex_id, osWaitForever); if (osOK != status) { TRACE("%s spi_mutex wait error = 0x%X!", __func__, status); return -2; } /*if cs use as gpio, pull down cs at first*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 0); } /*send cmd at first*/ if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_send(&tx_data[0], 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("spi dma tail send timeout"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_send(&tx_data[0], 1); } if (ret) { TRACE("spi mode %d send fail %d, size %d", spi->config.t_mode, ret, tx_size); goto OUT; } /*send test data at the same time need to recv data*/ hal_cache_sync(HAL_CACHE_ID_I_CACHE);//PSRAM must sync cache to memory when used dma if (spi->config.t_mode == SPI_TRANSFER_DMA) { ret = spi_ctx[spi->port].spi_dma_recv(&tx_data[1], rx_data, 1, spi_ctx[spi->port].spi_dma_irq); if (osSemaphoreWait(spi_ctx[spi->port].spi_dma_semaphore, timeout) <= 0) { TRACE("SPI Read timeout!"); goto OUT; } } else { ret = spi_ctx[spi->port].spi_recv(&tx_data[1], rx_data, 1); } OUT: /*if cs use as gpio, pull pull up cs at the end*/ if (spi_ctx[spi->port].spi_fun_CS0 == HAL_IOMUX_FUNC_AS_GPIO) { hal_gpio_pin_set_dir(spi_ctx[spi->port].spi_pin_CS0, HAL_GPIO_DIR_OUT, 1); } osMutexRelease(spi_ctx[spi->port].spi_mutex_id); return ret; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/ch395_spi.c
C
apache-2.0
15,358
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef CH395_SPI_H #define CH395_SPI_H #include "stdint.h" #include "aos/hal/spi.h" int32_t hal_ch395_spi_init(spi_dev_t *spi); int32_t hal_spi_send_ch395(spi_dev_t *spi, const uint8_t *data, uint16_t size, uint32_t timeout); int32_t hal_spi_send_and_recv_ch395_normal(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout); int32_t hal_spi_send_and_recv_ch395_exist(spi_dev_t *spi, uint8_t *tx_data, uint16_t tx_size, uint8_t *rx_data, uint16_t rx_size, uint32_t timeout); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/ch395_spi.h
C
apache-2.0
622
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include "aos/kernel.h" #include "ulog/ulog.h" #include "di.h" #include "hal_iomux_haas1000.h" #define TAG "ex_di" #define TIMER_CHECK_INTERVAL 10 #define DI_STABLE_COUNT 5 digital_input_value_change_notify g_di_notify_cb = NULL; typedef struct { uint8_t installed; uint8_t monitor_flag; uint8_t check_count; gpio_pinstate_t exactly_level; gpio_dev_t gpio_dev; } gpio_dev_input_t; /*digital input gpio dev list , the default value is high*/ static gpio_dev_input_t gpio_dev_input[DI_PORT_SIZE] = { {0, 0, 0, GPIO_PinState_Set, {HAL_IOMUX_PIN_P2_4, IRQ_MODE, NULL}}, {0, 0, 0, GPIO_PinState_Set, {HAL_IOMUX_PIN_P2_5, IRQ_MODE, NULL}}, {0, 0, 0, GPIO_PinState_Set, {HAL_IOMUX_PIN_P4_7, IRQ_MODE, NULL}}, {0, 0, 0, GPIO_PinState_Set, {HAL_IOMUX_PIN_P4_6, IRQ_MODE, NULL}}, }; static aos_timer_t st_di_check_timer = {0}; static int32_t get_di_port_by_iomux(uint8_t iomux, uint32_t *diport) { uint32_t i = 0; for (i = 0; i < DI_PORT_SIZE; i++) { if (gpio_dev_input[i].gpio_dev.port == iomux) { *diport = i; return 0; } } return -1; } static void di_interrup_proc(void *arg) { uint8_t port = 0; uint32_t diport = 0; int32_t ret = 0; uint32_t value = 0; if (NULL == arg) { LOGE(TAG, "Invalid input %s %d", __FILE__, __LINE__); return ; } port = *(uint8_t *)arg; ret = get_di_port_by_iomux(port, &diport); if (ret) { LOGE(TAG, "can not porc iomux %d interrupt", port); return ; } if (gpio_dev_input[diport].installed == 0) { LOGE(TAG, "di port %d iomux %d haven't init yet", diport, port); return ; } ret = hal_gpio_input_get(&(gpio_dev_input[diport].gpio_dev), &value); if (ret) { LOGE(TAG, "Fail to get di port %d input value ret %d", diport, value); return ; } hal_gpio_clear_irq(&gpio_dev_input[diport].gpio_dev); hal_gpio_disable_irq(&gpio_dev_input[diport].gpio_dev); if (value != gpio_dev_input[diport].exactly_level) { /*add the port to the monitorlist list*/ //LOGI(TAG,"add di %d to monitor list", diport); gpio_dev_input[diport].check_count = 0; gpio_dev_input[diport].monitor_flag = 1; } if (value == GPIO_PinState_Set) { /*rising edge interrupt, so enable falling interrupt */ //LOGI(TAG, "port %d recv a rising edge interrupt and enable the falling edge", diport); ret = hal_gpio_enable_irq(&gpio_dev_input[diport].gpio_dev, IRQ_TRIGGER_FALLING_EDGE, di_interrup_proc, &gpio_dev_input[diport].gpio_dev.port); } if (value == GPIO_PinState_Reset) { /*falling edge interrupt*/ //LOGI(TAG, "port %d recv a falling edge interrupt and enable the rising edge", diport); ret = hal_gpio_enable_irq(&gpio_dev_input[diport].gpio_dev, IRQ_TRIGGER_RISING_EDGE, di_interrup_proc, &gpio_dev_input[diport].gpio_dev.port); } if (ret) { LOGE(TAG, "Fail to enable gpio interrupt , gpio value is %d, ret %d", value, ret); } return ; } static void di_value_check(void *timer, void *arg) { uint32_t i; int32_t ret = 0; uint32_t gpio_value = 0; for (i = 0; i < DI_PORT_SIZE; i++) { if (gpio_dev_input[i].installed == 0 || gpio_dev_input[i].monitor_flag == 0) { continue; } ret = hal_gpio_input_get(&gpio_dev_input[i].gpio_dev, &gpio_value); if (ret) { LOGE(TAG, "Fail to get di %d port %d value at %s %d", i, gpio_dev_input[i].gpio_dev.port, __FILE__, __LINE__); continue; } if (gpio_value == gpio_dev_input[i].exactly_level) { /*remove it from standout monitor list*/ gpio_dev_input[i].monitor_flag = 0; gpio_dev_input[i].check_count = 0; } else { gpio_dev_input[i].check_count++; if (gpio_dev_input[i].check_count >= DI_STABLE_COUNT) { gpio_dev_input[i].monitor_flag = 0; gpio_dev_input[i].exactly_level = gpio_value; gpio_dev_input[i].check_count = 0; LOGI(TAG, "di %d changes to value %d", i, gpio_value); /*notify the gpio value change info */ if (NULL != g_di_notify_cb) { ret = g_di_notify_cb(i, gpio_value); if (ret) { LOGE(TAG, "Fail to notify di %d value changes to %d", i, gpio_value); } } } } } } int32_t expansion_board_di_init() { int32_t ret = 0; uint32_t i = 0; uint32_t gpio_value = GPIO_PinState_Set; /*init digital input*/ for (i = 0; i < DI_PORT_SIZE; i++) { ret = hal_gpio_init(&gpio_dev_input[i].gpio_dev); if (ret) { LOGE(TAG, "di %d pin %d init fail ret", i, gpio_dev_input[i].gpio_dev.port, ret); return -1; } ret = hal_gpio_input_get(&gpio_dev_input[i].gpio_dev, &gpio_value); if (ret) { LOGE(TAG, "di %d pin %d fail to get value, ret %d", i, gpio_dev_input[i].gpio_dev.port, ret); return -1; } LOGI(TAG, "di %d init value is %d", i, gpio_value); /*for haas1000 doesn't support both edge trigger*/ if (gpio_value == GPIO_PinState_Set) { ret = hal_gpio_enable_irq(&gpio_dev_input[i].gpio_dev, IRQ_TRIGGER_FALLING_EDGE, di_interrup_proc, &gpio_dev_input[i].gpio_dev.port); } else { ret = hal_gpio_enable_irq(&gpio_dev_input[i].gpio_dev, IRQ_TRIGGER_RISING_EDGE, di_interrup_proc, &gpio_dev_input[i].gpio_dev.port); } if (ret) { LOGE(TAG, "di %d pin %d fail enable irq ret %d", i, gpio_dev_input[i].gpio_dev.port, ret); return -1; } gpio_dev_input[i].installed = 1; gpio_dev_input[i].exactly_level = gpio_value; } /*init the gpio check timer, check gpio value every 10ms */ ret = aos_timer_new_ext(&st_di_check_timer, di_value_check, NULL, TIMER_CHECK_INTERVAL, 1, 1); if (ret) { LOGE(TAG, "Fail to new gpio value check timer ret 0x%x", ret); for (i = 0; i < DI_PORT_SIZE; i++) { hal_gpio_disable_irq(&gpio_dev_input[i].gpio_dev); hal_gpio_finalize(&gpio_dev_input[i].gpio_dev); gpio_dev_input[i].installed = 0; } return -1; } return 0; } int32_t expansion_board_di_get_value(uint8_t port, gpio_pinstate_t *value) { int32_t ret = 0; if (port >= DI_PORT_SIZE || NULL == value) { LOGE(TAG, " %s %d Invalid input port %d", __FILE__, __LINE__, port); return -1; } if (gpio_dev_input[port].installed == 0) { LOGE(TAG, "DI port %d haven't init yet", port); return -1; } *value = gpio_dev_input[port].exactly_level; return 0; } void expansion_board_di_change_notify_register(digital_input_value_change_notify cb) { if (NULL == cb) { LOGE(TAG, " %s %d Invalid input", __FILE__, __LINE__); return ; } g_di_notify_cb = cb; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/di.c
C
apache-2.0
7,367
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef GIDITAL_INPUT_H #define GIDITAL_INPUT_H #include "stdint.h" #include "aos/hal/gpio.h" enum en_di_port { DI_PORT_0 = 0, DI_PORT_1, DI_PORT_2, DI_PORT_3, DI_PORT_SIZE }; typedef int32_t (*digital_input_value_change_notify)(uint8_t port, uint32_t value); void expansion_board_di_change_notify_register(digital_input_value_change_notify cb); int32_t expansion_board_di_get_value(uint8_t port, gpio_pinstate_t *value); int32_t expansion_board_di_init(); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/di.h
C
apache-2.0
554
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include "aos/kernel.h" #include "ulog/ulog.h" #include "do.h" #include "hal_iomux_haas1000.h" #define TAG "ex_do" typedef struct { uint8_t installed; gpio_dev_t gpio_dev; } gpio_dev_ouput_t; /*digital input gpio dev list , the default value is high*/ static gpio_dev_ouput_t gpio_dev_output[DO_PORT_SIZE] = { {0, {HAL_IOMUX_PIN_P2_7, OUTPUT_PUSH_PULL, NULL}}, {0, {HAL_IOMUX_PIN_P2_6, OUTPUT_PUSH_PULL, NULL}}, {0, {HAL_IOMUX_PIN_P4_0, OUTPUT_PUSH_PULL, NULL}}, {0, {HAL_IOMUX_PIN_P4_1, OUTPUT_PUSH_PULL, NULL}}, }; int32_t expansion_board_do_init(void) { int32_t ret = 0; uint32_t i = 0; /*init digital input*/ for (i = 0; i < DO_PORT_SIZE; i++) { ret = hal_gpio_init(&gpio_dev_output[i].gpio_dev); if (ret) { LOGE(TAG, "do %d pin %d init fail ret", i, gpio_dev_output[i].gpio_dev.port, ret); return -1; } /*init status do should output low, depends on pd requires */ ret = hal_gpio_output_high(&gpio_dev_output[i].gpio_dev); if (ret) { LOGE(TAG, "%s %d port %d set low fail , ret %d", __FUNCTION__, __LINE__, i, ret); return -1; } gpio_dev_output[i].installed = 1; } return 0; } int32_t expansion_board_do_high(uint8_t port) { int32_t ret = -1; if (port >= DO_PORT_SIZE) { LOGE(TAG, "%s %d invalid input port %d", __FUNCTION__, __LINE__, port); return -1; } if (gpio_dev_output[port].installed == 0) { LOGE(TAG, "%s %d port %d haven't init yet", __FUNCTION__, __LINE__, port); return -1; } /*do output high ,gpio should pull down */ ret = hal_gpio_output_low(&gpio_dev_output[port].gpio_dev); if (ret) { LOGE(TAG, "%s %d port %d set high fail , ret %d", __FUNCTION__, __LINE__, port, ret); return -1; } return 0; } int32_t expansion_board_do_low(uint8_t port) { int32_t ret = -1; if (port >= DO_PORT_SIZE) { LOGE(TAG, "%s %d invalid input port %d", __FUNCTION__, __LINE__, port); return -1; } if (gpio_dev_output[port].installed == 0) { LOGE(TAG, "%s %d port %d haven't init yet", __FUNCTION__, __LINE__, port); return -1; } /*do output high ,gpio should pull up */ ret = hal_gpio_output_high(&gpio_dev_output[port].gpio_dev); if (ret) { LOGE(TAG, "%s %d port %d set low fail , ret %d", __FUNCTION__, __LINE__, port, ret); return -1; } return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/do.c
C
apache-2.0
2,600
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef GIDITAL_OUTPUT_H #define GIDITAL_OUTPUT_H #include "stdint.h" #include "aos/hal/gpio.h" enum en_do_port { DO_PORT_0 = 0, DO_PORT_1, DO_PORT_2, DO_PORT_3, DO_PORT_SIZE }; int32_t expansion_board_do_init(void); int32_t expansion_board_do_high(uint8_t port); int32_t expansion_board_do_low(uint8_t port); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/do.h
C
apache-2.0
407
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include "aos/kernel.h" #include "ulog/ulog.h" #include "exp_adc.h" #include "hal_iomux_haas1000.h" #define TAG "ex_adc" typedef struct { uint8_t installed; adc_dev_t st_adc_info; } exp_adc_dev_t; #define ADC_DEFAULT_TIMEOUT 3000 #define ADC_MAX_VALUE 3300 #define ADC_AVERAGE_TIME 32 /*exp adc device*/ static exp_adc_dev_t exp_adc_dev[ADC_PORT_SIZE] = { {0, {2, {1000}, NULL}}, {0, {0, {1000}, NULL}}, }; int32_t expansion_board_adc_init(void) { int32_t ret = 0; int32_t i = 0; for (i = 0; i < ADC_PORT_SIZE; i++) { if (exp_adc_dev[i].installed) { continue; } ret = hal_adc_init(&exp_adc_dev[i].st_adc_info); if (ret) { LOGE(TAG, "adc port %d init fail %d ", i, ret); return -1; } exp_adc_dev[i].installed = 1; } return 0; } int32_t expansion_board_adc_get_value(uint32_t port, uint32_t *output) { int32_t ret = 0; uint32_t i = 0; uint32_t adc_sum = 0; uint32_t adc_avrg = 0; /*for haas1000 adc max value */ uint32_t adc_min = ADC_MAX_VALUE; uint32_t adc_max = 0; uint32_t adc_value = 0; if (port >= ADC_PORT_SIZE || NULL == output ) { LOGE(TAG, "%s %d invalid input port %d", __FILE__, __LINE__, port); return -1; } if (exp_adc_dev[port].installed == 0) { LOGE(TAG, "exp adc %d haven't init yet , get value fail", port); return -1; } for(i = 0; i < ADC_AVERAGE_TIME + 2; i++) { ret = hal_adc_value_get(&exp_adc_dev[port].st_adc_info, &adc_value, ADC_DEFAULT_TIMEOUT); if (ret) { LOGE(TAG, "Get adc %d port value fail ", port); return -1; } adc_sum += adc_value; /* the min sampling voltage */ if(adc_min >= adc_value) { adc_min = output; } /* the max sampling voltage */ if(adc_max <= output) { adc_max = output; } aos_msleep(20); } /*adc sum value reduce adc min value reduse adc max value; and divided by 32*/ adc_avrg = (adc_sum - adc_min - adc_max) >> 5; *output = adc_avrg; return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/exp_adc.c
C
apache-2.0
2,292
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef EXP_ADC_H #define EXP_ADC_H #include "stdint.h" #include "aos/hal/adc.h" enum en_exp_adc_port { ADC_PORT_0 = 0, ADC_PORT_1, ADC_PORT_SIZE }; int32_t expansion_board_adc_init(void); int32_t expansion_board_do_high(uint8_t port); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/exp_adc.h
C
apache-2.0
324
#include <stdio.h> //#include <aos/kernel.h> #include "aos/hal/gpio.h" #include "hal_iomux_haas1000.h" #include "key.h" static key_cfg_t key_cfg; static gpio_dev_t key_gpio; static void key_rising_edge_handle(); static long long key_falling_ms = 0; static void key_falling_edge_handle() { hal_gpio_clear_irq(&key_gpio); hal_gpio_disable_irq(&key_gpio); key_falling_ms = aos_now_ms(); hal_gpio_enable_irq(&key_gpio, IRQ_TRIGGER_RISING_EDGE, key_rising_edge_handle, (void *)HAL_IOMUX_PIN_P3_2); } static void key_rising_edge_handle() { long long ms; uint32_t press_ms; hal_gpio_clear_irq(&key_gpio); hal_gpio_disable_irq(&key_gpio); ms = aos_now_ms(); press_ms = (uint32_t)(ms - key_falling_ms); if((press_ms < key_cfg.short_press_max_ms) && (press_ms > KEY_MIN_PRESS_MS)) { if(key_cfg.short_press_handler != NULL) { key_cfg.short_press_handler(); } } else if(press_ms > key_cfg.long_press_min_ms) { if(key_cfg.long_press_handler != NULL) { key_cfg.long_press_handler(); } } key_falling_ms = 0; hal_gpio_enable_irq(&key_gpio, IRQ_TRIGGER_FALLING_EDGE, key_falling_edge_handle, (void *)HAL_IOMUX_PIN_P3_2); } int key_init(key_cfg_t *cfg) { int ret = 0; if(cfg == NULL) { return -1; } if((cfg->short_press_handler == NULL) && (cfg->long_press_handler == NULL)) { return -1; } memcpy(&key_cfg, cfg, sizeof(key_cfg_t)); if(key_cfg.short_press_max_ms == 0) { key_cfg.short_press_max_ms = KEY_SHORT_PRESS_MS; } if(key_cfg.long_press_min_ms == 0) { key_cfg.long_press_min_ms = KEY_LONG_PRESS_MS; } key_gpio.port = HAL_IOMUX_PIN_P3_2; key_gpio.config = IRQ_MODE; hal_gpio_init(&key_gpio); ret = hal_gpio_enable_irq(&key_gpio, IRQ_TRIGGER_FALLING_EDGE, key_falling_edge_handle, (void *)HAL_IOMUX_PIN_P3_2); return ret; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/key.c
C
apache-2.0
1,936
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef K_KEY_H #define K_KEY_H #include "stdint.h" #define KEY_MIN_PRESS_MS 50 #define KEY_SHORT_PRESS_MS 2000 #define KEY_LONG_PRESS_MS 6000 typedef struct { uint32_t short_press_max_ms; // default 2000 uint32_t long_press_min_ms; // default 5000 void (*short_press_handler)(void); void (*long_press_handler)(void); } key_cfg_t; int key_init(key_cfg_t *cfg); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/key.h
C
apache-2.0
463
#include "aos/hal/gpio.h" #include "hal_iomux_haas1000.h" #include "led.h" void led_switch(int id, led_e onoff) { int ret = 0; gpio_dev_t led; /* gpio port config */ switch (id) { case 1: led.port = HAL_IOMUX_PIN_LED1; break; case 2: led.port = HAL_IOMUX_PIN_LED2; break; case 3: led.port = HAL_IOMUX_PIN_P4_4; break; case 4: led.port = HAL_IOMUX_PIN_P4_3; break; case 5: led.port = HAL_IOMUX_PIN_P4_2; break; default: return; } /* set as output mode */ led.config = OUTPUT_PUSH_PULL; ret = hal_gpio_init(&led); if(ret != 0) { printf("hal_gpio_init %d failed, ret=%d\n", id, ret); return; } if(onoff == LED_OFF) { ret = hal_gpio_output_high(&led); } else { ret = hal_gpio_output_low(&led); } if(ret != 0) { printf("hal_gpio_output %d failed, ret=%d\n", id, ret); return; } }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/led.c
C
apache-2.0
1,008
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef K_LED_H #define K_LED_H typedef enum { LED_OFF, LED_ON } led_e; void led_switch(int id, led_e onoff); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/led.h
C
apache-2.0
193
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include "ulog/ulog.h" #include "aos/hal/i2c.h" #include "pca9544.h" #include "mux_i2c.h" /********************************************************* * @fun haas_mux_i2c_init * @breif mux i2c initialization * @param i2c:the pointer for i2c configuration * @param port: port for muxer * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_init(i2c_dev_t *i2c, uint8_t port) { int32_t ret = 0; PCA9544_DEV_CFG_T dev_cfg; dev_cfg.dev_addr = PCA9544_BASE_ADDR; dev_cfg.pca9544_ch = port; if(i2c == NULL) { printf("i2c param is null\r\n"); return -1; } if((i2c->port != DFT_MCU_I2C_PORT)) { printf("The i2c port is not correct for mux_i2c\r\n"); i2c->port = 1; } ret = pca9544_init(i2c, &dev_cfg); if (ret) { printf("mux_i2c init error since pca9544 init fail\r\n"); return -1; } ret = pca9544_set_chan(dev_cfg.pca9544_ch); if (ret) { printf("mux_i2c init error since pca9544 init fail\r\n"); return -1; } return ret; } /********************************************************* * @fun haas_mux_i2c_reg_write * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] reg_addr register address * @param[in] reg_num register num * @param[in] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_reg_write(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t reg_addr, uint16_t reg_num, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; if(i2c == NULL) { printf("i2c param is null\r\n"); return -1; } if((i2c->port != DFT_MCU_I2C_PORT)) { printf("The i2c port is not correct for mux_i2c\r\n"); i2c->port = DFT_MCU_I2C_PORT; } ret = hal_i2c_mem_write(i2c, dev_addr, reg_addr, reg_num, data, size, timeout); if (ret) { printf("mux_i2c reg write failed\r\n"); return -1; } } /********************************************************* * @fun haas_mux_i2c_reg_read * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] reg_addr register address * @param[in] reg_num register number * @param[out] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_reg_read(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t reg_addr, uint16_t reg_num, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; if(i2c == NULL) { printf("i2c param is null\r\n"); return -1; } if((i2c->port != DFT_MCU_I2C_PORT)) { printf("The i2c port is not correct for mux_i2c\r\n"); i2c->port = DFT_MCU_I2C_PORT; } ret = hal_i2c_mem_read(i2c, dev_addr, reg_addr, reg_num, data, size, timeout); if (ret) { printf("mux_i2c reg write failed\r\n"); return -1; } } /******************************************************** * @fun haas_mux_i2c_data_send * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_data_send(i2c_dev_t *i2c, uint16_t dev_addr, const uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; if(i2c == NULL) { printf("i2c param is null\r\n"); return -1; } if((i2c->port != DFT_MCU_I2C_PORT)) { printf("The i2c port is not correct for mux_i2c\r\n"); i2c->port = DFT_MCU_I2C_PORT; } ret = hal_i2c_master_send(i2c, dev_addr, data, size, timeout); if (ret) { printf("mux_i2c data send failed\r\n"); return -1; } } /******************************************************** * @fun haas_mux_i2c_data_recv * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] data i2c master recv data * @param[in] size i2c master recv data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_data_recv(i2c_dev_t *i2c, uint16_t dev_addr, uint8_t *data, uint16_t size, uint32_t timeout) { int32_t ret = 0; if(i2c == NULL) { printf("i2c param is null\r\n"); return -1; } if((i2c->port != DFT_MCU_I2C_PORT)) { printf("The i2c port is not correct for mux_i2c\r\n"); i2c->port = DFT_MCU_I2C_PORT; } ret = hal_i2c_master_recv(i2c, dev_addr, data, size, timeout); if (ret) { printf("mux_i2c data recv failed\r\n"); return -1; } } /******************************************************** * @fun haas_mux_i2c_deinit * @param null * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_deinit() { int32_t ret = 0; pca9544_deinit(); return ret; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/mux_i2c.c
C
apache-2.0
6,393
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef MUX_I2C_H #define MUX_I2C_H /* Muxer I2C Port definition */ #define HAAS_MUX_I2C_PORT2 0x06 #define HAAS_MUX_I2C_PORT3 0x07 #define DFT_MCU_I2C_PORT 1 /********************************************************* * @fun haas_mux_i2c_init * @breif mux i2c initialization * @param i2c:the pointer for i2c configuration * @param port: port for muxer * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_init(i2c_dev_t *i2c, uint8_t port); /********************************************************* * @fun haas_mux_i2c_reg_write * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] reg_addr register address * @param[in] reg_num register num * @param[in] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_reg_write(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t reg_addr, uint16_t reg_num, const uint8_t *data, uint16_t size, uint32_t timeout); /********************************************************* * @fun haas_mux_i2c_reg_read * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] reg_addr register address * @param[in] reg_num register number * @param[out] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_reg_read(i2c_dev_t *i2c, uint16_t dev_addr, uint16_t reg_addr, uint16_t reg_num, const uint8_t *data, uint16_t size, uint32_t timeout); /******************************************************** * @fun haas_mux_i2c_data_send * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] data i2c master send data * @param[in] size i2c master send data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_data_send(i2c_dev_t *i2c, uint16_t dev_addr, const uint8_t *data, uint16_t size, uint32_t timeout); /******************************************************** * @fun haas_mux_i2c_data_recv * * @param[in] i2c the i2c device * @param[in] dev_addr device address * @param[in] data i2c master recv data * @param[in] size i2c master recv data size * @param[in] timeout timeout in milisecond, set this value to HAL_WAIT_FOREVER * if you want to wait forever * * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_data_recv(i2c_dev_t *i2c, uint16_t dev_addr, uint8_t *data, uint16_t size, uint32_t timeout); /******************************************************** * @fun haas_mux_i2c_deinit * @param null * @rtn 0 : on success, EIO : error *********************************************************/ int32_t haas_mux_i2c_deinit(); #endif /* MUX_I2C_H */
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/mux_i2c.h
C
apache-2.0
3,869
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include "ulog/ulog.h" #include "aos/hal/uart.h" /* RS485 Macro definition */ #define HAAS_RS485_UART_IDX 1 #define HAAS_RS485_BD_DFT 19200 /* static variable definition */ static uart_dev_t uart_rs485 = {0}; int32_t haas_rs485_init(uart_dev_t *uart_dev) { int32_t ret = 0; if(uart_dev == NULL) { uart_rs485.port = HAAS_RS485_UART_IDX; uart_rs485.config.baud_rate = HAAS_RS485_BD_DFT; uart_rs485.config.data_width = DATA_WIDTH_8BIT; uart_rs485.config.flow_control = FLOW_CONTROL_DISABLED; uart_rs485.config.mode = MODE_TX_RX; uart_rs485.config.parity = NO_PARITY; uart_rs485.config.stop_bits = STOP_BITS_1; } else { memset(&uart_rs485, 0, sizeof(uart_dev_t)); memcpy(&uart_rs485, uart_dev, sizeof(uart_dev_t)); } ret = hal_uart_init(&uart_rs485); if (ret) { printf("=====rs485: init fail =====\r\n"); return ret; } return ret; } int32_t haas_rs485_send(const void *data, uint32_t size, uint32_t timeout) { int32_t ret; ret = hal_uart_send(&uart_rs485, data, size, timeout); if (ret) { printf("=====rs485: fail to send test data======\r\n"); return -1; } } int32_t haas_rs485_recv(void *data, uint32_t expect_size, uint32_t *recv_size, uint32_t timeout) { int32_t ret = 0; ret = hal_uart_recv_II(&uart_rs485, data, expect_size, recv_size, timeout); if (ret) { printf("=====rs485: recv data fail=====\r\n"); } } int32_t haas_rs485_deinit(uart_dev_t *uart) { int32_t ret = 0; ret = hal_uart_finalize(&uart_rs485); return ret; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/rs485.c
C
apache-2.0
1,842
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef RS485_H #define RS485_H /* RS485 Macro definition */ #define HAAS_RS485_UART_IDX 1 #define HAAS_RS485_BD_DFT 19200 #define HAAS_RS485_DFT_CFG NULL int32_t haas_rs485_init(uart_dev_t *uart_dev); int32_t haas_rs485_send(const void *data, uint32_t size, uint32_t timeout); int32_t haas_rs485_recv(void *data, uint32_t expect_size, uint32_t *recv_size, uint32_t timeout); int32_t haas_rs485_deinit(uart_dev_t *uart_dev); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/rs485.h
C
apache-2.0
532
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include "aos/hal/rtc.h" #include "rx8130ce.h" /** * This function will initialize the on board CPU real time clock * * * @param[in] rtc rtc device * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_init(rtc_dev_t *rtc) { int ret = 0; ret = rx8130ce_init(); if(ret) { printf("board rtc init fail\r\n"); return -1; } return 0; } /** * This function will return the value of time read from the on board CPU real time clock. * * @param[in] rtc rtc device * @param[out] time pointer to a time structure * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_get_time(rtc_dev_t *rtc, rtc_time_t *time) { int ret = 0; ret = rx8130ce_get_time(time, sizeof(rtc_time_t)); if(ret) { printf("board rtc get time fail\r\n"); return -1; } return 0; } /** * This function will set MCU RTC time to a new value. * * @param[in] rtc rtc device * @param[out] time pointer to a time structure * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_set_time(rtc_dev_t *rtc, const rtc_time_t *time) { int ret = 0; ret = rx8130ce_set_time(time, sizeof(rtc_time_t)); if(ret) { printf("board rtc set time fail\r\n"); return -1; } return 0; } /** * De-initialises an RTC interface, Turns off an RTC hardware interface * * @param[in] RTC the interface which should be de-initialised * * @return 0 : on success, EIO : if an error occurred with any step */ int32_t hal_rtc_finalize(rtc_dev_t *rtc) { return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/rtc.c
C
apache-2.0
1,723
#include "aos/hal/gpio.h" #include "hal_iomux_haas1000.h" static gpio_dev_t wdg_gpio = {0, 0, NULL}; static int watchdog_flag = 0; void watchdog_feeddog(void) { if(watchdog_flag == 1) { return; } if(wdg_gpio.port == 0) { wdg_gpio.port = HAL_IOMUX_PIN_P4_5; wdg_gpio.config = OUTPUT_PUSH_PULL; hal_gpio_init(&wdg_gpio); } hal_gpio_output_toggle(&wdg_gpio); } void watchdog_stopfeed(void) { watchdog_flag = 1; } void watchdog_feeddog_user(void) { if (wdg_gpio.port == 0) { wdg_gpio.port = HAL_IOMUX_PIN_P4_5; wdg_gpio.config = OUTPUT_PUSH_PULL; hal_gpio_init(&wdg_gpio); } hal_gpio_output_toggle(&wdg_gpio); }
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/watchdog.c
C
apache-2.0
709
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef WATCHDOG_H #define WATCHDOG_H void watchdog_feeddog(void); void watchdog_stopfeed(void); #endif
YifuLiu/AliOS-Things
hardware/board/haas100/drivers/watchdog.h
C
apache-2.0
170
#include "stdio.h" #include "aos/init.h" #include "board.h" #include <k_api.h> #include "k_config.h" #include <stdio.h> #include <stdlib.h> //#include "aos/yloop.h" #ifdef AOS_COMP_YUNIT #include "yts.h" #endif #include "ota_port.h" //#include "apps.h" #include "hal_trace.h" #include "led.h" /* * If enable this macro for local test, we don't use wifi service to trigger connection, * remember to mask -DALIOS_WIFI_SERVICE and set -DLWIP_SUPPORT=1 in SDK. */ #if LWIP_SUPPORT #define ALIOS_BES_APP #endif #define BES_SDK 0 #define BES_WIFI_ONLY 1 #define BES_WIFI_BT 2 #define BES_WIFI_BT_MINI 3 // cut off nouse tasks /* * main task stask size(byte) */ #define OS_MAIN_TASK_STACK (32*1024) #define OS_MAIN_TASK_PRI 32 /* For user config kinit.argc = 0; kinit.argv = NULL; kinit.cli_enable = 0; */ static kinit_t kinit = {0, NULL, 1}; static ktask_t *g_main_task; static ktask_t *g_speech_task = NULL; static ktask_t *g_dsp_task = NULL; uint8_t mesh_open_enalbe = 1; uint32_t g_wifi_factory_test = 0; extern void soc_peripheral_init(); extern void aos_init_done_hook(void); extern void ble_nosignal_uart_bridge_loop(void); extern uint8_t ble_nosignal_start_flag; extern int32_t tg_bt_hal_vendor_hci_set_epta(int32_t state); extern uint8_t epta_hci_set_flag; extern void a7_heartbeat_reboot_enable(int enable); extern uint32_t __aos_lastword_start[]; #ifndef AOS_BINS extern int application_start(int argc, char **argv); #endif #ifdef ENABLE_LATTICE #include "ali_led.h" #include "ali_sensor.h" void ali_lattice_cli_init(); #endif #ifdef CONFIG_ALI_DISPLAY void disp_init(void); #endif static void haas_board_init(void) { #if CONFIG_A7_DSP_ENABLE int init = BES_WIFI_BT; #else int init = BES_WIFI_BT_MINI; #endif int release_version = 1; int ret = 0; #if 1//def CONFIG_GENIE_DEBUG // disable watchdog release_version = 0; #endif platform_init_step0(release_version); printf("%s platform_init_step0 done\n", __FUNCTION__); #if CONFIG_A7_DSP_ENABLE /*disable it, since output stereo as default*/ // analog_aud_codec_set_dev(1); // haas use spk-L #endif platform_init_step1(init); printf("%s platform_init_step1 done\n", __FUNCTION__); ASSERT(DEBUG_LASTWORD_RAM_ADDR == (uint32_t)__aos_lastword_start, "DEBUG_LASTWORD_RAM_ADDR(0x%x) is not equel to __aos_lastword_start(0x%x)", DEBUG_LASTWORD_RAM_ADDR, (uint32_t)__aos_lastword_start) led_switch(1, LED_ON); led_switch(2, LED_ON); led_switch(3, LED_ON); led_switch(4, LED_ON); led_switch(5, LED_ON); #if CONFIG_A7_DSP_ENABLE #ifndef CONFIG_GENIE_DEBUG a7_heartbeat_reboot_enable(1); #endif #endif } static void a7_dsp_init(void) { if (!app_enter_factory_wifi_test()) { printf("now a7_dsp_boot\n"); a7_dsp_boot(); } else { printf("app_enter_factory_wifi_test, no a7_dsp_boot\n"); } } static void factory_rf_test(void) { kinit_t kinit = {0, NULL, 1}; printf("wait factory test now...\n"); board_stduart_init(); aos_components_init(&kinit); #ifdef AOS_VENDOR_CLI vendor_cli_register_init(); #endif while(1) { aos_msleep(1000); } } static void aos_main_task_entry(void) { int ret = 0; #ifdef AOS_COMP_YUNIT char *parm[4] = {"yts", "kv", "ramfs", "vfs"}; #endif /* user code start */ soc_peripheral_init(); if (app_enter_factory_wifi_test()) { printf("********************************************************************\n"); printf("Begin wifi factory test ...\n"); printf("********************************************************************\n"); g_wifi_factory_test = 1; } ch395_device_dereset(); #ifdef AOS_COMP_CPLUSPLUS cpp_init(); #endif #ifdef AOS_COMP_YUNIT yts_run(sizeof(parm) / sizeof(parm[0]), &parm[0]); #endif #ifdef ENABLE_LATTICE ali_lattice_cli_init(); #endif #ifdef CONFIG_ALI_DISPLAY disp_init(); #endif aos_init_done_hook(); ret = bwifi_init(); if (ret) { printf("bwifi init fail\n"); } ret = eth_lwip_tcpip_init(); if (ret) { printf("haas100 ethernet init fail\n"); } #if (RHINO_CONFIG_HW_COUNT > 0) soc_hw_timer_init(); #endif #ifndef AOS_BINS if (app_enter_factory_wifi_test() == false) { aos_maintask(); } else { factory_rf_test(); } #endif } int main(void) { int times = 0; /*irq initialized is approved here.But irq triggering is forbidden, which will enter CPU scheduling. Put them in sys_init which will be called after aos_start. Irq for task schedule should be enabled here, such as PendSV for cortex-M4. */ haas_board_init(); //including aos_heap_set(); flash_partition_init(); /*kernel init, malloc can use after this!*/ //krhino_init(); /*main task to run */ krhino_task_dyn_create(&g_main_task, "main_task", 0, OS_MAIN_TASK_PRI, 0, OS_MAIN_TASK_STACK, (task_entry_t)aos_main_task_entry, 1); /*kernel start schedule!*/ //krhino_start(); while (1) { krhino_task_sleep(100); if (times == 10) { led_switch(1, LED_OFF); led_switch(2, LED_OFF); led_switch(3, LED_OFF); led_switch(4, LED_OFF); led_switch(5, LED_OFF); times ++; } else { if(times < 11) { times ++; } } #ifdef AOS_VENDOR_CLI /*only work when enter ble nosignal*/ if(ble_nosignal_start_flag) { ble_nosignal_uart_bridge_loop(); } #endif if(epta_hci_set_flag) { printf("%d epta_hci_set_flag \n", epta_hci_set_flag); tg_bt_hal_vendor_hci_set_epta(epta_hci_set_flag); epta_hci_set_flag = 0; } } /*never run here*/ return 0; }
YifuLiu/AliOS-Things
hardware/board/haas100/startup/startup.c
C
apache-2.0
5,829
/* File: startup_ARMCM3.S * Purpose: startup file for Cortex-M3 devices. Should use with * GCC for ARM Embedded Processors * Version: V2.0 * Date: 16 August 2013 * /* Copyright (c) 2011 - 2013 ARM LIMITED All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ARM nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------------*/ .syntax unified .arch armv7-m .section .stack .align 3 #ifdef __STACK_SIZE .equ Stack_Size, __STACK_SIZE #else .equ Stack_Size, 0xc00 #endif .globl __StackTop .globl __StackLimit __StackLimit: .space Stack_Size .size __StackLimit, . - __StackLimit __StackTop: .size __StackTop, . - __StackTop .section .heap .align 3 #ifdef __HEAP_SIZE .equ Heap_Size, __HEAP_SIZE #else .equ Heap_Size, 0x1B000 #endif .globl __HeapBase .globl __HeapLimit __HeapBase: .if Heap_Size .space Heap_Size .endif .size __HeapBase, . - __HeapBase __HeapLimit: .size __HeapLimit, . - __HeapLimit .section .isr_vector .align 2 .globl __isr_vector __isr_vector: .word __StackTop /* Top of Stack */ .word Reset_Handler /* Reset Handler */ .word NMI_Handler /* NMI Handler */ .word HardFault_Handler /* Hard Fault Handler */ .word MemManage_Handler /* MPU Fault Handler */ .word BusFault_Handler /* Bus Fault Handler */ .word UsageFault_Handler /* Usage Fault Handler */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word 0 /* Reserved */ .word SVC_Handler /* SVCall Handler */ .word DebugMon_Handler /* Debug Monitor Handler */ .word 0 /* Reserved */ .word PendSV_Handler /* PendSV Handler */ .word OS_CPU_SysTickHandler /* SysTick Handler */ /* External interrupts */ .word SDIO_RX_IRQHandler .word SDIO_TX_IRQHandler .word SDIO_RX_CMD_IRQHandler .word SDIO_TX_CMD_IRQHandler .word tls_wl_mac_isr .word Default_Handler .word tls_wl_rx_isr .word tls_wl_mgmt_tx_isr .word tls_wl_data_tx_isr .word PMU_TIMER1_IRQHandler .word PMU_TIMER0_IRQHandler .word PMU_GPIO_WAKE_IRQHandler .word PMU_SDIO_WAKE_IRQHandler .word DMA_Channel0_IRQHandler .word DMA_Channel1_IRQHandler .word DMA_Channel2_IRQHandler .word DMA_Channel3_IRQHandler .word DMA_Channel4_7_IRQHandler .word DMA_BRUST_IRQHandler .word I2C_IRQHandler .word ADC_IRQHandler .word SPI_LS_IRQHandler .word SPI_HS_IRQHandler .word UART0_IRQHandler .word UART1_IRQHandler .word GPIOA_IRQHandler .word TIM0_IRQHandler .word TIM1_IRQHandler .word TIM2_IRQHandler .word TIM3_IRQHandler .word TIM4_IRQHandler .word TIM5_IRQHandler .word WDG_IRQHandler .word PMU_IRQHandler .word FLASH_IRQHandler .word PWM_IRQHandler .word I2S_IRQHandler .word PMU_RTC_IRQHandler .word RSA_IRQHandler .word CRYPTION_IRQHandler .word GPIOB_IRQHandler .word UART2_IRQHandler .size __isr_vector, . - __isr_vector .text .thumb .thumb_func .align 2 .globl Reset_Handler .type Reset_Handler, %function Reset_Handler: /* Firstly it copies data from read only memory to RAM. * * The ranges of copy from/to are specified by following symbols * __etext: LMA of start of the section to copy from. Usually end of text * __data_start__: VMA of start of the section to copy to * __data_end__: VMA of end of the section to copy to * * All addresses must be aligned to 4 bytes boundary. */ ldr r1, =__etext ldr r2, =__data_start__ ldr r3, =__data_end__ .L_loop1: cmp r2, r3 ittt lt ldrlt r0, [r1], #4 strlt r0, [r2], #4 blt .L_loop1 /* Single BSS section scheme. * * The BSS section is specified by following symbols * __bss_start__: start of the BSS section. * __bss_end__: end of the BSS section. * * Both addresses must be aligned to 4 bytes boundary. */ ldr r1, =__bss_start__ ldr r2, =__bss_end__ movs r0, 0 .L_loop2: cmp r1, r2 itt lt strlt r0, [r1], #4 blt .L_loop2 #ifndef __NO_SYSTEM_INIT bl SystemInit #endif bl main .pool .size Reset_Handler, . - Reset_Handler .align 1 .thumb_func .weak Default_Handler .type Default_Handler, %function Default_Handler: b . .size Default_Handler, . - Default_Handler /* Macro to define default handlers. Default handler * will be weak symbol and just dead loops. They can be * overwritten by other handlers */ .macro def_irq_handler handler_name .weak \handler_name .set \handler_name, Default_Handler .endm def_irq_handler NMI_Handler def_irq_handler HardFault_Handler def_irq_handler MemManage_Handler def_irq_handler BusFault_Handler def_irq_handler UsageFault_Handler def_irq_handler SVC_Handler def_irq_handler DebugMon_Handler def_irq_handler PendSV_Handler def_irq_handler OS_CPU_SysTickHandler def_irq_handler SDIO_RX_IRQHandler def_irq_handler SDIO_TX_IRQHandler def_irq_handler SDIO_RX_CMD_IRQHandler def_irq_handler SDIO_TX_CMD_IRQHandler def_irq_handler tls_wl_mac_isr def_irq_handler tls_wl_rx_isr def_irq_handler tls_wl_mgmt_tx_isr def_irq_handler tls_wl_data_tx_isr def_irq_handler PMU_TIMER1_IRQHandler def_irq_handler PMU_TIMER0_IRQHandler def_irq_handler PMU_GPIO_WAKE_IRQHandler def_irq_handler PMU_SDIO_WAKE_IRQHandler def_irq_handler DMA_Channel0_IRQHandler def_irq_handler DMA_Channel1_IRQHandler def_irq_handler DMA_Channel2_IRQHandler def_irq_handler DMA_Channel3_IRQHandler def_irq_handler DMA_Channel4_7_IRQHandler def_irq_handler DMA_BRUST_IRQHandler def_irq_handler I2C_IRQHandler def_irq_handler ADC_IRQHandler def_irq_handler SPI_LS_IRQHandler def_irq_handler SPI_HS_IRQHandler def_irq_handler UART0_IRQHandler def_irq_handler UART1_IRQHandler def_irq_handler GPIOA_IRQHandler def_irq_handler TIM0_IRQHandler def_irq_handler TIM1_IRQHandler def_irq_handler TIM2_IRQHandler def_irq_handler TIM3_IRQHandler def_irq_handler TIM4_IRQHandler def_irq_handler TIM5_IRQHandler def_irq_handler WDG_IRQHandler def_irq_handler PMU_IRQHandler def_irq_handler FLASH_IRQHandler def_irq_handler PWM_IRQHandler def_irq_handler I2S_IRQHandler def_irq_handler PMU_RTC_IRQHandler def_irq_handler RSA_IRQHandler def_irq_handler CRYPTION_IRQHandler def_irq_handler GPIOB_IRQHandler def_irq_handler UART2_IRQHandler .end
YifuLiu/AliOS-Things
hardware/board/haas100/startup/startup_gcc.s
Unix Assembly
apache-2.0
8,530
linux_only_targets="athostapp blink coapapp helloworld http2app httpapp id2_app itls_app jsengine_app linkkit_gateway linkkitapp lwm2mapp meshapp modbus_demo mqttapp otaapp prov_app tls udata_demo.sensor_cloud_demo udata_demo.sensor_local_demo udata_demo.udata_cloud_demo udata_demo.udata_local_demo udataapp ulocation.baseapp yts"
YifuLiu/AliOS-Things
hardware/board/haas100/ucube.py
Python
apache-2.0
332
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef BLE_CONFIG_H #define BLE_CONFIG_H /** * CONFIG_BT: Tx thread stack size */ #ifndef CONFIG_BT_HCI_TX_STACK_SIZE #define CONFIG_BT_HCI_TX_STACK_SIZE 512 #endif #ifndef CONFIG_BT_HCI_RX_STACK_SIZE #define CONFIG_BT_HCI_RX_STACK_SIZE 1024 #endif #ifndef CONFIG_BT_HCI_CMD_COUNT #define CONFIG_BT_HCI_CMD_COUNT 16 #endif #define CONFIG_BT_HOST_RX_THREAD #if defined(__cplusplus) } #endif #endif /* BLE_DEF_CONFIG_H */
YifuLiu/AliOS-Things
hardware/board/haas200/config/ble_config.h
C
apache-2.0
495
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #pragma once #ifdef __cplusplus extern "C" { #endif #define HARDWARE_REVISION "V1.0" #define MODEL "AmebaD" #ifdef BOOTLOADER #define STDIO_UART 0 #define STDIO_UART_BUADRATE 921600 #else #define STDIO_UART 0 #define STDIO_UART_BUADRATE 921600 #endif /****************************************************** * Macros ******************************************************/ /****************************************************** * Constants ******************************************************/ /****************************************************** * Enumerations ******************************************************/ #define MICO_UNUSED 0xFF typedef enum { MICO_GPIO_1, MICO_GPIO_2, MICO_GPIO_3, MICO_GPIO_4, MICO_GPIO_5, MICO_GPIO_6, MICO_GPIO_7, MICO_GPIO_8, MICO_GPIO_9, MICO_GPIO_10, MICO_GPIO_11, MICO_GPIO_12, MICO_GPIO_13, MICO_GPIO_14, MICO_GPIO_15, MICO_GPIO_16, MICO_GPIO_17, MICO_GPIO_18, MICO_GPIO_19, MICO_GPIO_20, MICO_GPIO_21, MICO_GPIO_22, MICO_GPIO_23, MICO_GPIO_24, //MICO_GPIO_26, //MICO_GPIO_27, //MICO_GPIO_28, //MICO_GPIO_29, //MICO_GPIO_30, MICO_GPIO_MAX, /* Denotes the total number of GPIO port aliases. Not a valid GPIO alias */ MICO_GPIO_NONE, } mico_gpio_t; typedef enum { MICO_SPI_1, MICO_SPI_2, MICO_SPI_3, MICO_SPI_MAX, /* Denotes the total number of SPI port aliases. Not a valid SPI alias */ MICO_SPI_NONE, } mico_spi_t; typedef enum { MICO_I2C_1, MICO_I2C_2, MICO_I2C_MAX, /* Denotes the total number of I2C port aliases. Not a valid I2C alias */ MICO_I2C_NONE, } mico_i2c_t; typedef enum { MICO_PWM_1, MICO_PWM_2, MICO_PWM_3, MICO_PWM_4, MICO_PWM_5, MICO_PWM_6, MICO_PWM_7, MICO_PWM_8, MICO_PWM_9, MICO_PWM_10, MICO_PWM_11, MICO_PWM_12, MICO_PWM_13, MICO_PWM_14, MICO_PWM_15, MICO_PWM_16, MICO_PWM_17, MICO_PWM_18, MICO_PWM_MAX, /* Denotes the total number of PWM port aliases. Not a valid PWM alias */ MICO_PWM_NONE, } mico_pwm_t; typedef enum { MICO_ADC_1, MICO_ADC_2, MICO_ADC_3, MICO_ADC_4, MICO_ADC_5, MICO_ADC_6, MICO_ADC_7, MICO_ADC_8, MICO_ADC_MAX, /* Denotes the total number of ADC port aliases. Not a valid ADC alias */ MICO_ADC_NONE, } mico_adc_t; typedef enum { MICO_UART_1, /*km4 hs_uart*/ MICO_UART_2, /*km4 bt uart*/ MICO_UART_3, /*km0 loguart*/ MICO_UART_4, /*km0 lp_uart*/ MICO_UART_MAX, /* Denotes the total number of UART port aliases. Not a valid UART alias */ MICO_UART_NONE, } mico_uart_t; typedef enum { MICO_FLASH_EMBEDDED, MICO_FLASH_SPI, MICO_FLASH_MAX, MICO_FLASH_NONE, } mico_flash_t; typedef enum { MICO_PARTITION_USER_MAX } mico_user_partition_t; typedef enum { MICO_TIMER_0, MICO_TIMER_1, MICO_TIMER_2, MICO_TIMER_3, MICO_TIMER_MAX, } mico_timer_t; #ifdef BOOTLOADER #define STDIO_UART MICO_UART_NONE #define STDIO_UART_BAUDRATE (115200) #else #define STDIO_UART MICO_UART_NONE #define STDIO_UART_BAUDRATE (115200) #endif #define UART_FOR_APP MICO_UART_1 #define MFG_TEST MICO_UART_1 #define CLI_UART MICO_UART_1 /* Components connected to external I/Os*/ #define Standby_SEL (MICO_GPIO_29) /* I/O connection <-> Peripheral Connections */ #define MICO_I2C_CP (MICO_I2C_1) //#define USE_MICO_SPI_FLASH #define MICO_FLASH_FOR_PARA MICO_FLASH_SPI #define PARA_START_ADDRESS (uint32_t)0x00000020 #define PARA_END_ADDRESS (uint32_t)0x00003FFF #define PARA_FLASH_SIZE (PARA_END_ADDRESS - PARA_START_ADDRESS + 1) /* 4k bytes*/ #ifdef __cplusplus } /*extern "C" */ #endif
YifuLiu/AliOS-Things
hardware/board/haas200/config/board.h
C
apache-2.0
3,942
#ifndef _PCA10040_MESH_CONFIG_H_ #define _PCA10040_MESH_CONFIG_H_ /* Generic options */ #define CONFIG_BT_MESH_MODEL_KEY_COUNT 2 #define CONFIG_BT_MESH_MODEL_GROUP_COUNT 2 #define CONFIG_BT_MESH_APP_KEY_COUNT 1 #define CONFIG_BT_MESH_SUBNET_COUNT 2 #define CONFIG_BT_MESH_CRPL 5 #define CONFIG_BT_MESH_ADV_BUF_COUNT 32 #define CONFIG_BT_MESH_LABEL_COUNT 1 #define CONFIG_BT_MESH_MSG_CACHE_SIZE 2 #define CONFIG_BT_MESH_TX_SEG_MSG_COUNT 2 #define CONFIG_BT_MESH_RX_SDU_MAX 36 #define CONFIG_BT_MESH_RX_SEG_MSG_COUNT 2 #define CONFIG_BT_MESH_ADV_PRIO 41 #define CONFIG_BT_MESH_PROXY_FILTER_SIZE 1 #define CONFIG_BT_MESH_NODE_ID_TIMEOUT 60 /* Friend related options */ #ifdef CONFIG_BT_MESH_FRIEND #define CONFIG_BT_MESH_FRIEND_RECV_WIN 255 #define CONFIG_BT_MESH_FRIEND_QUEUE_SIZE 16 #define CONFIG_BT_MESH_FRIEND_SUB_LIST_SIZE 3 #define CONFIG_BT_MESH_FRIEND_LPN_COUNT 2 #define CONFIG_BT_MESH_FRIEND_SEG_RX 1 #endif // CONFIG_BT_MESH_FRIEND /* Low power related options */ #ifdef CONFIG_BT_MESH_LOW_POWER #define CONFIG_BT_MESH_LPN_ESTABLISHMENT #define CONFIG_BT_MESH_LPN_AUTO #define CONFIG_BT_MESH_LPN_AUTO_TIMEOUT 15 #define CONFIG_BT_MESH_LPN_RETRY_TIMEOUT 8 #define CONFIG_BT_MESH_LPN_RSSI_FACTOR 0 #define CONFIG_BT_MESH_LPN_RECV_WIN_FACTOR 0 #define CONFIG_BT_MESH_LPN_MIN_QUEUE_SIZE 1 #define CONFIG_BT_MESH_LPN_RECV_DELAY 100 #define CONFIG_BT_MESH_LPN_POLL_TIMEOUT 300 #define CONFIG_BT_MESH_LPN_INIT_POLL_TIMEOUT CONFIG_BT_MESH_LPN_POLL_TIMEOUT #define CONFIG_BT_MESH_LPN_SCAN_LATENCY 10 #define CONFIG_BT_MESH_LPN_GROUPS 8 #endif // CONFIG_BT_MESH_LOW_POWER /* Proxy related options */ #ifdef CONFIG_BT_MESH_PROXY #define CONFIG_BT_MESH_PROXY_FILTER_SIZE 1 #endif // BT_MESH_PROXY #endif
YifuLiu/AliOS-Things
hardware/board/haas200/config/bt_mesh_opt.h
C
apache-2.0
1,706
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <k_api.h> // #include "hal_gpio.h" // #include "hal_sleep.h" // #include "hal_timer.h" #include "board.h" //#include "watchdog.h" #if RHINO_CONFIG_USER_HOOK extern const k_mm_region_t g_mm_region[]; extern int g_region_num; static int mem_in_heap(uint32_t addr) { int i; for(i = 0; i < g_region_num; i++){ if(addr > (uint32_t)g_mm_region[i].start && addr < (uint32_t)g_mm_region[i].start + g_mm_region[i].len){ return 1; } } return 0; } void krhino_tick_hook(void) { // do nothing } // HWTIMER_ID krhino_sleep_timer; // void krhino_sleep(void) // { // hal_sleep_enter_sleep(); // } static int idle_sleep = 1; // swd will set it void krhino_idle_hook_onoff(int onoff) { idle_sleep = onoff; } void krhino_idle_hook(void) { } void aos_trace_crash_notify() { abort(); } void krhino_idle_pre_hook(void) { } void krhino_start_hook(void) { } void krhino_task_create_hook(ktask_t *task) { } void krhino_task_del_hook(ktask_t *task, res_free_t *arg) { /*free task->task_sem_obj*/ void * task_sem = task->task_sem_obj; g_sched_lock[cpu_cur_get()]++; if(task_sem) { krhino_task_sem_del(task); if(mem_in_heap((uint32_t)task_sem)){ aos_free(task_sem); } task->task_sem_obj = NULL; } g_sched_lock[cpu_cur_get()]--; return; } void krhino_init_hook(void) { } void krhino_task_switch_hook(ktask_t *orgin, ktask_t *dest) { } void krhino_mm_alloc_hook(void *mem, size_t size) { } void krhino_task_abort_hook(ktask_t *task) { } #endif
YifuLiu/AliOS-Things
hardware/board/haas200/config/k_config.c
C
apache-2.0
1,632
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #ifndef K_CONFIG_H #define K_CONFIG_H /* kernel feature conf */ #ifndef RHINO_CONFIG_SEM #define RHINO_CONFIG_SEM 1 #endif #ifndef RHINO_CONFIG_QUEUE #define RHINO_CONFIG_QUEUE 1 #endif #ifndef RHINO_CONFIG_TASK_SEM #define RHINO_CONFIG_TASK_SEM 1 #endif #ifndef RHINO_CONFIG_EVENT_FLAG #define RHINO_CONFIG_EVENT_FLAG 1 #endif #ifndef RHINO_CONFIG_TIMER #define RHINO_CONFIG_TIMER 1 #endif #ifndef RHINO_CONFIG_BUF_QUEUE #define RHINO_CONFIG_BUF_QUEUE 1 #endif /* kernel task conf */ #ifndef RHINO_CONFIG_TASK_INFO #define RHINO_CONFIG_TASK_INFO 1 #endif #ifndef RHINO_CONFIG_TASK_DEL #define RHINO_CONFIG_TASK_DEL 1 #endif #ifndef RHINO_CONFIG_TASK_STACK_OVF_CHECK #define RHINO_CONFIG_TASK_STACK_OVF_CHECK 1 #endif #ifndef RHINO_CONFIG_SCHED_RR #define RHINO_CONFIG_SCHED_RR 1 #endif #ifndef RHINO_CONFIG_TIME_SLICE_DEFAULT #define RHINO_CONFIG_TIME_SLICE_DEFAULT 50 #endif #ifndef RHINO_CONFIG_PRI_MAX #define RHINO_CONFIG_PRI_MAX 62 #endif #ifndef RHINO_CONFIG_USER_PRI_MAX #define RHINO_CONFIG_USER_PRI_MAX (RHINO_CONFIG_PRI_MAX - 2) #endif /* kernel workqueue conf */ //#ifndef RHINO_CONFIG_WORKQUEUE #define RHINO_CONFIG_WORKQUEUE 1 //#endif #ifndef RHINO_CONFIG_WORKQUEUE_STACK_SIZE #define RHINO_CONFIG_WORKQUEUE_STACK_SIZE 768 #endif /* kernel timer&tick conf */ #ifndef RHINO_CONFIG_TICKS_PER_SECOND #define RHINO_CONFIG_TICKS_PER_SECOND 1000 #endif /*must reserve enough stack size for timer cb will consume*/ #ifndef RHINO_CONFIG_TIMER_TASK_STACK_SIZE #define RHINO_CONFIG_TIMER_TASK_STACK_SIZE 2048 #endif #ifndef RHINO_CONFIG_TIMER_TASK_PRI #define RHINO_CONFIG_TIMER_TASK_PRI 5 #endif /* kernel intrpt conf */ #ifndef RHINO_CONFIG_INTRPT_STACK_OVF_CHECK #define RHINO_CONFIG_INTRPT_STACK_OVF_CHECK 0 #endif /* kernel dyn alloc conf */ #ifndef RHINO_CONFIG_KOBJ_DYN_ALLOC #define RHINO_CONFIG_KOBJ_DYN_ALLOC 1 #endif #if (RHINO_CONFIG_KOBJ_DYN_ALLOC > 0) #ifndef RHINO_CONFIG_K_DYN_TASK_STACK #define RHINO_CONFIG_K_DYN_TASK_STACK 256 #endif #ifndef RHINO_CONFIG_K_DYN_MEM_TASK_PRI #define RHINO_CONFIG_K_DYN_MEM_TASK_PRI 6 #endif #endif /* kernel idle conf */ #ifndef RHINO_CONFIG_IDLE_TASK_STACK_SIZE #define RHINO_CONFIG_IDLE_TASK_STACK_SIZE 1024 #endif /* kernel hook conf */ #ifndef RHINO_CONFIG_USER_HOOK #define RHINO_CONFIG_USER_HOOK 1 #endif #ifndef RHINO_CONFIG_CPU_NUM #define RHINO_CONFIG_CPU_NUM 1 #endif /*task user info index start*/ #ifndef RHINO_CONFIG_TASK_INFO_NUM #define RHINO_CONFIG_TASK_INFO_NUM 5 #endif #ifndef PTHREAD_CONFIG_USER_INFO_POS #define PTHREAD_CONFIG_USER_INFO_POS 0 #endif #ifndef RHINO_TASK_HOOK_USER_INFO_POS #define RHINO_TASK_HOOK_USER_INFO_POS 1 #endif #ifndef RHINO_CLI_CONSOLE_USER_INFO_POS #define RHINO_CLI_CONSOLE_USER_INFO_POS 2 #endif #ifndef RHINO_ERRNO_USER_INFO_POS #define RHINO_ERRNO_USER_INFO_POS 3 #endif /*task user info index end*/ #ifndef RHINO_CONFIG_SYS_STATS #define RHINO_CONFIG_SYS_STATS 1 #endif #ifndef RHINO_CONFIG_HW_COUNT #define RHINO_CONFIG_HW_COUNT 1 #endif #ifndef RHINO_CONFIG_MM_TRACE_LVL #define RHINO_CONFIG_MM_TRACE_LVL 0 #endif #ifndef RHINO_CONFIG_CLI_AS_NMI #define RHINO_CONFIG_CLI_AS_NMI 0 #endif #if (RHINO_CONFIG_CLI_AS_NMI > 0) #ifndef RHINO_CONFIG_NMI_OFFSET #define RHINO_CONFIG_NMI_OFFSET 40 #endif #endif #endif /* K_CONFIG_H */
YifuLiu/AliOS-Things
hardware/board/haas200/config/k_config.h
C
apache-2.0
3,701
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <aos/flashpart_core.h> #include <aos/hal/flash.h> static int flash_partitions_init(void) { static aos_flashpart_t partitions[] = { { .dev = { .id = HAL_PARTITION_BOOTLOADER, }, .flash_id = 0, .block_start = 0x4, .block_count = 0x2, }, { .dev = { .id = HAL_PARTITION_PARAMETER_1, }, .flash_id = 0, .block_start = 0x3FF, .block_count = 0x1, }, { .dev = { .id = HAL_PARTITION_PARAMETER_2, }, .flash_id = 0, .block_start = 0x3FD, .block_count = 0x2, }, { .dev = { .id = HAL_PARTITION_PARAMETER_4, }, .flash_id = 0, .block_start = 0x3FC, .block_count = 0x1, }, { .dev = { .id = HAL_PARTITION_PARAMETER_3, }, .flash_id = 0, .block_start = 0x3FB, .block_count = 0x1, }, { .dev = { .id = HAL_PARTITION_APPLICATION, }, .flash_id = 0, .block_start = 0x14, .block_count = 0x200, }, { .dev = { .id = HAL_PARTITION_OTA_TEMP, }, .flash_id = 0, .block_start = 0x214, .block_count = 0x140, }, { .dev = { .id = HAL_PARTITION_LITTLEFS, }, .flash_id = 0, .block_start = 0x354, .block_count = 0xA7, }, { .dev = { .id = HAL_PARTITION_BOOT1, }, .flash_id = 0, .block_start = 0x6, .block_count = 0xE, }, }; for (size_t i = 0; i < sizeof(partitions) / sizeof(partitions[0]); i++) { int ret; ret = aos_flashpart_register(&partitions[i]); if (ret) { for (size_t j = 0; j < i; j++) (void)aos_flashpart_unregister(partitions[j].dev.id); return ret; } } return 0; } LEVEL1_DRIVER_ENTRY(flash_partitions_init)
YifuLiu/AliOS-Things
hardware/board/haas200/config/partition_conf.c
C
apache-2.0
2,127
#include "aos/hal/gpio.h" #include "gpio_test.h" const qc_test_gpio_pair_t qc_test_gpio_pairs[1]; const int qc_test_gpio_pairs_num = 0;
YifuLiu/AliOS-Things
hardware/board/haas200/gpio_test_pair.c
C
apache-2.0
150
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <aos/kernel.h> #include "board.h" #include "aos/hal/uart.h" #include <aos/init.h> static uart_dev_t uart_0; void board_stduart_init() { uart_0.port = MICO_UART_1; uart_0.config.baud_rate = 115200; uart_0.config.data_width = DATA_WIDTH_8BIT; uart_0.config.parity = NO_PARITY; uart_0.config.stop_bits = STOP_BITS_1; uart_0.config.flow_control = FLOW_CONTROL_DISABLED; hal_uart_init(&uart_0); } void board_dma_init() { } void board_gpio_init() { } void board_tick_init() { } void board_kinit_init(kinit_t* init_args) { /* Use default args in demos.*/ } void board_flash_init() { } void board_network_init() { }
YifuLiu/AliOS-Things
hardware/board/haas200/startup/board.c
C
apache-2.0
756
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include "aos/kernel.h" #include <k_api.h> #include <stdio.h> #include <stdlib.h> #include "aos/init.h" #include "aos/kernel.h" #include "aos/hal/wdg.h" #include "aos/hal/gpio.h" #include "rtl8721d.h" #include "core_armv8mml.h" #include "osdep_service.h" //#include "rtl8710b_ota.h" #define AOS_START_STACK 2048 /* 8KB */ ktask_t *g_aos_init; extern void board_init(void); extern void sys_jtag_off(void); extern uint32_t SystemCoreClock; void sys_open_security_boot_log(void) { u32 temp; temp = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_SYS_EFUSE_SYSCFG3); if((temp & BIT_SYS_DIS_BOOT_LOG_EN) != 0) { temp &= ~BIT_SYS_DIS_BOOT_LOG_EN; EFUSE_LMAP_WRITE(0xe, 2, ((u8*)&temp) + 2); } } static void hal_init() { sys_jtag_off(); sys_open_security_boot_log(); } extern void hw_start_hal(void); void dump_mem_info(){} void start_ate(void) { u32 img2_addr = 0x080D0000; IMAGE_HEADER *img2_hdr = (IMAGE_HEADER *)img2_addr; IMAGE_HEADER *ram_img2_hdr = (IMAGE_HEADER *)(img2_addr + IMAGE_HEADER_LEN + img2_hdr->image_size); u8 *ram_img2_data = (u8*)(ram_img2_hdr + 1); u8 *ram_img2_valid_code = ram_img2_data + 8; if (_strcmp((const char *)ram_img2_valid_code, (const char *)"RTKWin")) { DBG_8195A("IMG_BOOTUSER SIGN Invalid\n"); while(1); } /* load ram image2 data into RAM */ _memcpy((void *)ram_img2_hdr->image_addr, ram_img2_data, ram_img2_hdr->image_size); PRAM_START_FUNCTION img2_entry_fun = (PRAM_START_FUNCTION)ram_img2_data; img2_entry_fun->RamStartFun(); } /* For QC test */ static void board_mode_check(void) { #define KEY_ELINK 12 #define KEY_BOOT 9 gpio_dev_t gpio_key_boot; gpio_key_boot.port = KEY_BOOT; gpio_key_boot.config = INPUT_PULL_UP; hal_gpio_init(&gpio_key_boot); uint32_t boot; hal_gpio_input_get(&gpio_key_boot, &boot); gpio_dev_t gpio_key_elink; gpio_key_elink.port = KEY_ELINK; gpio_key_elink.config = INPUT_PULL_UP; hal_gpio_init(&gpio_key_elink); uint32_t elink; hal_gpio_input_get(&gpio_key_elink, &elink); printf("--------------------------------> built at "__DATE__" "__TIME__"\r\n"); hal_gpio_input_get(&gpio_key_boot, &boot); printf("--------------------------------> boot %d, elink %d \r\n", boot, elink); if(boot == 0) { if(elink == 0) start_ate(); else qc_test(0); } if(elink == 0){ if(OTA_INDEX_1 == ota_get_cur_index()) { OTA_Change(OTA_INDEX_2); printf("-----change OTA 2 \r\n"); } else { OTA_Change(OTA_INDEX_1); printf("-----change OTA 1 \r\n"); } aos_msleep(1000); hal_reboot(); } board_init(); } extern u32 GlobalDebugEnable; void sys_init_func(void) { InterruptRegister(IPC_INTHandler, IPC_IRQ, (u32)IPCM0_DEV, 5); InterruptEn(IPC_IRQ, 5); hal_init(); #ifdef USE_MX1290 board_mode_check(); #endif #ifdef AOS_COMP_CPLUSPLUS cpp_init(); #endif GlobalDebugEnable = 0; aos_maintask(NULL); krhino_task_dyn_del(NULL); } #if (DEBUG_CONFIG_PANIC == 1) typedef void (*HAL_VECTOR_FUN) (void ); extern HAL_VECTOR_FUN NewVectorTable[]; extern void HardFault_Handler(void); #endif void main(void) { hal_wdg_finalize(0); aos_init(); #if (DEBUG_CONFIG_PANIC == 1) /* AliOS-Things taking over the exception */ /* replace HardFault Vector */ NewVectorTable[3] = HardFault_Handler; /* replace MemManage Vector */ NewVectorTable[4] = HardFault_Handler; /* replace BusFault Vector */ NewVectorTable[5] = HardFault_Handler; /* replace UsageFault Vector */ NewVectorTable[6] = HardFault_Handler; #endif krhino_task_dyn_create(&g_aos_init, "aos-init", 0, AOS_DEFAULT_APP_PRI , 0, AOS_START_STACK, (task_entry_t)sys_init_func, 1); SysTick_Config(SystemCoreClock/RHINO_CONFIG_TICKS_PER_SECOND); soc_hw_timer_init(); aos_start(); return; }
YifuLiu/AliOS-Things
hardware/board/haas200/startup/startup.c
C
apache-2.0
4,042
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include "aos/hal/adc.h" #include "aos/cli.h" struct adc_check { adc_dev_t st_adc_info; uint32_t test_threshold; uint32_t test_jitter; }; static struct adc_check edu_adc_dev[3] = { {{0, 1000, 0x12345678}, 200, 250}, // mic adc {{1, 1000, 0x12345678}, 1500, 300}, // vol {{2, 1000, 0x12345678}, 1100, 300}, // extra IO }; #define TEST_VOLT_MV 1500 static int32_t adc_test_process(uint32_t port) { int32_t ret = 0; uint32_t output = 0; uint32_t test_sum = 0; uint32_t test_avrg = 0; uint32_t test_min = 3300; uint32_t test_max = 0; ret = hal_adc_init(&edu_adc_dev[port].st_adc_info); if (ret) { printf("\r\n=====adc test : adc init failed===\r\n"); return -1; } for (int32_t i = 0; i < 34; i++) { hal_adc_value_get(&edu_adc_dev[port].st_adc_info, &output, 1000); test_sum += output; /* the min sampling voltage */ if (test_min >= output) { test_min = output; } /* the max sampling voltage */ if (test_max <= output) { test_max = output; } osDelay(20); } hal_adc_finalize(&edu_adc_dev[port].st_adc_info); test_avrg = (test_sum - test_min - test_max) >> 5; printf("\r\n=====adc test : the samping volage is:%dmv===\r\n", test_avrg); if (port != 0) { if (((test_avrg - edu_adc_dev[port].test_jitter) > edu_adc_dev[port].test_threshold) || ((test_avrg + edu_adc_dev[port].test_jitter) < edu_adc_dev[port].test_threshold)) { printf("\r\n=====adc test : the samping volage is out of scope===\r\n"); printf("\r\n=====adc test : FAIL===\r\n"); return -1; } } else { if (test_avrg < 1) { printf("\r\n=====adc test : the samping volage is out of scope===\r\n"); printf("\r\n=====adc test : FAIL===\r\n"); return -1; } // goto } printf("=====adc test : Done=====\r\n"); return 0; } static int adc_autotest(uint32_t port) { int32_t ret = 0; printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("*************************** ADC Test **************************\r\n"); printf("***************************************************************\r\n"); printf("** Note: adc Test include 3 section **\r\n"); printf("***************************************************************\r\n"); printf("=====adc test : Start=====\r\n"); ret = adc_test_process(port); if (ret) { printf("\r\n=====adc test : FAIL ===\r\n"); return -1; } printf("\r\n=====adc test : PASS===\r\n"); return 0; } static void handle_adctest_cmd(char *pwbuf, int blen, int argc, char **argv) { if (argv != 2) return; adc_autotest(atoi(argv[1])); } static struct cli_command adctest_cmd = { .name = "adctest index", .help = "adctest index", .function = handle_adctest_cmd }; int adc_test(uint32_t port) { aos_cli_register_command(&adctest_cmd); return adc_autotest(port); }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/adc_test.c
C
apache-2.0
3,288
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "k_api.h" #include "aos/cli.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_player.h" #include "uvoice_recorder.h" #include <aos/kernel.h> #include "uvoice_init.h" #include "uvoice_test.h" aos_task_t g_audio_test_task; static char *param_array[2]; static int audio_loopback_flag = 1; static uvoice_player_t *uvocplayer; extern int audio_install_codec_driver(); void audio_test_stop(int item) { if (item == 0) { char *param_array[2]; param_array[0] = "play"; param_array[1] = "stop"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); } else { param_array[0] = "loopback"; param_array[1] = "stop"; sound_example_loopback_entry(2, param_array); } } int audio_test_speeker(void) { param_array[0] = "play"; param_array[1] = "stopsync"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "fs:/data/mp3/teststart.mp3"; uvoice_play_test(2, param_array); return 0; } void cmd_audiotest_handler(char *buf, int len, int argc, char **argv) { char *param_array[2]; if (argc < 2 || strcmp(argv[0], "play")) return; if (!strcmp(argv[1], "pause")) { param_array[0] = "play"; param_array[1] = "pause"; uvoice_play_test(2, param_array); } else if (!strcmp(argv[1], "resume")) { param_array[0] = "play"; param_array[1] = "resume"; uvoice_play_test(2, param_array); } else if (!strcmp(argv[1], "loopback")) { param_array[0] = "play"; param_array[1] = "loopback"; uvoice_play_test(2, param_array); } else if (!strcmp(argv[1], "stop")) { param_array[0] = "play"; param_array[1] = "stop"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); } else { param_array[0] = "play"; param_array[1] = "stopsync"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = "clear"; uvoice_play_test(2, param_array); param_array[0] = "play"; param_array[1] = argv[1]; uvoice_play_test(2, param_array); } } struct cli_command audio_test_commands[] = { {"play", "try 'play fs:/data/mp3/teststart.mp3' | 'play url' | play pause | play pause | play resume", cmd_audiotest_handler} }; int audio_test(int item) { if (item == 0) { uvoice_init(); audio_install_codec_driver(); aos_set_master_volume(100); aos_cli_register_commands(audio_test_commands, sizeof(audio_test_commands) / sizeof(struct cli_command)); aos_task_create(&g_audio_test_task, "audio_test_speeker", audio_test_speeker, NULL, NULL, 4096, 30, 0x01u); } else if (item == 1) { printf("\r\n\r\n"); printf("****************************************************************\r\n"); printf("************************* Audio Test ***************************\r\n"); printf("****************************************************************\r\n"); printf("*How to test: please speaker any words, then you will hear it **\r\n"); printf("****************************************************************\r\n"); printf("===== AUDIO test : Start=====\r\n"); param_array[0] = "loopback"; param_array[1] = "start"; sound_example_loopback_entry(2, param_array); } }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/audio_test.c
C
apache-2.0
3,858
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include <k_api.h> #include "board.h" #include "aos/cli.h" #include <aos/ble.h> #include <bluetooth/bluetooth.h> #include <bluetooth/conn.h> #include <atomic.h> #include <work.h> #include <bluetooth/gatt.h> #include <bluetooth/uuid.h> static int bt_scan_start(); #define EXAMPLE_BLE_DEV_NAME "HaaS BLE" #define DEVICE_ADDR {0xE8, 0x3B, 0xE3, 0x88, 0xB4, 0xC8} static int bt_devices_find = 0; static void handle_ble_cmd(char *pwbuf, int blen, int argc, char **argv) { int id; char *onoff; printf("enable ble_cmd\n"); bt_scan_start(); } static int ble_scanf_result(uint32_t timeout) { #if 1 while (!bt_devices_find || timeout--) { aos_msleep(500); } #endif ble_stack_scan_stop(); if (bt_devices_find != 0) { printf("====Result: BT test PASS !!!===\n"); return 0; } else { printf("\r\n=====BT test : FAIL===\r\n"); return -1; } } static void device_find(ble_event_en event, void *event_data) { int ret = -1; int uuid_peer = -1; evt_data_gap_dev_find_t ee; evt_data_gap_dev_find_t *e; uint8_t find_dev = 0; memcpy(&ee, event_data, sizeof(evt_data_gap_dev_find_t)); e = &ee; if (e->adv_type != ADV_IND) { return; } if (e->adv_len > 31) { return; } printf("find BT device %x-%x-%x-%x-%x-%x RssI:%d\n", e->dev_addr.val[0], e->dev_addr.val[1], e->dev_addr.val[2], e->dev_addr.val[3], e->dev_addr.val[4], e->dev_addr.val[5], e->rssi); bt_devices_find++; } static int event_callback(ble_event_en event, void *event_data) { switch (event) { case EVENT_GAP_DEV_FIND: device_find(event, event_data); break; default: // printf("Unhandle event %d\n", event); break; } return 0; } static int bt_scan_start() { int ret; scan_param_t param = { SCAN_PASSIVE, SCAN_FILTER_DUP_ENABLE, SCAN_FAST_INTERVAL, SCAN_FAST_WINDOW, }; bt_devices_find = 0; ret = ble_stack_scan_start(&param); if (ret) { return ret; } return 0; } static ble_event_cb_t ble_cb = { .callback = event_callback, }; int example_BLE_init(void) { int ret; dev_addr_t addr = {DEV_ADDR_LE_RANDOM, DEVICE_ADDR}; init_param_t init = { .dev_name = EXAMPLE_BLE_DEV_NAME, .dev_addr = &addr, .conn_num_max = 1, }; /* we need first init hci driver */ hci_h4_driver_init(); /* bt stack init */ ret = ble_stack_init(&init); if (ret) { return -1; } ret = ble_stack_event_register(&ble_cb); if (ret) { return -1; } return 0; } int ble_test_process() { int ret = 0; printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* BT Connect Test *******************\r\n"); printf("*How to test: find any BT devices as successed. *****\r\n"); printf("***************************************************************\r\n"); printf("=====BT Connect test : Start=====\r\n"); ret = example_BLE_init(); if (ret) { return ret; } bt_scan_start(); return ble_scanf_result(5); } static struct cli_command ble_cmd = { .name = "ble", .help = "ble scan", .function = handle_ble_cmd }; int ble_test(void) { aos_cli_register_command(&ble_cmd); return ble_test_process(); }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/ble_test.c
C
apache-2.0
3,613
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #include "aos/cli.h" #include "aos/hal/flash.h" #include "do.h" #include "led.h" #include "key.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" #include "netmgr.h" #include <uservice/uservice.h> #include <uservice/eventid.h> #include <netmgr_wifi.h> #define UNKNOWN_RESULT 99 #define USE_QUICK_WIFI_TEST typedef enum { TEST_NULL, TEST_LED, TEST_KEY, TEST_UART_TTL, TEST_SPI, TEST_I2C, TEST_PWM, TEST_ADC, TEST_SD, TEST_WIFI_CONN, TEST_BT, TEST_WATCHDOG, TEST_NOISE, TEST_USB, TEST_AUDIO, TEST_EXTRAIO, TEST_GADC2, TEST_OLED, // i2c devices TEST_HUMI, TEST_GYRO, TEST_MAG, TEST_BARO, TEST_ALS, TEST_MAX, }; typedef struct { char *name; int result; } test_record_t; extern void led_test(void); extern int ble_test(void); extern int key_test(void); extern int pwm_test(); extern int adc_test(uint32_t port); extern int sdcard_test(void); extern void watchdog_test(); extern void led_blink(void); extern void oled_blink(void); extern int audio_test(int item); extern int usb_test(void); extern int sensors_test(int index); extern void edu_oled_show(char *buf, int len); extern void audio_test_stop(int item); aos_task_t g_extraio_test_task; extern aos_task_t g_led_test_task; test_record_t test_rec_group[TEST_MAX] = { [TEST_LED] = { .name = "LED", .result = UNKNOWN_RESULT, }, [TEST_KEY] = { .name = "KEY", .result = UNKNOWN_RESULT, }, [TEST_UART_TTL] = { .name = "UART", .result = UNKNOWN_RESULT, }, [TEST_SPI] = { .name = "SPI", .result = UNKNOWN_RESULT, }, [TEST_I2C] = { .name = "I2C", .result = UNKNOWN_RESULT, }, [TEST_PWM] = { .name = "PWM", .result = UNKNOWN_RESULT, }, [TEST_ADC] = { .name = "ADC", .result = UNKNOWN_RESULT, }, [TEST_SD] = { .name = "SD", .result = UNKNOWN_RESULT, }, [TEST_WIFI_CONN] = { .name = "WIFI CONNECT", .result = UNKNOWN_RESULT, }, [TEST_BT] = { .name = "BT", .result = UNKNOWN_RESULT, }, [TEST_WATCHDOG] = { .name = "WATCHDOG", .result = UNKNOWN_RESULT, }, [TEST_NOISE] = { .name = "NOISE", .result = UNKNOWN_RESULT, }, [TEST_USB] = { .name = "USB", .result = UNKNOWN_RESULT, }, [TEST_AUDIO] = { .name = "AUDIO", .result = UNKNOWN_RESULT, }, [TEST_EXTRAIO] = { .name = "EXTRAIO", .result = UNKNOWN_RESULT, }, [TEST_GADC2] = { .name = "GADC2", .result = UNKNOWN_RESULT, }, [TEST_OLED] = { .name = "OLED", .result = UNKNOWN_RESULT, }, [TEST_HUMI] = { .name = "HUMITURE", .result = UNKNOWN_RESULT, }, [TEST_GYRO] = { .name = "GYRO", .result = UNKNOWN_RESULT }, [TEST_MAG] = { .name = "MAG", .result = UNKNOWN_RESULT }, [TEST_BARO] = { .name = "BARO", .result = UNKNOWN_RESULT }, [TEST_ALS] = { .name = "ALS", .result = UNKNOWN_RESULT }, // extraboard_test end }; static int _ip_got_finished = 0; uint32_t led_test_flag = 0; uint32_t oled_test_flag = 0; uint32_t extraio_test_flag = 0; uint32_t audio_test_flag = 0; uint32_t auto_test_flag = 0; uint32_t extra_test_enable = 1; uint32_t keytest_successed = 0; int show_last_autotest_results() { int len = 4; char buff[5] = {0}; char buf[2] = {0}; char buff_lan[21] = {0}; char buff_rel[21] = "PASS !"; int j = 0; int k = 0; OLED_Clear(); if (0 == aos_kv_get(test_rec_group[1].name, buff, &len)) { printf("\r\n\r\n"); printf("**************************************************************\r\n"); printf("**************************AUTO TEST RESULT********************\r\n"); printf("--------------------------------------------------------------\r\n"); printf("Test Items Result \r\n"); printf("--------------------------------------------------------------\r\n"); for (int i = 1; i < TEST_MAX; i++) { int ret = 0; memset(buff, 0, sizeof(buff)); ret = aos_kv_get(test_rec_group[i].name, buff, &len); if (0 == strncmp(buff, "WAIT", 4)) { memcpy(buff, "PASS", 4); } if (ret == 0) { printf("%12s %s\n", test_rec_group[i].name, buff); // memcpy(buf,test_rec_group[i].name, 2); if (0 == strncmp(buff, "PASS", 4)) { buff_lan[j] = 'Y'; } else { buff_lan[j] = 'N'; memcpy(buff_rel, "FAIL !", 7); } j++; k++; if (k % 10 == 0) { buff_lan[j++] = ' '; } } aos_kv_del(test_rec_group[i].name); } OLED_Show_String(1, 4, "Auto Test Result:", 12, 1); OLED_Show_String(20, 16, buff_rel, 12, 1); OLED_Show_String(2, 28, "1234567890 123456789", 12, 1); OLED_Show_String(2, 40, "|||||||||| |||||||||", 12, 1); OLED_Show_String(2, 52, buff_lan, 12, 1); OLED_Refresh_GRAM(); printf("**************************************************************\r\n"); printf("**************************************************************\r\n"); printf("**************************************************************\r\n"); return 0; } return 1; } static void wifi_event_cb(uint32_t event_id, const void *param, void *context) { aos_task_t task; aos_status_t ret; if (event_id != EVENT_NETMGR_DHCP_SUCCESS) return; if (_ip_got_finished != 0) return; _ip_got_finished = 1; } #ifndef USE_QUICK_WIFI_TEST static int mfg_wifi_connect(const char *ssid, const char *passwd) { netmgr_hdl_t hdl; netmgr_connect_params_t params; hdl = netmgr_get_dev("/dev/wifi0"); if (hdl == -1) { printf("netmgr_get_dev failed! \r\n"); return -1; } memset(&params, 0, sizeof(netmgr_connect_params_t)); strncpy(params.params.wifi_params.ssid, ssid, sizeof(params.params.wifi_params.ssid) - 1); strncpy(params.params.wifi_params.pwd, passwd, sizeof(params.params.wifi_params.pwd) - 1); params.params.wifi_params.timeout = 15000; netmgr_connect(hdl, &params); return 0; } #endif void extraio_test(void) { unsigned int oled_id = 0; while (extraio_test_flag) { if ((oled_id % 8) == 0) { aos_msleep(500); for (int i = 0; i < 8; i++) { expansion_board_do_low(i); } } aos_msleep(200); expansion_board_do_high(oled_id % 8); oled_id++; } } static void beep() { gpio_dev_t beeper; /* set as output mode */ beeper.port = HAL_IOMUX_PIN_P2_6; beeper.config = OUTPUT_PUSH_PULL; hal_gpio_init(&beeper); hal_gpio_output_high(&beeper); aos_msleep(100); hal_gpio_output_low(&beeper); } void test_process_entry() { uint8_t value = 0; int len = 1; int ret = 0; printf("Haas edu test entry here! version build time %s:%s \r\n", __DATE__, __TIME__); sh1106_init(); ret = show_last_autotest_results(); if (ret == 0) { return; } if (0 == aos_kv_get("factory_test_extra", &value, &len)) { extra_test_enable = 1; } key_test(); led_test_flag = 1; oled_test_flag = 1; extraio_test_flag = 1; audio_test_flag = 1; OLED_Clear(); /*first, init the value*/ { test_rec_group[TEST_LED].result = -1; test_rec_group[TEST_OLED].result = -1; test_rec_group[TEST_EXTRAIO].result = -1; test_rec_group[TEST_AUDIO].result = -1; } #if 1 OLED_Show_String(4, 4, "Led pass -- prs k1.", 12, 1); OLED_Show_String(4, 16, "Oled pass -- prs k2.", 12, 1); OLED_Show_String(4, 28, "Extra pass -- prs k3.", 12, 1); OLED_Show_String(4, 40, "Voice pass -- prs k4.", 12, 1); OLED_Show_String(2, 52, "Pls K1+K2 to autotest", 12, 1); #endif OLED_Refresh_GRAM(); #if 1 led_test(); aos_task_create(&g_extraio_test_task, "extraio_test", extraio_test, NULL, NULL, 4096, 30, 0x01u); audio_test(0); while (auto_test_flag != 1 || keytest_successed != 0xF) { // printf("keytest_successed %x\n",keytest_successed); if (led_test_flag == 0) { printf("\r\n\r\n******************************************\r\n\r\n"); printf("\r\n\r\n====Result: LED test PASS !!!=== \r\n\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); led_test_flag = 1; aos_task_delete(&g_led_test_task); OLED_Clear(); OLED_Show_String(8, 8, "Key 1 pressed!", 12, 1); OLED_Show_String(6, 30, "Led-test passed!", 12, 1); OLED_Refresh_GRAM(); audio_test_stop(0); beep(); test_rec_group[TEST_LED].result = 0; } if (oled_test_flag == 0) { printf("\r\n\r\n******************************************\r\n\r\n"); printf("\r\n\r\n====Result: OELD test PASS !!!=== \r\n\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); oled_test_flag = 1; beep(); OLED_Clear(); OLED_Show_String(8, 8, "Key 2 pressed!", 12, 1); OLED_Show_String(6, 30, "Oled-test passed!", 12, 1); OLED_Refresh_GRAM(); audio_test_stop(0); test_rec_group[TEST_OLED].result = 0; } if (extraio_test_flag == 0) { printf("\r\n\r\n******************************************\r\n\r\n"); printf("\r\n\r\n====Result: EXTRAIO test PASS !!!=== \r\n\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); extraio_test_flag = 1; beep(); OLED_Clear(); OLED_Show_String(8, 8, "Key 3 pressed!", 12, 1); OLED_Show_String(6, 30, "Extraio-test passed!", 12, 1); OLED_Refresh_GRAM(); aos_task_delete(&g_extraio_test_task); test_rec_group[TEST_EXTRAIO].result = 0; audio_test(1); } if (audio_test_flag == 0) { printf("\r\n\r\n******************************************\r\n\r\n"); printf("\r\n\r\n====Result: AUDIO test PASS !!!=== \r\n\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); audio_test_flag = 1; OLED_Clear(); OLED_Show_String(8, 8, "Key 4 pressed!", 12, 1); OLED_Show_String(6, 30, "Audio-test passed", 12, 1); OLED_Show_String(2, 52, "Pls K1+K2 to autotest", 12, 1); OLED_Refresh_GRAM(); audio_test_stop(1); beep(); test_rec_group[TEST_AUDIO].result = 0; } aos_msleep(100); } printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* KEY Test ****************************\r\n"); printf("***************************************************************\r\n"); printf("***************************************************************\r\n"); printf("===== KEY test : Start=====\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); printf("\r\n\r\n====Result: KEY test PASS !!!=== \r\n\r\n"); printf("\r\n\r\n******************************************\r\n\r\n"); test_rec_group[TEST_KEY].result = 0; #endif printf("\r\n\r\n\r\n\r\n"); printf("!!!!!!!!!!!!!!!!!!!!AUTO TEST BEGIN!!!!!!!!!!!!!!!!!!!!!!!!!\r\n"); edu_oled_show(" Auto Testing!", 10); test_rec_group[TEST_ADC].result = adc_test(0); test_rec_group[TEST_NOISE].result = adc_test(1); test_rec_group[TEST_GADC2].result = adc_test(2); // test_rec_group[TEST_UART_TTL].result = uart_ttl_test(); // test_rec_group[TEST_SPI].result = spi_test(); test_rec_group[TEST_SD].result = sdcard_test(); test_rec_group[TEST_PWM].result = pwm_test(); if (extra_test_enable) test_rec_group[TEST_USB].result = usb_test(); test_rec_group[TEST_HUMI].result = sensors_test(0); test_rec_group[TEST_GYRO].result = sensors_test(1); test_rec_group[TEST_MAG].result = sensors_test(2); test_rec_group[TEST_BARO].result = sensors_test(3); test_rec_group[TEST_ALS].result = sensors_test(4); test_rec_group[TEST_BT].result = ble_test(); printf("\r\n\r\n"); #ifdef USE_QUICK_WIFI_TEST printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* WIFI Test *******************\r\n"); printf("*How to test: find any Wi-Fi devices as successed. *****\r\n"); printf("***************************************************************\r\n"); printf("=====WIFI Connect test : Start=====\r\n"); netmgr_wifi_ap_list_t ap_info[32]; int ap_num = 0; memset(ap_info, 0, sizeof(ap_info)); ap_num = netmgr_wifi_scan_result(ap_info, 32, NETMGR_WIFI_SCAN_TYPE_FULL); if (ap_num != 0) #else printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* WIFI Connect Test *******************\r\n"); printf("*How to test: connect wifi ssid:haas200 paasword:12345678 *****\r\n"); printf("***************************************************************\r\n"); printf("=====WIFI Connect test : Start=====\r\n"); mfg_wifi_connect("haas200", "12345678"); if (_ip_got_finished == 1) #endif { test_rec_group[TEST_WIFI_CONN].result = 0; printf("\r\n\r\n====Result: wifi connect test PASS !!!=== \r\n\r\n"); } else { test_rec_group[TEST_WIFI_CONN].result = -1; printf("\r\n\r\n====Result: wifi connect test Failed !!!=== \r\n\r\n"); } printf("\r\n\r\n******************************************\r\n\r\n"); printf("--------------------------------------------------------------\r\n"); for (int i = 1; i < TEST_MAX; i++) { if (test_rec_group[i].result != UNKNOWN_RESULT) { aos_kv_set(test_rec_group[i].name, (test_rec_group[i].result == 0) ? "PASS" : "FAIL", 4, 1); } } aos_kv_set(test_rec_group[TEST_WATCHDOG].name, "WAIT", 4, 1); watchdog_test(); aos_reboot(); } static void handle_haas_cmd(char *pwbuf, int blen, int argc, char **argv) { if ((0 == strcmp(argv[1], "key")) && (0 == strcmp(argv[2], "short"))) { printf("key show pressed\n"); led_test_flag = 0; } else if ((0 == strcmp(argv[1], "key")) && (0 == strcmp(argv[2], "long"))) { printf("key long pressed\n"); auto_test_flag = 1; } else if ((0 == strcmp(argv[1], "kv")) && (0 == strcmp(argv[2], "erase"))) { hal_flash_erase(HAL_PARTITION_PARAMETER_2, 0, 0xd000); } } static struct cli_command haas_cmd = { .name = "haas", .help = "haas [set]", .function = handle_haas_cmd }; extern uint32_t g_wifi_factory_test; int board_test() { int count = 0; int ret = 0; expansion_board_do_init(); // Wi-Fi initialization ret = event_service_init(NULL); if (ret != 0) { printf("event_service_init failed! %d\n", ret); } ret = netmgr_service_init(NULL); if (ret != 0) { printf("netmgr_service_init failed! %d\n", ret); } event_subscribe(EVENT_NETMGR_DHCP_SUCCESS, wifi_event_cb, NULL); // BLE initialization aos_task_new("test_process", test_process_entry, NULL, 8192); while (1) { aos_msleep(1000); } }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/board_test.c
C
apache-2.0
16,635
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #include "aos/cli.h" #include "led.h" #include "key.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" extern uint32_t led_test_flag; extern uint32_t oled_test_flag; extern uint32_t extraio_test_flag; extern uint32_t audio_test_flag; extern uint32_t keytest_successed; extern uint32_t auto_test_flag; static void key_event_handle(key_code_t key_code) { switch (key_code) { case EDK_KEY_1: printf("key 1 press\n"); led_test_flag = 0; keytest_successed |= 1 << 0; break; case EDK_KEY_2: printf("key 2 press\n"); oled_test_flag = 0; keytest_successed |= 1 << 1; break; case EDK_KEY_3: printf("key 3 press\n"); extraio_test_flag = 0; keytest_successed |= 1 << 2; break; case EDK_KEY_4: printf("key 4 press\n"); audio_test_flag = 0; keytest_successed |= 1 << 3; break; case EDK_KEY_1 | EDK_KEY_2: printf("Enter auto_test mode\n"); auto_test_flag = 1; break; } } void key_test(void) { key_init(key_event_handle); }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/key_test.c
C
apache-2.0
1,409
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #include "aos/cli.h" #include "led.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" extern uint32_t led_test_flag; aos_task_t g_led_test_task; void led_blink(void) { unsigned int led_id = 0; while (led_test_flag) { if (led_id % 2 == 0) { led_switch(1, LED_ON); led_switch(2, LED_ON); led_switch(3, LED_ON); } else { led_switch(1, LED_OFF); led_switch(2, LED_OFF); led_switch(3, LED_OFF); } aos_msleep(500); led_id++; } } void led_test_process(void) { printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* LED Test ****************************\r\n"); printf("***************************************************************\r\n"); printf("*How to test: If the light flashes normally, press the function key *\r\n"); printf("***************************************************************\r\n"); printf("===== LED test : Start=====\r\n"); aos_task_create(&g_led_test_task, "led_blink", led_blink, NULL, NULL, 4096, 30, 0x01u); } void led_test_task_delete(void) { aos_task_delete(&g_led_test_task); } static void handle_led_cmd(char *pwbuf, int blen, int argc, char **argv) { int id; char *onoff; if (argc < 2) { printf("Usage: led id on/off\n"); printf("Example: led 3 on\n"); return; } id = atoi(argv[1]); onoff = argv[2]; if (0 == strcmp(onoff, "on")) { led_switch(id, LED_ON); } else if (0 == strcmp(onoff, "off")) { led_switch(id, LED_OFF); } } static struct cli_command led_cmd = { .name = "led", .help = "led [3, on/off]", .function = handle_led_cmd }; void led_test(void) { aos_cli_register_command(&led_cmd); led_test_flag = 1; led_test_process(); }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/led_test.c
C
apache-2.0
2,132
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <aos/errno.h> #include <aos/kernel.h> #include "aos/init.h" #include "board.h" #include <k_api.h> #include "aos/cli.h" #include "led.h" #include "hal_gpio.h" #include "hal_iomux_haas1000.h" #include "hal_oled.h" extern uint32_t oled_test_flag; void oled_test_process() { printf("\r\n\r\n"); printf("***************************************************************\r\n"); printf("************************* OLED Test ****************************\r\n"); printf("***************************************************************\r\n"); printf("***************************************************************\r\n"); printf("===== OLED test : Start=====\r\n"); OLED_Clear(); OLED_Show_String(12, 12, "Enter factory_test", 16, 1); OLED_Refresh_GRAM(); aos_msleep(1000); oled_blink(); } void oled_blink(void) { unsigned int oled_id = 0; while (oled_test_flag) { if (oled_id % 2 == 0) { OLED_test(1); } else { OLED_test(0); } aos_msleep(500); oled_id++; } } void edu_oled_show(char *buf, int len) { OLED_Clear(); OLED_Show_String(12, 12, buf, 12, 1); OLED_Refresh_GRAM(); } static void handle_oled_cmd(char *pwbuf, int blen, int argc, char **argv) { oled_test_process(); } static struct cli_command oled_cmd = { .name = "oledtest", .help = "oledtest", .function = handle_oled_cmd }; void oled_test(void) { aos_cli_register_command(&oled_cmd); oled_test_process(); }
YifuLiu/AliOS-Things
hardware/board/haaseduk1/board_test/oled_test.c
C
apache-2.0
1,637