Index: azure_iot_hub_riscv/trunk/app_iothub_client/.vscode/tasks.json
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/.vscode/tasks.json	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/.vscode/tasks.json	(revision 458)
@@ -149,5 +149,5 @@
             "label": "write app_iothub_client",
             "command": "/C/Python38/python.exe",
-                "args": [
+            "args": [
                 "../tools/kflash/kflash.py",
                 "-p",
Index: azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/atomic.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/atomic.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/atomic.h	(revision 458)
@@ -22,21 +22,21 @@
 
 #define SPINLOCK_INIT \
-    {                 \
-        0             \
-    }
+	{                 \
+		0             \
+	}
 
 #define CORELOCK_INIT          \
-    {                          \
-        .lock = SPINLOCK_INIT, \
-        .count = 0,            \
-        .core = -1             \
-    }
+	{                          \
+		.lock = SPINLOCK_INIT, \
+		.count = 0,            \
+		.core = -1             \
+	}
 
 /* Defination of memory barrier macro */
 #define mb()                          \
-    {                                 \
-        asm volatile("fence" ::       \
-                         : "memory"); \
-    }
+	{                                 \
+		asm volatile("fence" ::       \
+						 : "memory"); \
+	}
 
 #define atomic_set(ptr, val) (*(volatile typeof(*(ptr)) *)(ptr) = val)
@@ -53,179 +53,179 @@
 typedef struct _spinlock
 {
-    int lock;
+	int lock;
 } spinlock_t;
 
 typedef struct _semaphore
 {
-    spinlock_t lock;
-    int count;
-    int waiting;
+	spinlock_t lock;
+	int count;
+	int waiting;
 } semaphore_t;
 
 typedef struct _corelock
 {
-    spinlock_t lock;
-    int count;
-    int core;
+	spinlock_t lock;
+	int count;
+	int core;
 } corelock_t;
 
 static inline int spinlock_trylock(spinlock_t *lock)
 {
-    int res = atomic_swap(&lock->lock, -1);
-    /* Use memory barrier to keep coherency */
-    mb();
-    return res;
+	int res = atomic_swap(&lock->lock, -1);
+	/* Use memory barrier to keep coherency */
+	mb();
+	return res;
 }
 
 static inline void spinlock_lock(spinlock_t *lock)
 {
-    while(spinlock_trylock(lock))
-        ;
+	while(spinlock_trylock(lock))
+		;
 }
 
 static inline void spinlock_unlock(spinlock_t *lock)
 {
-    /* Use memory barrier to keep coherency */
-    mb();
-    atomic_set(&lock->lock, 0);
-    asm volatile("nop");
+	/* Use memory barrier to keep coherency */
+	mb();
+	atomic_set(&lock->lock, 0);
+	asm volatile("nop");
 }
 
 static inline void semaphore_signal(semaphore_t *semaphore, int i)
 {
-    spinlock_lock(&(semaphore->lock));
-    semaphore->count += i;
-    spinlock_unlock(&(semaphore->lock));
+	spinlock_lock(&(semaphore->lock));
+	semaphore->count += i;
+	spinlock_unlock(&(semaphore->lock));
 }
 
 static inline void semaphore_wait(semaphore_t *semaphore, int i)
 {
-    atomic_add(&(semaphore->waiting), 1);
-    while(1)
-    {
-        spinlock_lock(&(semaphore->lock));
-        if(semaphore->count >= i)
-        {
-            semaphore->count -= i;
-            atomic_add(&(semaphore->waiting), -1);
-            spinlock_unlock(&(semaphore->lock));
-            break;
-        }
-        spinlock_unlock(&(semaphore->lock));
-    }
+	atomic_add(&(semaphore->waiting), 1);
+	while(1)
+	{
+		spinlock_lock(&(semaphore->lock));
+		if(semaphore->count >= i)
+		{
+			semaphore->count -= i;
+			atomic_add(&(semaphore->waiting), -1);
+			spinlock_unlock(&(semaphore->lock));
+			break;
+		}
+		spinlock_unlock(&(semaphore->lock));
+	}
 }
 
 static inline int semaphore_count(semaphore_t *semaphore)
 {
-    int res = 0;
-
-    spinlock_lock(&(semaphore->lock));
-    res = semaphore->count;
-    spinlock_unlock(&(semaphore->lock));
-    return res;
+	int res = 0;
+
+	spinlock_lock(&(semaphore->lock));
+	res = semaphore->count;
+	spinlock_unlock(&(semaphore->lock));
+	return res;
 }
 
 static inline int semaphore_waiting(semaphore_t *semaphore)
 {
-    return atomic_read(&(semaphore->waiting));
+	return atomic_read(&(semaphore->waiting));
 }
 
 static inline int corelock_trylock(corelock_t *lock)
 {
-    int res = 0;
-    unsigned long core;
-
-    asm volatile("csrr %0, mhartid;"
-                 : "=r"(core));
-    if(spinlock_trylock(&lock->lock))
-    {
-        return -1;
-    }
-
-    if(lock->count == 0)
-    {
-        /* First time get lock */
-        lock->count++;
-        lock->core = core;
-        res = 0;
-    } else if(lock->core == core)
-    {
-        /* Same core get lock */
-        lock->count++;
-        res = 0;
-    } else
-    {
-        /* Different core get lock */
-        res = -1;
-    }
-    spinlock_unlock(&lock->lock);
-
-    return res;
+	int res = 0;
+	unsigned long core;
+
+	asm volatile("csrr %0, mhartid;"
+				 : "=r"(core));
+	if(spinlock_trylock(&lock->lock))
+	{
+		return -1;
+	}
+
+	if(lock->count == 0)
+	{
+		/* First time get lock */
+		lock->count++;
+		lock->core = core;
+		res = 0;
+	} else if(lock->core == core)
+	{
+		/* Same core get lock */
+		lock->count++;
+		res = 0;
+	} else
+	{
+		/* Different core get lock */
+		res = -1;
+	}
+	spinlock_unlock(&lock->lock);
+
+	return res;
 }
 
 static inline void corelock_lock(corelock_t *lock)
 {
-    unsigned long core;
-
-    asm volatile("csrr %0, mhartid;"
-                 : "=r"(core));
-    spinlock_lock(&lock->lock);
-
-    if(lock->count == 0)
-    {
-        /* First time get lock */
-        lock->count++;
-        lock->core = core;
-    } else if(lock->core == core)
-    {
-        /* Same core get lock */
-        lock->count++;
-    } else
-    {
-        /* Different core get lock */
-        spinlock_unlock(&lock->lock);
-
-        do
-        {
-            while(atomic_read(&lock->count))
-                ;
-        } while(corelock_trylock(lock));
-        return;
-    }
-    spinlock_unlock(&lock->lock);
+	unsigned long core;
+
+	asm volatile("csrr %0, mhartid;"
+				 : "=r"(core));
+	spinlock_lock(&lock->lock);
+
+	if(lock->count == 0)
+	{
+		/* First time get lock */
+		lock->count++;
+		lock->core = core;
+	} else if(lock->core == core)
+	{
+		/* Same core get lock */
+		lock->count++;
+	} else
+	{
+		/* Different core get lock */
+		spinlock_unlock(&lock->lock);
+
+		do
+		{
+			while(atomic_read(&lock->count))
+				;
+		} while(corelock_trylock(lock));
+		return;
+	}
+	spinlock_unlock(&lock->lock);
 }
 
 static inline void corelock_unlock(corelock_t *lock)
 {
-    unsigned long core;
-
-    asm volatile("csrr %0, mhartid;"
-                 : "=r"(core));
-    spinlock_lock(&lock->lock);
-
-    if(lock->core == core)
-    {
-        /* Same core release lock */
-        lock->count--;
-        if(lock->count <= 0)
-        {
-            lock->core = -1;
-            lock->count = 0;
-        }
-    } else
-    {
-        /* Different core release lock */
-        spinlock_unlock(&lock->lock);
-
-        register unsigned long a7 asm("a7") = 93;
-        register unsigned long a0 asm("a0") = 0;
-        register unsigned long a1 asm("a1") = 0;
-        register unsigned long a2 asm("a2") = 0;
-
-        asm volatile("scall"
-                     : "+r"(a0)
-                     : "r"(a1), "r"(a2), "r"(a7));
-    }
-    spinlock_unlock(&lock->lock);
+	unsigned long core;
+
+	asm volatile("csrr %0, mhartid;"
+				 : "=r"(core));
+	spinlock_lock(&lock->lock);
+
+	if(lock->core == core)
+	{
+		/* Same core release lock */
+		lock->count--;
+		if(lock->count <= 0)
+		{
+			lock->core = -1;
+			lock->count = 0;
+		}
+	} else
+	{
+		/* Different core release lock */
+		spinlock_unlock(&lock->lock);
+
+		register unsigned long a7 asm("a7") = 93;
+		register unsigned long a0 asm("a0") = 0;
+		register unsigned long a1 asm("a1") = 0;
+		register unsigned long a2 asm("a2") = 0;
+
+		asm volatile("scall"
+					 : "+r"(a0)
+					 : "r"(a1), "r"(a2), "r"(a7));
+	}
+	spinlock_unlock(&lock->lock);
 }
 
Index: azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/incbin.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/incbin.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/incbin.h	(revision 458)
@@ -11,5 +11,5 @@
 #include <limits.h>
 
-# define INCBIN_ALIGNMENT_INDEX 7
+# define INCBIN_ALIGNMENT_INDEX 8
 
 /* Lookup table of (1 << n) where `n' is `INCBIN_ALIGNMENT_INDEX' */
@@ -22,26 +22,27 @@
 #define INCBIN_ALIGN_SHIFT_6 64
 #define INCBIN_ALIGN_SHIFT_7 128
+#define INCBIN_ALIGN_SHIFT_8 256
 
 /* Actual alignment value */
 #define INCBIN_ALIGNMENT \
-    INCBIN_CONCATENATE( \
-        INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
-        INCBIN_ALIGNMENT_INDEX)
+	INCBIN_CONCATENATE( \
+		INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
+		INCBIN_ALIGNMENT_INDEX)
 
 /* Stringize */
 #define INCBIN_STR(X) \
-    #X
+	#X
 #define INCBIN_STRINGIZE(X) \
-    INCBIN_STR(X)
+	INCBIN_STR(X)
 /* Concatenate */
 #define INCBIN_CAT(X, Y) \
-    X ## Y
+	X ## Y
 #define INCBIN_CONCATENATE(X, Y) \
-    INCBIN_CAT(X, Y)
+	INCBIN_CAT(X, Y)
 /* Deferred macro expansion */
 #define INCBIN_EVAL(X) \
-    X
+	X
 #define INCBIN_INVOKE(N, ...) \
-    INCBIN_EVAL(N(__VA_ARGS__))
+	INCBIN_EVAL(N(__VA_ARGS__))
 
 /* Green Hills uses a different directive for including binary data */
@@ -54,5 +55,5 @@
 #ifndef _MSC_VER
 #  define INCBIN_ALIGN \
-    __attribute__((aligned(INCBIN_ALIGNMENT)))
+	__attribute__((aligned(INCBIN_ALIGNMENT)))
 #else
 #  define INCBIN_ALIGN __declspec(align(INCBIN_ALIGNMENT))
@@ -60,6 +61,6 @@
 
 #if defined(__arm__) || /* GNU C and RealView */ \
-    defined(__arm) || /* Diab */ \
-    defined(_ARM) /* ImageCraft */
+	defined(__arm) || /* Diab */ \
+	defined(_ARM) /* ImageCraft */
 #  define INCBIN_ARM
 #endif
@@ -93,5 +94,5 @@
 #if defined(__APPLE__)
 /* The directives are different for Apple branded compilers */
-#  define INCBIN_SECTION         ".data\n"
+#  define INCBIN_SECTION         ".rodata\n"
 #  define INCBIN_GLOBAL(NAME)    ".globl " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
 #  define INCBIN_INT             ".long "
@@ -100,5 +101,5 @@
 #  define INCBIN_TYPE(...)
 #else
-#  define INCBIN_SECTION         ".section .data\n"
+#  define INCBIN_SECTION         ".section .rodata\n"
 #  define INCBIN_GLOBAL(NAME)    ".global " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
 #  define INCBIN_INT             ".int "
@@ -199,32 +200,32 @@
 /* Style lookup: returning identifier */
 #define INCBIN_STYLE_IDENT(TYPE) \
-    INCBIN_CONCATENATE( \
-        INCBIN_STYLE_, \
-        INCBIN_CONCATENATE( \
-            INCBIN_EVAL(INCBIN_STYLE), \
-            INCBIN_CONCATENATE(_, TYPE)))
+	INCBIN_CONCATENATE( \
+		INCBIN_STYLE_, \
+		INCBIN_CONCATENATE( \
+			INCBIN_EVAL(INCBIN_STYLE), \
+			INCBIN_CONCATENATE(_, TYPE)))
 
 /* Style lookup: returning string literal */
 #define INCBIN_STYLE_STRING(TYPE) \
-    INCBIN_STRINGIZE( \
-        INCBIN_STYLE_IDENT(TYPE)) \
+	INCBIN_STRINGIZE( \
+		INCBIN_STYLE_IDENT(TYPE)) \
 
 /* Generate the global labels by indirectly invoking the macro with our style
  * type and concatenating the name against them. */
 #define INCBIN_GLOBAL_LABELS(NAME, TYPE) \
-    INCBIN_INVOKE( \
-        INCBIN_GLOBAL, \
-        INCBIN_CONCATENATE( \
-            NAME, \
-            INCBIN_INVOKE( \
-                INCBIN_STYLE_IDENT, \
-                TYPE))) \
-    INCBIN_INVOKE( \
-        INCBIN_TYPE, \
-        INCBIN_CONCATENATE( \
-            NAME, \
-            INCBIN_INVOKE( \
-                INCBIN_STYLE_IDENT, \
-                TYPE)))
+	INCBIN_INVOKE( \
+		INCBIN_GLOBAL, \
+		INCBIN_CONCATENATE( \
+			NAME, \
+			INCBIN_INVOKE( \
+				INCBIN_STYLE_IDENT, \
+				TYPE))) \
+	INCBIN_INVOKE( \
+		INCBIN_TYPE, \
+		INCBIN_CONCATENATE( \
+			NAME, \
+			INCBIN_INVOKE( \
+				INCBIN_STYLE_IDENT, \
+				TYPE)))
 
 /**
@@ -249,16 +250,16 @@
  */
 #define INCBIN_EXTERN(NAME) \
-    INCBIN_EXTERNAL INCBIN_ALIGN unsigned char \
-        INCBIN_CONCATENATE( \
-            INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
-            INCBIN_STYLE_IDENT(DATA))[]; \
-    INCBIN_EXTERNAL INCBIN_ALIGN unsigned char * \
-    INCBIN_CONCATENATE( \
-        INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
-        INCBIN_STYLE_IDENT(END)); \
-    INCBIN_EXTERNAL unsigned int \
-        INCBIN_CONCATENATE( \
-            INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
-            INCBIN_STYLE_IDENT(SIZE))
+	INCBIN_EXTERNAL INCBIN_ALIGN unsigned char \
+		INCBIN_CONCATENATE( \
+			INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
+			INCBIN_STYLE_IDENT(DATA))[]; \
+	INCBIN_EXTERNAL INCBIN_ALIGN unsigned char * \
+	INCBIN_CONCATENATE( \
+		INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
+		INCBIN_STYLE_IDENT(END)); \
+	INCBIN_EXTERNAL unsigned int \
+		INCBIN_CONCATENATE( \
+			INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
+			INCBIN_STYLE_IDENT(SIZE))
 
 /**
@@ -291,24 +292,24 @@
 #ifdef _MSC_VER
 #define INCBIN(NAME, FILENAME) \
-    INCBIN_EXTERN(NAME)
+	INCBIN_EXTERN(NAME)
 #else
 #define INCBIN(NAME, FILENAME) \
-    __asm__(INCBIN_SECTION \
-            INCBIN_GLOBAL_LABELS(NAME, DATA) \
-            INCBIN_ALIGN_HOST \
-            INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
-            INCBIN_MACRO " \"" FILENAME "\"\n" \
-            INCBIN_GLOBAL_LABELS(NAME, END) \
-            INCBIN_ALIGN_BYTE \
-            INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
-                INCBIN_BYTE "1\n" \
-            INCBIN_GLOBAL_LABELS(NAME, SIZE) \
-            INCBIN_ALIGN_HOST \
-            INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
-                INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
-                           INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
-    ); \
-    INCBIN_EXTERN(NAME)
-
-#endif
-#endif
+	__asm__(INCBIN_SECTION \
+			INCBIN_GLOBAL_LABELS(NAME, DATA) \
+			INCBIN_ALIGN_HOST \
+			INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
+			INCBIN_MACRO " \"" FILENAME "\"\n" \
+			INCBIN_GLOBAL_LABELS(NAME, END) \
+			INCBIN_ALIGN_BYTE \
+			INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
+				INCBIN_BYTE "1\n" \
+			INCBIN_GLOBAL_LABELS(NAME, SIZE) \
+			INCBIN_ALIGN_HOST \
+			INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
+				INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
+						   INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
+	); \
+	INCBIN_EXTERN(NAME)
+
+#endif
+#endif
Index: azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.c	(revision 458)
@@ -17,56 +17,45 @@
 #include "utils.h"
 #include "kpu_main.h"
+#include "kernel_cfg.h"
 
 #define sil_orw_mem(a, b) sil_wrw_mem((a), sil_rew_mem(a) | (b))
 
-void sysctl_enable_irq(void)
-{
-    set_csr(mie, MIP_MEIP);
-    set_csr(mstatus, MSTATUS_MIE);
-}
-
-void sysctl_disable_irq(void)
-{
-    clear_csr(mie, MIP_MEIP);
-    clear_csr(mstatus, MSTATUS_MIE);
-}
-
 uint64_t sysctl_get_time_us(void)
 {
-    uint64_t v_cycle = read_cycle();
-    return v_cycle * 1000000 / SYSCTRL_CLOCK_FREQ_IN0;
+	uint64_t v_cycle = read_cycle();
+	return v_cycle * 1000000 / SYSCTRL_CLOCK_FREQ_IN0;
 }
 
 static int is_memory(uintptr_t address)
 {
-    enum
-    {
-        mem_len = 6 * 1024 * 1024,
-        mem_no_cache_len = 8 * 1024 * 1024,
-    };
-    return ((address >= 0x80000000) && (address < 0x80000000 + mem_len)) || ((address >= 0x40000000) && (address < 0x40000000 + mem_no_cache_len)) || (address == 0x50450040);
+	enum
+	{
+		mem_len = 6 * 1024 * 1024,
+		mem_no_cache_len = 8 * 1024 * 1024,
+	};
+	return ((address >= 0x80000000) && (address < 0x80000000 + mem_len)) || ((address >= 0x40000000) && (address < 0x40000000 + mem_no_cache_len)) || (address == 0x50450040);
 }
 
 uint32_t is_memory_cache(uintptr_t address)
 {
-    #define MEM_CACHE_LEN (6 * 1024 * 1024)
-
-    return ((address >= 0x80000000) && (address < 0x80000000 + MEM_CACHE_LEN));
+#define MEM_CACHE_LEN (6 * 1024 * 1024)
+
+	return ((address >= 0x80000000) && (address < 0x80000000 + MEM_CACHE_LEN));
 }
 
 int plic_irq_enable(INTNO irq_number)
 {
-    if (irq_number != INTNO_AI)
-        return -1;
-    ena_int(irq_number);
-    return 0;
+	if (irq_number != INTNO_AI)
+		return -1;
+	ena_int(irq_number);
+	return 0;
 }
 
 int plic_set_priority(INTNO irq_number, uint32_t priority)
 {
-    if (irq_number != INTNO_AI)
-        return -1;
-    set_ipriority(irq_number, priority);
-    return 0;
+	if (irq_number != INTNO_AI)
+		return -1;
+	set_ipriority(irq_number, priority);
+	return 0;
 }
 
@@ -76,24 +65,23 @@
 void plic_irq_register(INTNO irq, plic_irq_callback_t callback, void *ctx)
 {
-    ER ret;
-    if (irq != INTNO_AI)
-        return;
-
-    ret = loc_cpu();
-
-    ai_done_callback = callback;
-    ai_done_ctx = ctx;
-
-    if (ret == E_OK)
-        unl_cpu();
+	if (irq != INTNO_AI)
+		return;
+
+	dis_int(INTNO_AI);
+
+	ai_done_callback = callback;
+	ai_done_ctx = ctx;
+
+	ena_int(INTNO_AI);
 }
 
 void ai_done_isr(intptr_t exinf)
 {
-    sysctl_disable_irq();
-    if (ai_done_callback != NULL){
-        ai_done_callback(ai_done_ctx);
-    }
-    sysctl_enable_irq();
+	dis_int(INTNO_AI);
+	if (ai_done_callback != NULL)
+	{
+		ai_done_callback(ai_done_ctx);
+	}
+	ena_int(INTNO_AI);
 }
 
@@ -102,46 +90,45 @@
 
 void kpu_dmac_irq_register(dmac_channel_number_t channel_num,
-    plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority)
-{
-    ER ret;
-    if (channel_num != AI_DMA_CH)
-        return;
-
-    set_ipriority(INTNO_DMAAI, priority);
-
-    ret = loc_cpu();
-
-    ai_dma_done_callback = dmac_callback;
-    ai_dma_done_ctx = ctx;
-
-    if (ret == E_OK)
-        unl_cpu();
+						   plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority)
+{
+	if (channel_num != AI_DMA_CH)
+		return;
+
+	//set_ipriority(INTNO_DMAAI, priority);
+
+	dis_int(INTNO_DMAAI);
+
+	ai_dma_done_callback = dmac_callback;
+	ai_dma_done_ctx = ctx;
+
+	ena_int(INTNO_DMAAI);
 }
 
 void ai_dma_done_isr(DMA_Handle_t *dma)
 {
-    sysctl_disable_irq();
-    if (ai_dma_done_callback != NULL) {
-        ai_dma_done_callback(ai_dma_done_ctx);
-    }
-    sysctl_enable_irq();
+	dis_int(INTNO_DMAAI);
+
+	if (ai_dma_done_callback != NULL)
+	{
+		ai_dma_done_callback(ai_dma_done_ctx);
+	}
+
+	ena_int(INTNO_DMAAI);
 }
 
 void dmac_set_irq(dmac_channel_number_t channel_num,
-    plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority)
-{
-    ER ret;
-    if (channel_num != AI_DMA_CH)
-        return;
-
-    set_ipriority(INTNO_DMAAI, priority);
-
-    ret = loc_cpu();
-
-    ai_dma_done_callback = dmac_callback;
-    ai_dma_done_ctx = ctx;
-
-    if (ret == E_OK)
-        unl_cpu();
+				  plic_irq_callback_t dmac_callback, void *ctx, uint32_t priority)
+{
+	if (channel_num != AI_DMA_CH)
+		return;
+
+	//set_ipriority(INTNO_DMAAI, priority);
+
+	dis_int(INTNO_DMAAI);
+
+	ai_dma_done_callback = dmac_callback;
+	ai_dma_done_ctx = ctx;
+
+	ena_int(INTNO_DMAAI);
 }
 
@@ -149,37 +136,37 @@
 
 void dmac_set_single_mode(dmac_channel_number_t channel_num,
-    const void *src, void *dest, uint8_t src_inc,
-    uint8_t dest_inc,
-    uint8_t dmac_burst_size,
-    uint8_t dmac_trans_width,
-    size_t block_size)
-{
-    if (channel_num != AI_DMA_CH)
-        return;
-
-    DMA_Handle_t *hdma = &g_ai_hdma;
-    int mem_type_src = is_memory((uintptr_t)src), mem_type_dest = is_memory((uintptr_t)dest);
-    uint8_t flow_control;
-    if(mem_type_src == 0 && mem_type_dest == 0)
-        flow_control = DMA_PERIPH_TO_PERIPH;
-    else if(mem_type_src == 1 && mem_type_dest == 0)
-        flow_control = DMA_MEMORY_TO_PERIPH;
-    else if(mem_type_src == 0 && mem_type_dest == 1)
-        flow_control = DMA_PERIPH_TO_MEMORY;
-    else
-        flow_control = DMA_MEMORY_TO_MEMORY;
-
-    hdma->Init.Direction    = flow_control;	/* DMA転送方向 */
-    hdma->Init.SrcHandShake = (mem_type_src ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	/* ソースハンドシェイク */
-    hdma->Init.DrcHandShake = (mem_type_dest ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	/* デスティネーションハンドシェイク */
-    hdma->Init.SrcInc       = src_inc;	/* ソースインクリメント設定 */
-    hdma->Init.DstInc       = dest_inc;	/* デスティネーションインクリメント設定 */
-    hdma->Init.SrcTransWidth = dmac_trans_width;	/* ソース転送幅 */
-    hdma->Init.DstTransWidth = dmac_trans_width;	/* デスティネーション転送幅 */
-    hdma->Init.SrcBurstSize = dmac_burst_size;	/* ソースバーストサイズ */
-    hdma->Init.DstBurstSize = dmac_burst_size;	/* デスティネーションバーストサイズ */
-    dma_reset(hdma);
-
-    dma_start(hdma, (uintptr_t)src, (uintptr_t)dest, block_size);
+						  const void *src, void *dest, uint8_t src_inc,
+						  uint8_t dest_inc,
+						  uint8_t dmac_burst_size,
+						  uint8_t dmac_trans_width,
+						  size_t block_size)
+{
+	if (channel_num != AI_DMA_CH)
+		return;
+
+	DMA_Handle_t *hdma = &g_ai_hdma;
+	int mem_type_src = is_memory((uintptr_t)src), mem_type_dest = is_memory((uintptr_t)dest);
+	uint8_t flow_control;
+	if (mem_type_src == 0 && mem_type_dest == 0)
+		flow_control = DMA_PERIPH_TO_PERIPH;
+	else if (mem_type_src == 1 && mem_type_dest == 0)
+		flow_control = DMA_MEMORY_TO_PERIPH;
+	else if (mem_type_src == 0 && mem_type_dest == 1)
+		flow_control = DMA_PERIPH_TO_MEMORY;
+	else
+		flow_control = DMA_MEMORY_TO_MEMORY;
+
+	hdma->Init.Direction = flow_control;											 /* DMA転送方向 */
+	hdma->Init.SrcHandShake = (mem_type_src ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	 /* ソースハンドシェイク */
+	hdma->Init.DrcHandShake = (mem_type_dest ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE); /* デスティネーションハンドシェイク */
+	hdma->Init.SrcInc = src_inc;													 /* ソースインクリメント設定 */
+	hdma->Init.DstInc = dest_inc;													 /* デスティネーションインクリメント設定 */
+	hdma->Init.SrcTransWidth = dmac_trans_width;									 /* ソース転送幅 */
+	hdma->Init.DstTransWidth = dmac_trans_width;									 /* デスティネーション転送幅 */
+	hdma->Init.SrcBurstSize = dmac_burst_size;										 /* ソースバーストサイズ */
+	hdma->Init.DstBurstSize = dmac_burst_size;										 /* デスティネーションバーストサイズ */
+	dma_reset(hdma);
+
+	dma_start(hdma, (uintptr_t)src, (uintptr_t)dest, block_size);
 }
 
@@ -199,1319 +186,872 @@
 static volatile uint32_t kpu_status;
 
-typedef struct kpu_context
-{
-    kpu_task_t kpu_task;
-    uint32_t kpu_status;
-} kpu_context_t;
-
-volatile kpu_context_t g_kpu_context;
-
-static int kpu_run_all_done(void *_task)
-{
-    atomic_swap(&g_kpu_context.kpu_status, 0);
-    kpu_task_t *task = (kpu_task_t *)_task;
-    task->callback(task);
-    return 0;
-}
-
-int kpu_continue(void *_task)
-{
-    kpu_task_t *task = (kpu_task_t *)_task;
-    int layer_burst_size = 1;
-
-    kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-
-    if(task->remain_layers_length == 0)
-    {
-        return 0;
-    }
-    if(task->remain_layers_length <= layer_burst_size)
-    {
-        for(uint32_t i = 0; i < task->remain_layers_length; i++)
-        {
-            kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg;
-        }
-        task->remain_layers_length = 0;
-    } else
-    {
-        for(uint32_t i = 0; i < layer_burst_size; i++)
-        {
-            kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg;
-        }
-        task->remain_layers += layer_burst_size;
-        task->remain_layers_length -= layer_burst_size;
-    }
-    return 0;
-}
-
-static int kpu_run_dma_output(uint32_t dma_ch, void *dst, uint32_t length, plic_irq_callback_t cb, void *_task)
-{
-    select_dma_channel(dma_ch, DMA_SELECT_AI_RX_REQ);
-    kpu_dmac_irq_register(dma_ch, kpu_run_all_done, _task, 1);
-    dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), (void *)(dst), DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (length + 7) / 8);
-    return 0;
-}
-
-static int kpu_run_dma_input_done_push_layers(void *_task)
-{
-    kpu_task_t *task = (kpu_task_t *)_task;
-    kpu->interrupt_clear.reg = 7;
-    dma_end(&g_ai_hdma);
-    kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t){
-        .fifo_full_threshold = 10, .fifo_empty_threshold = 1};
-    kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t){
-        .eight_bit_mode = task->eight_bit_mode};
-
-    kpu_layer_argument_t *last_layer = &task->layers[task->layers_length - 1];
-
-    kpu_run_dma_output(task->dma_ch, task->dst, last_layer->dma_parameter.data.dma_total_byte + 1, kpu_run_all_done, task);
-
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 0,
-        .layer_cfg_almost_empty_int = 0,
-        .layer_cfg_almost_full_int = 1};
-    kpu_continue(task);
-    return 0;
-}
-
-static void kpu_run_dma_input(uint32_t dma_ch, const void *src, plic_irq_callback_t cb, void *_task)
-{
-    kpu_task_t *task = _task;
-    kpu_layer_argument_t *first_layer = &task->layers[0];
-    uint64_t input_size = first_layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (first_layer->image_channel_num.data.i_ch_num + 1);
-    kpu_dmac_irq_register(dma_ch, cb, _task, 1);
-    dmac_set_single_mode(dma_ch, (void *)src, (void *)(AI_IO_BASE_ADDR), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8);
-}
-
-int kpu_run(kpu_task_t *v_task, dmac_channel_number_t dma_ch, const void *src, void *dest, plic_irq_callback_t callback)
-{
-    if(atomic_cas(&g_kpu_context.kpu_status, 0, 1))
-        return -1;
-
-    memcpy((void *)&g_kpu_context.kpu_task, v_task, sizeof(kpu_task_t));
-    kpu_task_t *task = (kpu_task_t *)&g_kpu_context.kpu_task;
-
-    kpu_layer_argument_t *last_layer = &task->layers[task->layers_length - 1];
-
-    uint64_t output_size = last_layer->dma_parameter.data.dma_total_byte + 1;
-
-    last_layer->dma_parameter.data.send_data_out = 1;
-    last_layer->interrupt_enabe.data.int_en = 1;
-
-    task->dma_ch = dma_ch;
-    task->dst = dest;
-    task->dst_length = output_size;
-    task->callback = callback;
-    task->remain_layers_length = task->layers_length;
-    task->remain_layers = task->layers;
-
-    plic_set_priority(INTNO_AI, 1);
-    plic_irq_register(INTNO_AI, kpu_continue, task);
-    plic_irq_enable(INTNO_AI);
-
-    kpu_run_dma_input(dma_ch, src, kpu_run_dma_input_done_push_layers, task);
-
-    return 0;
-}
-
-uint8_t *kpu_get_output_buf(kpu_task_t *task)
-{
-    kpu_layer_argument_t *last_layer = &task->layers[task->layers_length - 1];
-    size_t output_size = ((last_layer->dma_parameter.data.dma_total_byte + 1) + 7) / 8 * 8;
-    return malloc(output_size);
-}
-
-void kpu_release_output_buf(uint8_t *output_buf)
-{
-    if(output_buf != NULL)
-        free(output_buf);
-}
-
-static int kpu_done(void *ctx)
-{
-    atomic_swap(&kpu_status, 0);
-    kpu_task_t *task = (kpu_task_t *)ctx;
-    task->callback(task->ctx);
-    return 0;
-}
-
-static int kpu_config_input(void *ctx)
-{
-    kpu_task_t *task = (kpu_task_t *)ctx;
-    kpu->interrupt_clear.reg = 7;
-    if(task->remain_layers_length <= LAYER_BURST_SIZE)
-    {
-        for(uint32_t i = 0; i < task->remain_layers_length; i++)
-        {
-            kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg;
-        }
-        task->remain_layers_length = 0;
-        kpu->interrupt_mask.reg = 7;
-    } else
-    {
-        for(uint32_t i = 0; i < LAYER_BURST_SIZE; i++)
-        {
-            kpu->layer_argument_fifo = task->remain_layers[i].interrupt_enabe.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_addr.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_channel_num.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].image_size.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_pool_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_load_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_offset.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].kernel_calc_type_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].write_back_cfg.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].conv_value2.reg;
-            kpu->layer_argument_fifo = task->remain_layers[i].dma_parameter.reg;
-        }
-        task->remain_layers += LAYER_BURST_SIZE;
-        task->remain_layers_length -= LAYER_BURST_SIZE;
-    }
-    return 0;
-}
-
-static void kpu_data_output(kpu_task_t *task)
-{
-    select_dma_channel(task->dma_ch, DMA_SELECT_AI_RX_REQ);
-    kpu_dmac_irq_register(task->dma_ch, kpu_done, task, 1);
-    dmac_set_single_mode(task->dma_ch, (void *)(&kpu->fifo_data_out), (void *)(task->dst), DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, task->dst_length);
-}
-
-static int kpu_data_ready(void *ctx)
-{
-    kpu_task_t *task = (kpu_task_t *)ctx;
-
-    dma_end(&g_ai_hdma);
-    kpu_data_output(task);
-
-    kpu->eight_bit_mode.reg = task->eight_bit_mode;
-    kpu->interrupt_mask.reg = 7;
-    kpu->interrupt_clear.reg = 7;
-    kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t){
-        .fifo_full_threshold = 12, .fifo_empty_threshold = 1};
-
-    plic_set_priority(INTNO_AI, 2);
-    plic_irq_register(INTNO_AI, kpu_config_input, task);
-    plic_irq_enable(INTNO_AI);
-    kpu_config_input(task);
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 0,
-        .layer_cfg_almost_full_int = 1};
-    return 0;
-}
-
-static void kpu_data_input(kpu_task_t *task)
-{
-    if(task->src == NULL)
-    {
-        kpu_data_ready(task);
-        return;
-    }
-    kpu_dmac_irq_register(task->dma_ch, kpu_data_ready, task, 1);
-    kpu_layer_argument_t *layer = &task->layers[0];
-    dmac_set_single_mode(task->dma_ch, (void *)(uintptr_t)task->src, (void *)(uintptr_t)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, task->src_length);
-}
-
-int kpu_single_task_init(kpu_task_t *task)
-{
-    /*
-    *  AIクロック有効化
-    */
-    sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_PERI), SYSCTL_CLK_EN_PERI_AI_CLK_EN);
-
-    kpu_layer_argument_t *first_layer = &task->layers[0];
-    kpu_layer_argument_t *last_layer = &task->layers[task->layers_length - 1];
-
-    last_layer->dma_parameter.data.send_data_out = 1;
-    last_layer->interrupt_enabe.data.int_en = 1;
-    task->src_length = first_layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (first_layer->image_channel_num.data.i_ch_num + 1) / 8;
-    task->dst_length = ((last_layer->dma_parameter.data.dma_total_byte + 1) + 7) / 8;
-    task->dst = (uint64_t *)malloc(task->dst_length * 8);
-    if(task->dst == NULL)
-        return 1;
-    memset(task->dst, 0, task->dst_length * 8);
-    return 0;
-}
-
-int kpu_single_task_deinit(kpu_task_t *task)
-{
-    free(task->dst);
-    return 0;
-}
-
-int kpu_model_load_from_buffer(kpu_task_t *task, uint8_t *buffer, kpu_model_layer_metadata_t **meta)
-{
-    uintptr_t base_addr = (uintptr_t)buffer;
-    kpu_model_header_t *header = (kpu_model_header_t *)buffer;
-    kpu_model_layer_metadata_t *layer_meta = (kpu_model_layer_metadata_t *)(base_addr + sizeof(kpu_model_header_t));
-    kpu_layer_argument_t *layers = (kpu_layer_argument_t *)(base_addr + header->layers_argument_start);
-
-    if(header->version != 1)
-        return -1;
-    uint32_t layers_length = header->layers_length;
-    task->layers_length = layers_length;
-    task->eight_bit_mode = header->flags & 1;
-    task->layers = layers;
-    task->output_scale = layer_meta[layers_length - 1].output_scale;
-    task->output_bias = layer_meta[layers_length - 1].output_bias;
-    size_t i;
-    for(i = 0; i < layers_length; i++)
-    {
-        layers[i].kernel_load_cfg.data.para_start_addr = (uint64_t)(base_addr + layer_meta[i].weigths_offset);
-        layers[i].kernel_pool_type_cfg.data.bwsx_base_addr = (uint64_t)(base_addr + layer_meta[i].bn_offset);
-        layers[i].kernel_calc_type_cfg.data.active_addr = (uint64_t)(base_addr + layer_meta[i].act_offset);
-    }
-
-    if(meta)
-        *meta = layer_meta;
-    return 0;
-}
-
-int kpu_start(kpu_task_t *task)
-{
-    if(atomic_cas(&kpu_status, 0, 1))
-        return -1;
-
-    task->remain_layers_length = task->layers_length;
-    task->remain_layers = task->layers;
-    kpu_data_input(task);
-    return 0;
-}
-
 static void kpu_send_layer(const kpu_layer_argument_t *layer)
 {
-    kpu->layer_argument_fifo = layer->interrupt_enabe.reg;
-    kpu->layer_argument_fifo = layer->image_addr.reg;
-    kpu->layer_argument_fifo = layer->image_channel_num.reg;
-    kpu->layer_argument_fifo = layer->image_size.reg;
-    kpu->layer_argument_fifo = layer->kernel_pool_type_cfg.reg;
-    kpu->layer_argument_fifo = layer->kernel_load_cfg.reg;
-    kpu->layer_argument_fifo = layer->kernel_offset.reg;
-    kpu->layer_argument_fifo = layer->kernel_calc_type_cfg.reg;
-    kpu->layer_argument_fifo = layer->write_back_cfg.reg;
-    kpu->layer_argument_fifo = layer->conv_value.reg;
-    kpu->layer_argument_fifo = layer->conv_value2.reg;
-    kpu->layer_argument_fifo = layer->dma_parameter.reg;
-}
-
-void kpu_init(int eight_bit_mode, plic_irq_callback_t callback, void *userdata)
-{
-    kpu->interrupt_clear.reg = 7;
-    kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t){
-        .fifo_full_threshold = 10, .fifo_empty_threshold = 1};
-    kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t){
-        .eight_bit_mode = eight_bit_mode};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 0,
-        .layer_cfg_almost_full_int = 1};
-
-    plic_set_priority(INTNO_AI, 1);
-    plic_irq_register(INTNO_AI, callback, userdata);
-    plic_irq_enable(INTNO_AI);
+	kpu->layer_argument_fifo = layer->interrupt_enabe.reg;
+	kpu->layer_argument_fifo = layer->image_addr.reg;
+	kpu->layer_argument_fifo = layer->image_channel_num.reg;
+	kpu->layer_argument_fifo = layer->image_size.reg;
+	kpu->layer_argument_fifo = layer->kernel_pool_type_cfg.reg;
+	kpu->layer_argument_fifo = layer->kernel_load_cfg.reg;
+	kpu->layer_argument_fifo = layer->kernel_offset.reg;
+	kpu->layer_argument_fifo = layer->kernel_calc_type_cfg.reg;
+	kpu->layer_argument_fifo = layer->write_back_cfg.reg;
+	kpu->layer_argument_fifo = layer->conv_value.reg;
+	kpu->layer_argument_fifo = layer->conv_value2.reg;
+	kpu->layer_argument_fifo = layer->dma_parameter.reg;
 }
 
 void kpu_input_dma(const kpu_layer_argument_t *layer, const uint8_t *src, dmac_channel_number_t dma_ch, plic_irq_callback_t callback, void *userdata)
 {
-    uint64_t input_size = layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (layer->image_channel_num.data.i_ch_num + 1);
-    dmac_set_irq(dma_ch, callback, userdata, 1);
-    dmac_set_single_mode(dma_ch, (void *)src, (void *)(uintptr_t)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8);
+	uint64_t input_size = layer->kernel_calc_type_cfg.data.channel_switch_addr * 64 * (layer->image_channel_num.data.i_ch_num + 1);
+	dmac_set_irq(dma_ch, callback, userdata, 1);
+	dmac_set_single_mode(dma_ch, (void *)src, (void *)(uintptr_t)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64), DMAC_ADDR_INCREMENT, DMAC_ADDR_INCREMENT,
+						 DMAC_MSIZE_16, DMAC_TRANS_WIDTH_64, input_size / 8);
 }
 
 static void kpu_conv2d_core(kpu_layer_argument_t *layer)
 {
-    kpu_send_layer(layer);
+	kpu_send_layer(layer);
 }
 
 void kpu_conv2d(kpu_layer_argument_t *layer)
 {
-    kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 0,
-        .layer_cfg_almost_full_int = 1};
-    kpu_conv2d_core(layer);
-}
-
-void kpu_conv2d_output(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint8_t *dest, plic_irq_callback_t callback, void *userdata)
-{
-    kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    layer->dma_parameter.data.send_data_out = 1;
-    select_dma_channel(dma_ch, DMA_SELECT_AI_RX_REQ);
-    dmac_set_irq(dma_ch, callback, userdata, 1);
-    dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (layer->dma_parameter.data.dma_total_byte + 8) / 8);
-    kpu_conv2d_core(layer);
-}
-
-void kpu_conv2d_output_full_add(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint64_t *dest, plic_irq_callback_t callback, void *userdata)
-{
-    uint32_t channels = layer->image_channel_num.data.o_ch_num + 1;
-    layer->interrupt_enabe.data.full_add = 1;
-
-    kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    layer->dma_parameter.data.send_data_out = 1;
-    select_dma_channel(dma_ch, DMA_SELECT_AI_RX_REQ);
-    dmac_set_irq(dma_ch, callback, userdata, 1);
-    dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                        DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, channels);
-    kpu_conv2d_core(layer);
-}
-
-void kpu_add(const uint8_t *src1, const quantize_param_t *src1_param, const uint8_t *src2, const quantize_param_t *src2_param, size_t count, uint8_t *dest, const quantize_param_t *dest_param)
-{
-    quantize_param_t q1 = *src1_param, q2 = *src2_param, q3 = *dest_param;
-
-    size_t i;
-    for(i = 0; i < count; i++)
-    {
-        int value = ((*src1++ * q1.scale + q1.bias + *src2++ * q2.scale + q2.bias) - q3.bias) / q3.scale;
-        if(value < 0)
-            value = 0;
-        if(value > 0xFF)
-            value = 0xFF;
-        *dest++ = value;
-    }
+	kpu->interrupt_clear.data = (kpu_config_interrupt_t){
+		.calc_done_int = 1,
+		.layer_cfg_almost_empty_int = 1,
+		.layer_cfg_almost_full_int = 1};
+	kpu->interrupt_mask.data = (kpu_config_interrupt_t){
+		.calc_done_int = 1,
+		.layer_cfg_almost_empty_int = 0,
+		.layer_cfg_almost_full_int = 1};
+	kpu_conv2d_core(layer);
 }
 
 void kpu_global_average_pool(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, uint8_t *dest, const quantize_param_t *dest_param)
 {
-    quantize_param_t q1 = *src_param, q2 = *dest_param;
-    size_t oc, y, x;
-
-    if(((uintptr_t)dest) >= AI_IO_BASE_ADDR && ((uintptr_t)dest) < AI_IO_BASE_ADDR + 2 * 1024 * 1024)
-    {
-        uint32_t row_padding = 16;
-        uint32_t row_group = 4;
-        uint32_t row_length = 1;
-        uint32_t height = 4;
-
-        for(oc = 0; oc < channels; oc++)
-        {
-            uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
-            for(y = 0; y < 1; y++)
-            {
-                uint8_t *y_origin = channel_origin + y * row_length * 64;
-                for(x = 0; x < 1; x++)
-                {
-                    int64_t sum = 0;
-                    size_t i;
-                    for(i = 0; i < kernel_size; i++)
-                        sum += *src++;
-
-                    int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale;
-                    if(value < 0)
-                        value = 0;
-                    if(value > 0xFF)
-                        value = 0xFF;
-                    y_origin[x] = value;
-                }
-            }
-        }
-    } else
-    {
-        for(oc = 0; oc < channels; oc++)
-        {
-            int64_t sum = 0;
-            size_t i;
-            for(i = 0; i < kernel_size; i++)
-                sum += *src++;
-
-            int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale;
-            if(value < 0)
-                value = 0;
-            if(value > 0xFF)
-                value = 0xFF;
-            dest[oc] = value;
-        }
-    }
+	quantize_param_t q1 = *src_param, q2 = *dest_param;
+	size_t oc, y, x;
+
+	if (((uintptr_t)dest) >= AI_IO_BASE_ADDR && ((uintptr_t)dest) < AI_IO_BASE_ADDR + 2 * 1024 * 1024)
+	{
+		uint32_t row_padding = 16;
+		uint32_t row_group = 4;
+		uint32_t row_length = 1;
+		uint32_t height = 4;
+
+		for (oc = 0; oc < channels; oc++)
+		{
+			uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
+			for (y = 0; y < 1; y++)
+			{
+				uint8_t *y_origin = channel_origin + y * row_length * 64;
+				for (x = 0; x < 1; x++)
+				{
+					int64_t sum = 0;
+					size_t i;
+					for (i = 0; i < kernel_size; i++)
+						sum += *src++;
+
+					int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale;
+					if (value < 0)
+						value = 0;
+					if (value > 0xFF)
+						value = 0xFF;
+					y_origin[x] = value;
+				}
+			}
+		}
+	}
+	else
+	{
+		for (oc = 0; oc < channels; oc++)
+		{
+			int64_t sum = 0;
+			size_t i;
+			for (i = 0; i < kernel_size; i++)
+				sum += *src++;
+
+			int value = ((sum * q1.scale + q1.bias) / kernel_size - q2.bias) / q2.scale;
+			if (value < 0)
+				value = 0;
+			if (value > 0xFF)
+				value = 0xFF;
+			dest[oc] = value;
+		}
+	}
 }
 
 void kpu_global_average_pool_float(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, float *dest)
 {
-    quantize_param_t q = *src_param;
-    size_t oc;
-
-    for(oc = 0; oc < channels; oc++)
-    {
-        int64_t sum = 0;
-        size_t i;
-        for(i = 0; i < kernel_size; i++)
-            sum += *src++;
-
-        float value = (sum * q.scale + q.bias) / kernel_size;
-        dest[oc] = value;
-    }
-}
-
-void kpu_matmul_end(const uint8_t *src, int channels, float *dest, const quantize_param_t *dest_param)
-{
-    quantize_param_t q1 = *dest_param;
-    size_t i = 0;
-    for(i = 0; i < channels; i++)
-        *dest++ = src[i * 16] * q1.scale + q1.bias;
-}
-
-void kpu_fully_connected(const float *src, const float *weights, const float *biases, float *dest, int input_channels, int output_channels)
-{
-    int ic, oc;
-    for(oc = 0; oc < output_channels; oc++)
-    {
-        const float *c_weights = weights + oc * input_channels;
-
-        float sum = 0.0f;
-        for(ic = 0; ic < input_channels; ic++)
-            sum += src[ic] * c_weights[ic];
-        dest[oc] = sum + biases[oc];
-    }
-}
-
-void kpu_dequantize(const uint8_t *src, const quantize_param_t *src_param, size_t count, float *dest)
-{
-    quantize_param_t q1 = *src_param;
-    size_t i = 0;
-    for(i = 0; i < count; i++)
-        *dest++ = src[i] * q1.scale + q1.bias;
-}
-
-void kpu_input_with_padding(kpu_layer_argument_t *layer, const uint8_t *src, int width, int height, int channels)
-{
-    uint8_t *dest = (uint8_t *)(uintptr_t)(AI_IO_BASE_ADDR + layer->image_addr.data.image_src_addr * 64);
-    size_t oc, y, x;
-
-    uint32_t row_padding;
-    uint32_t row_group;
-    uint32_t row_length;
-
-    if(width <= 16)
-    {
-        row_padding = 16;
-        row_group = 4;
-        row_length = 1;
-    } else if(width <= 32)
-    {
-        row_padding = 32;
-        row_group = 2;
-        row_length = 1;
-    } else
-    {
-        row_padding = 64;
-        row_group = 1;
-        row_length = (width + 63) / 64;
-    }
-
-    for(oc = 0; oc < channels; oc++)
-    {
-        uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
-        for(y = 0; y < height; y++)
-        {
-            uint8_t *y_origin = channel_origin + y * row_length * 64;
-            for(x = 0; x < width; x++)
-                y_origin[x] = *src++;
-        }
-    }
-}
+	quantize_param_t q = *src_param;
+	size_t oc;
+
+	for (oc = 0; oc < channels; oc++)
+	{
+		int64_t sum = 0;
+		size_t i;
+		for (i = 0; i < kernel_size; i++)
+			sum += *src++;
+
+		float value = (sum * q.scale + q.bias) / kernel_size;
+		dest[oc] = value;
+	}
+}
+
 #if USE_CACHED_AI_RAM
 static void kpu_flush_cache(uint32_t addr, size_t lines)
 {
-    size_t line;
-    for(line = 0; line < lines; line++)
-    {
-        const uint64_t *src = (const uint64_t *)(AI_RAM_BASE_ADDR + (addr + line) * 64);
-        uint64_t *dest = (uint64_t *)(AI_IO_BASE_ADDR + (addr + line) * 64);
-        size_t i;
-        for(i = 0; i < 8; i++)
-            dest[i] = src[i];
-    }
+	size_t line;
+	for (line = 0; line < lines; line++)
+	{
+		const uint64_t *src = (const uint64_t *)(AI_RAM_BASE_ADDR + (addr + line) * 64);
+		uint64_t *dest = (uint64_t *)(AI_IO_BASE_ADDR + (addr + line) * 64);
+		size_t i;
+		for (i = 0; i < 8; i++)
+			dest[i] = src[i];
+	}
 }
 #endif
 static int64_t kpu_carry_shift(int64_t value, uint32_t shift)
 {
-    if(shift > 0)
-    {
-        value >>= shift - 1;
-        if(value & 0x1)
-        {
-            if(value < 0)
-                value = (value >> 1) - 1;
-            else
-                value = (value >> 1) + 1;
-        } else
-        {
-            value >>= 1;
-        }
-    }
-
-    return value;
+	if (shift > 0)
+	{
+		value >>= shift - 1;
+		if (value & 0x1)
+		{
+			if (value < 0)
+				value = (value >> 1) - 1;
+			else
+				value = (value >> 1) + 1;
+		}
+		else
+		{
+			value >>= 1;
+		}
+	}
+
+	return value;
 }
 static void kpu_upload_core(size_t width, size_t height, size_t channels, const uint8_t *src, uint32_t kpu_addr)
 {
-    uint8_t *dest = (uint8_t *)(uintptr_t)(AI_IO_BASE_ADDR + kpu_addr * 64);
-    size_t oc, y, x;
-    uint32_t row_padding;
-    uint32_t row_group;
-    uint32_t row_length;
-    if(width <= 16)
-    {
-        row_padding = 16;
-        row_group = 4;
-        row_length = 1;
-    } else if(width <= 32)
-    {
-        row_padding = 32;
-        row_group = 2;
-        row_length = 1;
-    } else
-    {
-        row_padding = 64;
-        row_group = 1;
-        row_length = (width + 63) / 64;
-    }
-
-    if((uintptr_t)src % 8 == 0 && width % 8 == 0)
-    {
+	uint8_t *dest = (uint8_t *)(uintptr_t)(AI_IO_BASE_ADDR + kpu_addr * 64);
+	size_t oc, y, x;
+	uint32_t row_padding;
+	uint32_t row_group;
+	uint32_t row_length;
+	if (width <= 16)
+	{
+		row_padding = 16;
+		row_group = 4;
+		row_length = 1;
+	}
+	else if (width <= 32)
+	{
+		row_padding = 32;
+		row_group = 2;
+		row_length = 1;
+	}
+	else
+	{
+		row_padding = 64;
+		row_group = 1;
+		row_length = (width + 63) / 64;
+	}
+
+	if ((uintptr_t)src % 8 == 0 && width % 8 == 0)
+	{
 #define UPLOAD_BEGIN()                                                                                             \
-    for(oc = 0; oc < channels; oc++)                                                                               \
-    {                                                                                                              \
-        uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; \
-        for(y = 0; y < height; y++)                                                                                \
-        {                                                                                                          \
-            uint64_t *y_origin = (uint64_t *)(channel_origin + y * row_length * 64);
+	for (oc = 0; oc < channels; oc++)                                                                              \
+	{                                                                                                              \
+		uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding; \
+		for (y = 0; y < height; y++)                                                                               \
+		{                                                                                                          \
+			uint64_t *y_origin = (uint64_t *)(channel_origin + y * row_length * 64);
 
 #define UPLOAD_END() \
-    }                \
-    }
-
-        width /= 8;
-        const uint64_t *u64_src = (const uint64_t *)src;
-        if(width == 1)
-        {
-            UPLOAD_BEGIN()
-            y_origin[0] = *u64_src++;
-            UPLOAD_END()
-        } else if(width == 2)
-        {
-            UPLOAD_BEGIN()
-            {
-                y_origin[0] = *u64_src++;
-                y_origin[1] = *u64_src++;
-            }
-            UPLOAD_END()
-        } else if(width == 4)
-        {
-            UPLOAD_BEGIN()
-            {
-                y_origin[0] = *u64_src++;
-                y_origin[1] = *u64_src++;
-                y_origin[2] = *u64_src++;
-                y_origin[3] = *u64_src++;
-            }
-            UPLOAD_END()
-        } else
-        {
-            UPLOAD_BEGIN()
-            for(x = 0; x < width; x++)
-                y_origin[x] = *u64_src++;
-            UPLOAD_END()
-        }
-    } else
-    {
-        for(oc = 0; oc < channels; oc++)
-        {
-            uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
-            for(y = 0; y < height; y++)
-            {
-                uint8_t *y_origin = channel_origin + y * row_length * 64;
-                for(x = 0; x < width; x++)
-                    y_origin[x] = *src++;
-            }
-        }
-    }
+	}                \
+	}
+
+		width /= 8;
+		const uint64_t *u64_src = (const uint64_t *)src;
+		if (width == 1)
+		{
+			UPLOAD_BEGIN()
+			y_origin[0] = *u64_src++;
+			UPLOAD_END()
+		}
+		else if (width == 2)
+		{
+			UPLOAD_BEGIN()
+			{
+				y_origin[0] = *u64_src++;
+				y_origin[1] = *u64_src++;
+			}
+			UPLOAD_END()
+		}
+		else if (width == 4)
+		{
+			UPLOAD_BEGIN()
+			{
+				y_origin[0] = *u64_src++;
+				y_origin[1] = *u64_src++;
+				y_origin[2] = *u64_src++;
+				y_origin[3] = *u64_src++;
+			}
+			UPLOAD_END()
+		}
+		else
+		{
+			UPLOAD_BEGIN()
+			for (x = 0; x < width; x++)
+				y_origin[x] = *u64_src++;
+			UPLOAD_END()
+		}
+	}
+	else
+	{
+		for (oc = 0; oc < channels; oc++)
+		{
+			uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
+			for (y = 0; y < height; y++)
+			{
+				uint8_t *y_origin = channel_origin + y * row_length * 64;
+				for (x = 0; x < width; x++)
+					y_origin[x] = *src++;
+			}
+		}
+	}
 }
 static void kpu_kmodel_input_with_padding(const kpu_layer_argument_t *layer, const uint8_t *src)
 {
-    size_t width = layer->image_size.data.i_row_wid + 1;
-    size_t height = layer->image_size.data.i_col_high + 1;
-    size_t channels = layer->image_channel_num.data.i_ch_num + 1;
-
-    kpu_upload_core(width, height, channels, src, layer->image_addr.data.image_src_addr);
+	size_t width = layer->image_size.data.i_row_wid + 1;
+	size_t height = layer->image_size.data.i_col_high + 1;
+	size_t channels = layer->image_channel_num.data.i_ch_num + 1;
+
+	kpu_upload_core(width, height, channels, src, layer->image_addr.data.image_src_addr);
 }
 
 static void kpu_kmodel_input_float(const float *src, float *dest, size_t count)
 {
-    memcpy(dest, src, count * sizeof(float));
+	memcpy(dest, src, count * sizeof(float));
 }
 
 static void kpu_float_activation(float *data, size_t count, kpu_model_activation_t act)
 {
-    size_t i;
-
-    if(act == KLA_RELU)
-    {
-        for(i = 0; i < count; i++)
-            data[i] = max(data[i], 0);
-    } else if(act == KLA_RELU6)
-    {
-        for(i = 0; i < count; i++)
-            data[i] = min(max(data[i], 0), 6);
-    }
+	size_t i;
+
+	if (act == KLA_RELU)
+	{
+		for (i = 0; i < count; i++)
+			data[i] = max(data[i], 0);
+	}
+	else if (act == KLA_RELU6)
+	{
+		for (i = 0; i < count; i++)
+			data[i] = min(max(data[i], 0), 6);
+	}
 }
 
 static void kpu_kmodel_add(const kpu_model_add_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src_a = (const float *)(ctx->main_buffer + arg->main_mem_in_a_address);
-    const float *src_b = (const float *)(ctx->main_buffer + arg->main_mem_in_b_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t i, count = arg->count;
-
-    for(i = 0; i < count; i++)
-        dest[i] = src_a[i] + src_b[i];
+	const float *src_a = (const float *)(ctx->main_buffer + arg->main_mem_in_a_address);
+	const float *src_b = (const float *)(ctx->main_buffer + arg->main_mem_in_b_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t i, count = arg->count;
+
+	for (i = 0; i < count; i++)
+		dest[i] = src_a[i] + src_b[i];
 }
 
 static void kpu_quantized_add(const kpu_model_quant_add_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src_a = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_a_address);
-    const uint8_t *src_b = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_b_address);
-    size_t count = ALIGN_UP(arg->count, 8) / 8;
-    int64_t off_a = arg->in_a_offset, mul_a = arg->in_a_mul, sh_a = arg->in_a_shift;
-    int64_t off_b = arg->in_b_offset, mul_b = arg->in_b_mul, sh_b = arg->in_b_shift;
-    int64_t off_o = arg->out_offset, mul_o = arg->out_mul, sh_o = arg->out_shift;
-
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t i;
-
-    if(sh_a == sh_b)
-    {
+	const uint8_t *src_a = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_a_address);
+	const uint8_t *src_b = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_b_address);
+	size_t count = ALIGN_UP(arg->count, 8) / 8;
+	int64_t off_a = arg->in_a_offset, mul_a = arg->in_a_mul, sh_a = arg->in_a_shift;
+	int64_t off_b = arg->in_b_offset, mul_b = arg->in_b_mul, sh_b = arg->in_b_shift;
+	int64_t off_o = arg->out_offset, mul_o = arg->out_mul, sh_o = arg->out_shift;
+
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t i;
+
+	if (sh_a == sh_b)
+	{
 #define QADD_UNROLL_1(x)     \
-    int64_t a##x = *src_a++; \
-    int64_t b##x = *src_b++;
+	int64_t a##x = *src_a++; \
+	int64_t b##x = *src_b++;
 
 #define QADD_UNROLL_2(x) \
-    a##x += off_a;       \
-    b##x += off_b;
+	a##x += off_a;       \
+	b##x += off_b;
 
 #define QADD_UNROLL_3(x) \
-    a##x *= mul_a;       \
-    b##x *= mul_b;
+	a##x *= mul_a;       \
+	b##x *= mul_b;
 
 #define QADD_UNROLL_4(x) \
-    int64_t v##x = a##x + b##x;
+	int64_t v##x = a##x + b##x;
 
 #define QADD_UNROLL_5(x) \
-    v##x >>= sh_a;
+	v##x >>= sh_a;
 
 #define QADD_UNROLL_6(x) \
-    v##x *= mul_o;
+	v##x *= mul_o;
 
 #define QADD_UNROLL_7(x) \
-    v##x = kpu_carry_shift(v##x, sh_o);
+	v##x = kpu_carry_shift(v##x, sh_o);
 
 #define QADD_UNROLL_8(x) \
-    v##x += off_o;
+	v##x += off_o;
 
 #define QADD_UNROLL_9(x) \
-    v##x = min(0xFF, max(0, v##x));
+	v##x = min(0xFF, max(0, v##x));
 
 #define QADD_UNROLL_10(x) \
-    *dest++ = v##x;
+	*dest++ = v##x;
 
 #define QADD_UNROLL_S(x)                       \
-    QADD_UNROLL_##x(0)                         \
-        QADD_UNROLL_##x(1)                     \
-            QADD_UNROLL_##x(2)                 \
-                QADD_UNROLL_##x(3)             \
-                    QADD_UNROLL_##x(4)         \
-                        QADD_UNROLL_##x(5)     \
-                            QADD_UNROLL_##x(6) \
-                                QADD_UNROLL_##x(7)
-
-        for(i = 0; i < count; i++)
-        {
-            QADD_UNROLL_S(1);
-            QADD_UNROLL_S(2);
-            QADD_UNROLL_S(3);
-            QADD_UNROLL_S(4);
-            QADD_UNROLL_S(5);
-            QADD_UNROLL_S(6);
-            QADD_UNROLL_S(7);
-            QADD_UNROLL_S(8);
-            QADD_UNROLL_S(9);
-            QADD_UNROLL_S(10);
-        }
-    } else
-    {
+	QADD_UNROLL_##x(0)                         \
+		QADD_UNROLL_##x(1)                     \
+			QADD_UNROLL_##x(2)                 \
+				QADD_UNROLL_##x(3)             \
+					QADD_UNROLL_##x(4)         \
+						QADD_UNROLL_##x(5)     \
+							QADD_UNROLL_##x(6) \
+								QADD_UNROLL_##x(7)
+
+		for (i = 0; i < count; i++)
+		{
+			QADD_UNROLL_S(1);
+			QADD_UNROLL_S(2);
+			QADD_UNROLL_S(3);
+			QADD_UNROLL_S(4);
+			QADD_UNROLL_S(5);
+			QADD_UNROLL_S(6);
+			QADD_UNROLL_S(7);
+			QADD_UNROLL_S(8);
+			QADD_UNROLL_S(9);
+			QADD_UNROLL_S(10);
+		}
+	}
+	else
+	{
 #undef QADD_UNROLL_1
 #define QADD_UNROLL_1(x)     \
-    int64_t a##x = *src_a++; \
-    int64_t b##x = *src_b++;
+	int64_t a##x = *src_a++; \
+	int64_t b##x = *src_b++;
 
 #undef QADD_UNROLL_2
 #define QADD_UNROLL_2(x) \
-    a##x += off_a;       \
-    b##x += off_b;
+	a##x += off_a;       \
+	b##x += off_b;
 
 #undef QADD_UNROLL_3
 #define QADD_UNROLL_3(x) \
-    a##x *= mul_a;       \
-    b##x *= mul_b;
+	a##x *= mul_a;       \
+	b##x *= mul_b;
 
 #undef QADD_UNROLL_4
 #define QADD_UNROLL_4(x) \
-    a##x >>= sh_a;       \
-    b##x >>= sh_b;
+	a##x >>= sh_a;       \
+	b##x >>= sh_b;
 
 #undef QADD_UNROLL_5
 #define QADD_UNROLL_5(x) \
-    int64_t v##x = a##x + b##x;
+	int64_t v##x = a##x + b##x;
 
 #undef QADD_UNROLL_6
 #define QADD_UNROLL_6(x) \
-    v##x *= mul_o;
+	v##x *= mul_o;
 
 #undef QADD_UNROLL_7
 #define QADD_UNROLL_7(x) \
-    v##x = kpu_carry_shift(v##x, sh_o);
+	v##x = kpu_carry_shift(v##x, sh_o);
 
 #undef QADD_UNROLL_8
 #define QADD_UNROLL_8(x) \
-    v##x += off_o;
+	v##x += off_o;
 
 #undef QADD_UNROLL_9
 #define QADD_UNROLL_9(x) \
-    v##x = min(0xFF, max(0, v##x));
+	v##x = min(0xFF, max(0, v##x));
 
 #undef QADD_UNROLL_10
 #define QADD_UNROLL_10(x) \
-    *dest++ = v##x;
+	*dest++ = v##x;
 
 #undef QADD_UNROLL_S
 #define QADD_UNROLL_S(x)                       \
-    QADD_UNROLL_##x(0)                         \
-        QADD_UNROLL_##x(1)                     \
-            QADD_UNROLL_##x(2)                 \
-                QADD_UNROLL_##x(3)             \
-                    QADD_UNROLL_##x(4)         \
-                        QADD_UNROLL_##x(5)     \
-                            QADD_UNROLL_##x(6) \
-                                QADD_UNROLL_##x(7)
-
-        for(i = 0; i < count; i++)
-        {
-            QADD_UNROLL_S(1);
-            QADD_UNROLL_S(2);
-            QADD_UNROLL_S(3);
-            QADD_UNROLL_S(4);
-            QADD_UNROLL_S(5);
-            QADD_UNROLL_S(6);
-            QADD_UNROLL_S(7);
-            QADD_UNROLL_S(8);
-            QADD_UNROLL_S(9);
-            QADD_UNROLL_S(10);
-        }
-    }
+	QADD_UNROLL_##x(0)                         \
+		QADD_UNROLL_##x(1)                     \
+			QADD_UNROLL_##x(2)                 \
+				QADD_UNROLL_##x(3)             \
+					QADD_UNROLL_##x(4)         \
+						QADD_UNROLL_##x(5)     \
+							QADD_UNROLL_##x(6) \
+								QADD_UNROLL_##x(7)
+
+		for (i = 0; i < count; i++)
+		{
+			QADD_UNROLL_S(1);
+			QADD_UNROLL_S(2);
+			QADD_UNROLL_S(3);
+			QADD_UNROLL_S(4);
+			QADD_UNROLL_S(5);
+			QADD_UNROLL_S(6);
+			QADD_UNROLL_S(7);
+			QADD_UNROLL_S(8);
+			QADD_UNROLL_S(9);
+			QADD_UNROLL_S(10);
+		}
+	}
 }
 
 static void kpu_global_average_pool2d(const kpu_model_gap2d_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, channels = arg->channels, kernel_size = arg->kernel_size;
-
-    for(oc = 0; oc < channels; oc++)
-    {
-        float sum = 0.f;
-        size_t i;
-        for(i = 0; i < kernel_size; i++)
-            sum += *src++;
-
-        dest[oc] = sum / kernel_size;
-    }
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, channels = arg->channels, kernel_size = arg->kernel_size;
+
+	for (oc = 0; oc < channels; oc++)
+	{
+		float sum = 0.f;
+		size_t i;
+		for (i = 0; i < kernel_size; i++)
+			sum += *src++;
+
+		dest[oc] = sum / kernel_size;
+	}
 }
 
 static void kpu_quantized_max_pool2d(const kpu_model_quant_max_pool2d_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape;
-    uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height;
-    uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height;
-    uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height;
-
-    uint32_t out_y, out_x, oc;
-
-    for(oc = 0; oc < out_shape.channels; oc++)
-    {
-        const uint8_t *channel_src = src + in_shape.width * in_shape.height * oc;
-        for(out_y = 0; out_y < out_shape.height; out_y++)
-        {
-            for(out_x = 0; out_x < out_shape.width; out_x++)
-            {
-                int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width;
-                int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height;
-                int32_t kernel_x_start = max(0, -in_x_origin);
-                int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin);
-                int32_t kernel_y_start = max(0, -in_y_origin);
-                int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin);
-                uint8_t value = 0;
-
-                int32_t kernel_y, kernel_x;
-                for(kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++)
-                {
-                    for(kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++)
-                    {
-                        int32_t in_x = in_x_origin + kernel_x;
-                        int32_t in_y = in_y_origin + kernel_y;
-                        value = max(value, channel_src[in_y * in_shape.width + in_x]);
-                    }
-                }
-
-                *dest++ = value;
-            }
-        }
-    }
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape;
+	uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height;
+	uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height;
+	uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height;
+
+	uint32_t out_y, out_x, oc;
+
+	for (oc = 0; oc < out_shape.channels; oc++)
+	{
+		const uint8_t *channel_src = src + in_shape.width * in_shape.height * oc;
+		for (out_y = 0; out_y < out_shape.height; out_y++)
+		{
+			for (out_x = 0; out_x < out_shape.width; out_x++)
+			{
+				int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width;
+				int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height;
+				int32_t kernel_x_start = max(0, -in_x_origin);
+				int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin);
+				int32_t kernel_y_start = max(0, -in_y_origin);
+				int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin);
+				uint8_t value = 0;
+
+				int32_t kernel_y, kernel_x;
+				for (kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++)
+				{
+					for (kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++)
+					{
+						int32_t in_x = in_x_origin + kernel_x;
+						int32_t in_y = in_y_origin + kernel_y;
+						value = max(value, channel_src[in_y * in_shape.width + in_x]);
+					}
+				}
+
+				*dest++ = value;
+			}
+		}
+	}
 }
 
 static void kpu_average_pool2d(const kpu_model_ave_pool2d_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape;
-    uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height;
-    uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height;
-    uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height;
-
-    uint32_t out_y, out_x, oc;
-
-    for(oc = 0; oc < out_shape.channels; oc++)
-    {
-        const float *channel_src = src + in_shape.width * in_shape.height * oc;
-        for(out_y = 0; out_y < out_shape.height; out_y++)
-        {
-            for(out_x = 0; out_x < out_shape.width; out_x++)
-            {
-                int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width;
-                int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height;
-                int32_t kernel_x_start = max(0, -in_x_origin);
-                int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin);
-                int32_t kernel_y_start = max(0, -in_y_origin);
-                int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin);
-                float value = 0;
-                float kernel_count = 0;
-
-                int32_t kernel_y, kernel_x;
-                for(kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++)
-                {
-                    for(kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++)
-                    {
-                        int32_t in_x = in_x_origin + kernel_x;
-                        int32_t in_y = in_y_origin + kernel_y;
-                        value += channel_src[in_y * in_shape.width + in_x];
-                        kernel_count++;
-                    }
-                }
-
-                *dest++ = value / kernel_count;
-            }
-        }
-    }
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	kpu_model_shape_t in_shape = arg->in_shape, out_shape = arg->out_shape;
+	uint32_t kernel_width = arg->kernel_width, kernel_height = arg->kernel_height;
+	uint32_t stride_width = arg->stride_width, stride_height = arg->stride_height;
+	uint32_t padding_width = arg->padding_width, padding_height = arg->padding_height;
+
+	uint32_t out_y, out_x, oc;
+
+	for (oc = 0; oc < out_shape.channels; oc++)
+	{
+		const float *channel_src = src + in_shape.width * in_shape.height * oc;
+		for (out_y = 0; out_y < out_shape.height; out_y++)
+		{
+			for (out_x = 0; out_x < out_shape.width; out_x++)
+			{
+				int32_t in_x_origin = (int32_t)(out_x * stride_width) - padding_width;
+				int32_t in_y_origin = (int32_t)(out_y * stride_height) - padding_height;
+				int32_t kernel_x_start = max(0, -in_x_origin);
+				int32_t kernel_x_end = min(kernel_width, in_shape.width - in_x_origin);
+				int32_t kernel_y_start = max(0, -in_y_origin);
+				int32_t kernel_y_end = min(kernel_height, in_shape.height - in_y_origin);
+				float value = 0;
+				float kernel_count = 0;
+
+				int32_t kernel_y, kernel_x;
+				for (kernel_y = kernel_y_start; kernel_y < kernel_y_end; kernel_y++)
+				{
+					for (kernel_x = kernel_x_start; kernel_x < kernel_x_end; kernel_x++)
+					{
+						int32_t in_x = in_x_origin + kernel_x;
+						int32_t in_y = in_y_origin + kernel_y;
+						value += channel_src[in_y * in_shape.width + in_x];
+						kernel_count++;
+					}
+				}
+
+				*dest++ = value / kernel_count;
+			}
+		}
+	}
 }
 
 static void kpu_quantize(const kpu_model_quantize_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    size_t count = arg->count;
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-
-    kpu_model_quant_param_t q = arg->quant_param;
-
-    float scale = 1.f / q.scale;
-
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->mem_out_address);
-    size_t i;
-    for(i = 0; i < count; i++)
-    {
-        int value = roundf((*src++ - q.bias) * scale);
-        if(value < 0)
-            value = 0;
-        if(value > 0xFF)
-            value = 0xFF;
-        *dest++ = (uint8_t)value;
-    }
+	size_t count = arg->count;
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+
+	kpu_model_quant_param_t q = arg->quant_param;
+
+	float scale = 1.f / q.scale;
+
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->mem_out_address);
+	size_t i;
+	for (i = 0; i < count; i++)
+	{
+		int value = roundf((*src++ - q.bias) * scale);
+		if (value < 0)
+			value = 0;
+		if (value > 0xFF)
+			value = 0xFF;
+		*dest++ = (uint8_t)value;
+	}
 }
 
 static void kpu_kmodel_dequantize(const kpu_model_dequantize_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, count = arg->count;
-    kpu_model_quant_param_t q = arg->quant_param;
-
-    for(oc = 0; oc < count; oc++)
-        dest[oc] = *src++ * q.scale + q.bias;
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, count = arg->count;
+	kpu_model_quant_param_t q = arg->quant_param;
+
+	for (oc = 0; oc < count; oc++)
+		dest[oc] = *src++ * q.scale + q.bias;
 }
 
 static void kpu_kmodel_channelwise_dequantize(const kpu_model_channelwise_dequant_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, i, channels = arg->channels, count = arg->channel_size;
-
-    for(oc = 0; oc < channels; oc++)
-    {
-        const kpu_model_quant_param_t q = arg->quant_params[oc];
-
-        for(i = 0; i < count; i++)
-            *dest++ = *src++ * q.scale + q.bias;
-    }
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, i, channels = arg->channels, count = arg->channel_size;
+
+	for (oc = 0; oc < channels; oc++)
+	{
+		const kpu_model_quant_param_t q = arg->quant_params[oc];
+
+		for (i = 0; i < count; i++)
+			*dest++ = *src++ * q.scale + q.bias;
+	}
 }
 
 static void kpu_requantize(const kpu_model_requantize_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, count = arg->count;
-    const uint8_t *table = arg->table;
-
-    if(false && count % 8 == 0)
-    {
-        for(oc = 0; oc < count;)
-        {
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-            dest[oc++] = table[*src++];
-        }
-    } else
-    {
-        for(oc = 0; oc < count; oc++)
-            dest[oc] = table[src[oc]];
-    }
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, count = arg->count;
+	const uint8_t *table = arg->table;
+
+	if (false && count % 8 == 0)
+	{
+		for (oc = 0; oc < count;)
+		{
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+			dest[oc++] = table[*src++];
+		}
+	}
+	else
+	{
+		for (oc = 0; oc < count; oc++)
+			dest[oc] = table[src[oc]];
+	}
 }
 
 static void kpu_l2_normalization(const kpu_model_l2_norm_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, channels = arg->channels;
-
-    float sum = 0.f;
-    const float epsilon = 1e-10f;
-    for(oc = 0; oc < channels; oc++)
-        sum += src[oc] * src[oc];
-    if(sum < epsilon)
-        sum = epsilon;
-    sum = 1.f / sqrtf(sum);
-    for(oc = 0; oc < channels; oc++)
-        dest[oc] = src[oc] * sum;
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, channels = arg->channels;
+
+	float sum = 0.f;
+	const float epsilon = 1e-10f;
+	for (oc = 0; oc < channels; oc++)
+		sum += src[oc] * src[oc];
+	if (sum < epsilon)
+		sum = epsilon;
+	sum = 1.f / sqrtf(sum);
+	for (oc = 0; oc < channels; oc++)
+		dest[oc] = src[oc] * sum;
 }
 
 static void kpu_softmax(const kpu_model_softmax_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, channels = arg->channels;
-
-    float max = FLT_MIN;
-    for(oc = 0; oc < channels; oc++)
-        max = fmaxf(max, src[oc]);
-
-    float sum = 0.f;
-    for(oc = 0; oc < channels; oc++)
-    {
-        float value = expf(src[oc] - max);
-        sum += value;
-        dest[oc] = value;
-    }
-
-    for(oc = 0; oc < channels; oc++)
-        dest[oc] /= sum;
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, channels = arg->channels;
+
+	float max = FLT_MIN;
+	for (oc = 0; oc < channels; oc++)
+		max = fmaxf(max, src[oc]);
+
+	float sum = 0.f;
+	for (oc = 0; oc < channels; oc++)
+	{
+		float value = expf(src[oc] - max);
+		sum += value;
+		dest[oc] = value;
+	}
+
+	for (oc = 0; oc < channels; oc++)
+		dest[oc] /= sum;
 }
 
 static void kpu_concat(const kpu_model_concat_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    uint32_t count = arg->input_count, i;
-
-    for(i = 0; i < count; i++)
-    {
-        kpu_model_memory_range_t input = arg->inputs_mem[i];
-        const uint8_t *src = (const uint8_t *)(ctx->main_buffer + input.start);
-        memcpy(dest, src, input.size);
-        dest += input.size;
-    }
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	uint32_t count = arg->input_count, i;
+
+	for (i = 0; i < count; i++)
+	{
+		kpu_model_memory_range_t input = arg->inputs_mem[i];
+		const uint8_t *src = (const uint8_t *)(ctx->main_buffer + input.start);
+		memcpy(dest, src, input.size);
+		dest += input.size;
+	}
 }
 
 static void kpu_kmodel_fully_connected(const kpu_model_fully_connected_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    uint32_t in_channels = arg->in_channels, out_channels = arg->out_channels, ic, oc;
-    float *weights = (float *)malloc(in_channels * out_channels * sizeof(float));
-    float *bias = (float *)malloc(out_channels * sizeof(float));
-    memcpy(weights, arg->weights, out_channels * in_channels * sizeof(float));
-    memcpy(bias, arg->weights + in_channels * out_channels, out_channels * sizeof(float));
-
-    if(in_channels % 8 == 0)
-    {
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	uint32_t in_channels = arg->in_channels, out_channels = arg->out_channels, ic, oc;
+	float *weights = (float *)malloc(in_channels * out_channels * sizeof(float));
+	float *bias = (float *)malloc(out_channels * sizeof(float));
+	memcpy(weights, arg->weights, out_channels * in_channels * sizeof(float));
+	memcpy(bias, arg->weights + in_channels * out_channels, out_channels * sizeof(float));
+
+	if (in_channels % 8 == 0)
+	{
 #define FC_UNROLL_1(x)     \
-    float i##x = *c_src++; \
-    float w##x = *c_weights++;
+	float i##x = *c_src++; \
+	float w##x = *c_weights++;
 
 #define FC_UNROLL_2(x) \
-    sum += i##x * w##x;
+	sum += i##x * w##x;
 
 #define FC_UNROLL_S(x)                       \
-    FC_UNROLL_##x(0)                         \
-        FC_UNROLL_##x(1)                     \
-            FC_UNROLL_##x(2)                 \
-                FC_UNROLL_##x(3)             \
-                    FC_UNROLL_##x(4)         \
-                        FC_UNROLL_##x(5)     \
-                            FC_UNROLL_##x(6) \
-                                FC_UNROLL_##x(7)
-
-        for(oc = 0; oc < out_channels; oc++)
-        {
-            const float *c_src = src;
-            const float *c_weights = weights + oc * in_channels;
-
-            float sum = 0.0f;
-            for(ic = 0; ic < in_channels / 8; ic++)
-            {
-                FC_UNROLL_S(1);
-                FC_UNROLL_S(2);
-            }
-
-            dest[oc] = sum + bias[oc];
-        }
-    } else
-    {
-        for(oc = 0; oc < out_channels; oc++)
-        {
-            const float *c_weights = weights + oc * in_channels;
-
-            float sum = 0.0f;
-            for(ic = 0; ic < in_channels; ic++)
-                sum += src[ic] * c_weights[ic];
-            dest[oc] = sum + bias[oc];
-        }
-    }
-    free(weights);
-    free(bias);
-    kpu_float_activation(dest, out_channels, arg->act);
+	FC_UNROLL_##x(0)                         \
+		FC_UNROLL_##x(1)                     \
+			FC_UNROLL_##x(2)                 \
+				FC_UNROLL_##x(3)             \
+					FC_UNROLL_##x(4)         \
+						FC_UNROLL_##x(5)     \
+							FC_UNROLL_##x(6) \
+								FC_UNROLL_##x(7)
+
+		for (oc = 0; oc < out_channels; oc++)
+		{
+			const float *c_src = src;
+			const float *c_weights = weights + oc * in_channels;
+
+			float sum = 0.0f;
+			for (ic = 0; ic < in_channels / 8; ic++)
+			{
+				FC_UNROLL_S(1);
+				FC_UNROLL_S(2);
+			}
+
+			dest[oc] = sum + bias[oc];
+		}
+	}
+	else
+	{
+		for (oc = 0; oc < out_channels; oc++)
+		{
+			const float *c_weights = weights + oc * in_channels;
+
+			float sum = 0.0f;
+			for (ic = 0; ic < in_channels; ic++)
+				sum += src[ic] * c_weights[ic];
+			dest[oc] = sum + bias[oc];
+		}
+	}
+	free(weights);
+	free(bias);
+	kpu_float_activation(dest, out_channels, arg->act);
 }
 
 static void kpu_tf_flatten(const kpu_model_tf_flatten_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    kpu_model_shape_t in_shape = arg->shape;
-    uint32_t oc, oy, ox;
-
-    for(oy = 0; oy < in_shape.height; oy++)
-        for(ox = 0; ox < in_shape.width; ox++)
-            for(oc = 0; oc < in_shape.channels; oc++)
-                *dest++ = src[(oc * in_shape.height + oy) * in_shape.width + ox];
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	kpu_model_shape_t in_shape = arg->shape;
+	uint32_t oc, oy, ox;
+
+	for (oy = 0; oy < in_shape.height; oy++)
+		for (ox = 0; ox < in_shape.width; ox++)
+			for (oc = 0; oc < in_shape.channels; oc++)
+				*dest++ = src[(oc * in_shape.height + oy) * in_shape.width + ox];
 }
 
 static void kpu_resize_nearest_neighbor(const kpu_model_resize_nearest_neighbor_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    kpu_model_shape_t in_shape = arg->in_shape;
-    uint32_t out_width = arg->out_width, out_height = arg->out_height;
-    uint32_t oc, oy, ox;
-
-    float height_scale = (float)in_shape.height / out_height;
-    float width_scale = (float)in_shape.width / out_width;
-
-    for(oc = 0; oc < in_shape.channels; oc++)
-    {
-        const float *channel_src = src + in_shape.width * in_shape.height * oc;
-        for(oy = 0; oy < out_height; oy++)
-        {
-            uint32_t in_y = (uint32_t)min(floorf(oy * height_scale), in_shape.height - 1);
-            const float *y_origin = channel_src + in_y * in_shape.width;
-            for(ox = 0; ox < out_width; ox++)
-            {
-                uint32_t in_x = (uint32_t)min(floorf(ox * width_scale), in_shape.width - 1);
-                *dest++ = y_origin[in_x];
-            }
-        }
-    }
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	kpu_model_shape_t in_shape = arg->in_shape;
+	uint32_t out_width = arg->out_width, out_height = arg->out_height;
+	uint32_t oc, oy, ox;
+
+	float height_scale = (float)in_shape.height / out_height;
+	float width_scale = (float)in_shape.width / out_width;
+
+	for (oc = 0; oc < in_shape.channels; oc++)
+	{
+		const float *channel_src = src + in_shape.width * in_shape.height * oc;
+		for (oy = 0; oy < out_height; oy++)
+		{
+			uint32_t in_y = (uint32_t)min(floorf(oy * height_scale), in_shape.height - 1);
+			const float *y_origin = channel_src + in_y * in_shape.width;
+			for (ox = 0; ox < out_width; ox++)
+			{
+				uint32_t in_x = (uint32_t)min(floorf(ox * width_scale), in_shape.width - 1);
+				*dest++ = y_origin[in_x];
+			}
+		}
+	}
 }
 
 static void kpu_quant_resize_nearest_neighbor(const kpu_model_quant_resize_nearest_neighbor_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    kpu_model_shape_t in_shape = arg->in_shape;
-    uint32_t out_width = arg->out_width, out_height = arg->out_height;
-    uint32_t oc, oy, ox;
-
-    float height_scale = (float)in_shape.height / out_height;
-    float width_scale = (float)in_shape.width / out_width;
-
-    for(oc = 0; oc < in_shape.channels; oc++)
-    {
-        const uint8_t *channel_src = src + in_shape.width * in_shape.height * oc;
-        for(oy = 0; oy < out_height; oy++)
-        {
-            uint32_t in_y = (uint32_t)min(floorf(oy * height_scale), in_shape.height - 1);
-            const uint8_t *y_origin = channel_src + in_y * in_shape.width;
-            for(ox = 0; ox < out_width; ox++)
-            {
-                uint32_t in_x = (uint32_t)min(floorf(ox * width_scale), in_shape.width - 1);
-                *dest++ = y_origin[in_x];
-            }
-        }
-    }
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	kpu_model_shape_t in_shape = arg->in_shape;
+	uint32_t out_width = arg->out_width, out_height = arg->out_height;
+	uint32_t oc, oy, ox;
+
+	float height_scale = (float)in_shape.height / out_height;
+	float width_scale = (float)in_shape.width / out_width;
+
+	for (oc = 0; oc < in_shape.channels; oc++)
+	{
+		const uint8_t *channel_src = src + in_shape.width * in_shape.height * oc;
+		for (oy = 0; oy < out_height; oy++)
+		{
+			uint32_t in_y = (uint32_t)min(floorf(oy * height_scale), in_shape.height - 1);
+			const uint8_t *y_origin = channel_src + in_y * in_shape.width;
+			for (ox = 0; ox < out_width; ox++)
+			{
+				uint32_t in_x = (uint32_t)min(floorf(ox * width_scale), in_shape.width - 1);
+				*dest++ = y_origin[in_x];
+			}
+		}
+	}
 }
 
 static void kpu_logistic(const kpu_model_logistic_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
-    float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
-    size_t oc, channels = arg->channels;
-
-    for(oc = 0; oc < channels; oc++)
-        dest[oc] = 1.f / (1.f + expf(-src[oc]));
+	const float *src = (const float *)(ctx->main_buffer + arg->main_mem_in_address);
+	float *dest = (float *)(ctx->main_buffer + arg->main_mem_out_address);
+	size_t oc, channels = arg->channels;
+
+	for (oc = 0; oc < channels; oc++)
+		dest[oc] = 1.f / (1.f + expf(-src[oc]));
 }
 
 static void kpu_conv(const kpu_model_conv_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    volatile kpu_layer_argument_t layer = *(const volatile kpu_layer_argument_t *)(ctx->model_buffer + arg->layer_offset);
-    layer.kernel_load_cfg.data.para_start_addr = (uintptr_t)(ctx->model_buffer + arg->weights_offset) - IOMEM;
-    layer.kernel_pool_type_cfg.data.bwsx_base_addr = (uintptr_t)(ctx->model_buffer + arg->bn_offset) - IOMEM;
-    layer.kernel_calc_type_cfg.data.active_addr = (uintptr_t)(ctx->model_buffer + arg->act_offset) - IOMEM;
-
-    if(arg->flags & KLF_MAIN_MEM_OUT)
-    {
-        dmac_channel_number_t dma_ch = ctx->dma_ch;
-        uint8_t *dest = ctx->main_buffer + arg->main_mem_out_address;
-        kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-            .calc_done_int = 1,
-            .layer_cfg_almost_empty_int = 1,
-            .layer_cfg_almost_full_int = 1};
-        kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-            .calc_done_int = 1,
-            .layer_cfg_almost_empty_int = 1,
-            .layer_cfg_almost_full_int = 1};
-        layer.dma_parameter.data.send_data_out = 1;
-        select_dma_channel(dma_ch, DMA_SELECT_AI_RX_REQ);
-        if(ctx->current_layer < ctx->layers_length)
-            dmac_set_irq(dma_ch, ai_step, ctx, 1);
-        else
-            dmac_set_irq(dma_ch, (plic_irq_callback_t)kpu_kmodel_done, ctx, 1);
-        dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                            DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (layer.dma_parameter.data.dma_total_byte + 8) / 8);
-    } else
-    {
-        kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-            .calc_done_int = 1,
-            .layer_cfg_almost_empty_int = 1,
-            .layer_cfg_almost_full_int = 1};
-
-        kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-            .calc_done_int = 0,
-            .layer_cfg_almost_empty_int = 1,
-            .layer_cfg_almost_full_int = 1};
-        layer.interrupt_enabe.data.int_en = 1;
-    }
-
-    kpu_send_layer((const kpu_layer_argument_t *)&layer);
+	volatile kpu_layer_argument_t layer = *(const volatile kpu_layer_argument_t *)(ctx->model_buffer + arg->layer_offset);
+	layer.kernel_load_cfg.data.para_start_addr = (uintptr_t)(ctx->model_buffer + arg->weights_offset) - IOMEM;
+	layer.kernel_pool_type_cfg.data.bwsx_base_addr = (uintptr_t)(ctx->model_buffer + arg->bn_offset) - IOMEM;
+	layer.kernel_calc_type_cfg.data.active_addr = (uintptr_t)(ctx->model_buffer + arg->act_offset) - IOMEM;
+
+	if (arg->flags & KLF_MAIN_MEM_OUT)
+	{
+		dmac_channel_number_t dma_ch = ctx->dma_ch;
+		uint8_t *dest = ctx->main_buffer + arg->main_mem_out_address;
+		kpu->interrupt_clear.data = (kpu_config_interrupt_t){
+			.calc_done_int = 1,
+			.layer_cfg_almost_empty_int = 1,
+			.layer_cfg_almost_full_int = 1};
+		kpu->interrupt_mask.data = (kpu_config_interrupt_t){
+			.calc_done_int = 1,
+			.layer_cfg_almost_empty_int = 1,
+			.layer_cfg_almost_full_int = 1};
+		layer.dma_parameter.data.send_data_out = 1;
+		select_dma_channel(dma_ch, DMA_SELECT_AI_RX_REQ);
+		if (ctx->current_layer < ctx->layers_length)
+			dmac_set_irq(dma_ch, ai_step, ctx, 1);
+		else
+			dmac_set_irq(dma_ch, (plic_irq_callback_t)kpu_kmodel_done, ctx, 1);
+		dmac_set_single_mode(dma_ch, (void *)(&kpu->fifo_data_out), dest, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
+							 DMAC_MSIZE_8, DMAC_TRANS_WIDTH_64, (layer.dma_parameter.data.dma_total_byte + 8) / 8);
+	}
+	else
+	{
+		kpu->interrupt_clear.data = (kpu_config_interrupt_t){
+			.calc_done_int = 1,
+			.layer_cfg_almost_empty_int = 1,
+			.layer_cfg_almost_full_int = 1};
+
+		kpu->interrupt_mask.data = (kpu_config_interrupt_t){
+			.calc_done_int = 0,
+			.layer_cfg_almost_empty_int = 1,
+			.layer_cfg_almost_full_int = 1};
+		layer.interrupt_enabe.data.int_en = 1;
+	}
+
+	kpu_send_layer((const kpu_layer_argument_t *)&layer);
 }
 
 static void kpu_add_padding(const kpu_model_add_padding_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
 #if USE_CACHED_AI_RAM
-    uint8_t *dest = (uint8_t *)(uintptr_t)(AI_RAM_BASE_ADDR + arg->kpu_mem_out_address * 64);
+	uint8_t *dest = (uint8_t *)(uintptr_t)(AI_RAM_BASE_ADDR + arg->kpu_mem_out_address * 64);
 #else
-    uint8_t *dest = (uint8_t *)(uintptr_t)(AI_IO_BASE_ADDR + arg->kpu_mem_out_address * 64);
+	uint8_t *dest = (uint8_t *)(uintptr_t)(AI_IO_BASE_ADDR + arg->kpu_mem_out_address * 64);
 #endif
 
-    uint32_t row_padding = 16;
-    uint32_t row_group = 4;
-    uint32_t row_length = 1;
-    uint32_t height = 4;
-    uint32_t oc, x, y, channels = arg->channels;
-
-    for(oc = 0; oc < channels; oc++)
-    {
-        uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
-        for(y = 0; y < 1; y++)
-        {
-            uint8_t *y_origin = channel_origin + y * row_length * 64;
-            for(x = 0; x < 1; x++)
-                y_origin[x] = *src++;
-        }
-    }
+	uint32_t row_padding = 16;
+	uint32_t row_group = 4;
+	uint32_t row_length = 1;
+	uint32_t height = 4;
+	uint32_t oc, x, y, channels = arg->channels;
+
+	for (oc = 0; oc < channels; oc++)
+	{
+		uint8_t *channel_origin = dest + oc / row_group * row_length * height * 64 + oc % row_group * row_padding;
+		for (y = 0; y < 1; y++)
+		{
+			uint8_t *y_origin = channel_origin + y * row_length * 64;
+			for (x = 0; x < 1; x++)
+				y_origin[x] = *src++;
+		}
+	}
 
 #if USE_CACHED_AI_RAM
-    uint32_t lines = row_length * height * channels / row_group;
-    kpu_flush_cache(arg->kpu_mem_out_address, lines);
+	uint32_t lines = row_length * height * channels / row_group;
+	kpu_flush_cache(arg->kpu_mem_out_address, lines);
 #endif
 }
@@ -1519,19 +1059,19 @@
 static void kpu_remove_padding(const kpu_model_remove_padding_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
-    uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
-    uint32_t oc, channels = arg->channels;
-
-    for(oc = 0; oc < channels; oc++)
-        *dest++ = src[oc * 16];
+	const uint8_t *src = (const uint8_t *)(ctx->main_buffer + arg->main_mem_in_address);
+	uint8_t *dest = (uint8_t *)(ctx->main_buffer + arg->main_mem_out_address);
+	uint32_t oc, channels = arg->channels;
+
+	for (oc = 0; oc < channels; oc++)
+		*dest++ = src[oc * 16];
 }
 
 static void kpu_upload(const kpu_model_upload_layer_argument_t *arg, kpu_model_context_t *ctx)
 {
-    size_t width = arg->width;
-    size_t height = arg->height;
-    size_t channels = arg->channels;
-
-    kpu_upload_core(width, height, channels, ctx->main_buffer + arg->main_mem_in_address, arg->kpu_mem_out_address);
+	size_t width = arg->width;
+	size_t height = arg->height;
+	size_t channels = arg->channels;
+
+	kpu_upload_core(width, height, channels, ctx->main_buffer + arg->main_mem_in_address, arg->kpu_mem_out_address);
 }
 
@@ -1539,64 +1079,57 @@
 {
 #if FIX_CACHE
-    configASSERT(is_memory_cache((uintptr_t)buffer));
+	configASSERT(is_memory_cache((uintptr_t)buffer));
 #endif
-    uintptr_t base_addr = (uintptr_t)buffer;
-    const kpu_kmodel_header_t *header = (const kpu_kmodel_header_t *)buffer;
-
-    if (header->version == 3 && header->arch == 0)
-    {
-        ctx->is_nncase = 0;
-        ctx->model_buffer = buffer;
-        ctx->output_count = header->output_count;
-        ctx->outputs = (const kpu_model_output_t *)(base_addr + sizeof(kpu_kmodel_header_t));
-        ctx->layer_headers = (const kpu_model_layer_header_t *)((uintptr_t)ctx->outputs + sizeof(kpu_model_output_t) * ctx->output_count);
-        ctx->layers_length = header->layers_length;
-        ctx->body_start = (const uint8_t *)((uintptr_t)ctx->layer_headers + sizeof(kpu_model_layer_header_t) * header->layers_length);
-        ctx->main_buffer = (uint8_t *)malloc(header->main_mem_usage);
-        if (!ctx->main_buffer)
-            return -1;
-        uint32_t body_size = 0;
-        for (int i=0; i<ctx->layers_length; i++)
-        {
-            const kpu_model_layer_header_t *cnt_layer_header = ctx->layer_headers + i;
-            body_size += cnt_layer_header->body_size;
-        }
-        uint8_t *body_start_iomem = (uint8_t *)((uintptr_t)ctx->body_start - IOMEM);
-        const uint8_t *body_start_cache = ctx->body_start;
-        memcpy(body_start_iomem, body_start_cache, body_size);
-        for (int i=0; i<body_size; i++)
-        {
-            configASSERT(body_start_iomem[i] == body_start_cache[i]);
-        }
-        
-    } else
-    {
-        return -1;
-    }
-
-    return 0;
+	uintptr_t base_addr = (uintptr_t)buffer;
+	const kpu_kmodel_header_t *header = (const kpu_kmodel_header_t *)buffer;
+
+	if (header->version == 3 && header->arch == 0)
+	{
+		ctx->model_buffer = buffer;
+		ctx->output_count = header->output_count;
+		ctx->outputs = (const kpu_model_output_t *)(base_addr + sizeof(kpu_kmodel_header_t));
+		ctx->layer_headers = (const kpu_model_layer_header_t *)((uintptr_t)ctx->outputs + sizeof(kpu_model_output_t) * ctx->output_count);
+		ctx->layers_length = header->layers_length;
+		ctx->body_start = (const uint8_t *)((uintptr_t)ctx->layer_headers + sizeof(kpu_model_layer_header_t) * header->layers_length);
+		ctx->main_buffer = (uint8_t *)malloc(header->main_mem_usage);
+		if (!ctx->main_buffer)
+			return -1;
+		uint32_t body_size = 0;
+		for (int i = 0; i < ctx->layers_length; i++)
+		{
+			const kpu_model_layer_header_t *cnt_layer_header = ctx->layer_headers + i;
+			body_size += cnt_layer_header->body_size;
+		}
+		uint8_t *body_start_iomem = (uint8_t *)((uintptr_t)ctx->body_start - IOMEM);
+		const uint8_t *body_start_cache = ctx->body_start;
+		memcpy(body_start_iomem, body_start_cache, body_size);
+		for (int i = 0; i < body_size; i++)
+		{
+			configASSERT(body_start_iomem[i] == body_start_cache[i]);
+		}
+	}
+	else
+	{
+		return -1;
+	}
+
+	return 0;
 }
 
 int kpu_get_output(kpu_model_context_t *ctx, uint32_t index, uint8_t **data, size_t *size)
 {
-    if(ctx->is_nncase)
-        return -1;
-
-    if(index >= ctx->output_count)
-        return -1;
-
-    const kpu_model_output_t *output = ctx->outputs + index;
-    *data = ctx->main_buffer + output->address;
-    *size = output->size;
-    return 0;
+	if (index >= ctx->output_count)
+		return -1;
+
+	const kpu_model_output_t *output = ctx->outputs + index;
+	*data = ctx->main_buffer + output->address;
+	*size = output->size;
+	return 0;
 }
 
 void kpu_model_free(kpu_model_context_t *ctx)
 {
-    if(ctx->is_nncase)
-        return;
-
-    free(ctx->main_buffer);
-    ctx->main_buffer = NULL;
+	free(ctx->main_buffer);
+	ctx->main_buffer = NULL;
 }
 
@@ -1609,53 +1142,53 @@
 static const char *str_layer_type(uint32_t type)
 {
-    switch(type)
-    {
-        case KL_ADD:
-            return "Add";
-        case KL_QUANTIZED_ADD:
-            return "QuantAdd";
-        case KL_GLOBAL_AVERAGE_POOL2D:
-            return "GAP";
-        case KL_QUANTIZED_MAX_POOL2D:
-            return "QuantMaxPool2d";
-        case KL_AVERAGE_POOL2D:
-            return "AveragePool2d";
-        case KL_QUANTIZE:
-            return "Quantize";
-        case KL_DEQUANTIZE:
-            return "Dequantize";
-        case KL_REQUANTIZE:
-            return "Requantize";
-        case KL_L2_NORMALIZATION:
-            return "L2Norm";
-        case KL_SOFTMAX:
-            return "Softmax";
-        case KL_CONCAT:
-            return "Concat";
-        case KL_QUANTIZED_CONCAT:
-            return "QuantConcat";
-        case KL_FULLY_CONNECTED:
-            return "FullyConnected";
-        case KL_TENSORFLOW_FLATTEN:
-            return "TFFlatten";
-        case KL_RESIZE_NEAREST_NEIGHBOR:
-            return "ResizeNearestNeighbor";
-        case KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR:
-            return "QuantResizeNearestNeighbor";
-        case KL_CHANNELWISE_DEQUANTIZE:
-            return "ChannelwiseDequantize";
-        case KL_LOGISTIC:
-            return "Logistic";
-        case KL_K210_CONV:
-            return "K210Conv";
-        case KL_K210_ADD_PADDING:
-            return "K210AddPad";
-        case KL_K210_REMOVE_PADDING:
-            return "K210RemovePad";
-        case KL_K210_UPLOAD:
-            return "K210Upload";
-        default:
-            return "Unknown";
-    }
+	switch (type)
+	{
+	case KL_ADD:
+		return "Add";
+	case KL_QUANTIZED_ADD:
+		return "QuantAdd";
+	case KL_GLOBAL_AVERAGE_POOL2D:
+		return "GAP";
+	case KL_QUANTIZED_MAX_POOL2D:
+		return "QuantMaxPool2d";
+	case KL_AVERAGE_POOL2D:
+		return "AveragePool2d";
+	case KL_QUANTIZE:
+		return "Quantize";
+	case KL_DEQUANTIZE:
+		return "Dequantize";
+	case KL_REQUANTIZE:
+		return "Requantize";
+	case KL_L2_NORMALIZATION:
+		return "L2Norm";
+	case KL_SOFTMAX:
+		return "Softmax";
+	case KL_CONCAT:
+		return "Concat";
+	case KL_QUANTIZED_CONCAT:
+		return "QuantConcat";
+	case KL_FULLY_CONNECTED:
+		return "FullyConnected";
+	case KL_TENSORFLOW_FLATTEN:
+		return "TFFlatten";
+	case KL_RESIZE_NEAREST_NEIGHBOR:
+		return "ResizeNearestNeighbor";
+	case KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR:
+		return "QuantResizeNearestNeighbor";
+	case KL_CHANNELWISE_DEQUANTIZE:
+		return "ChannelwiseDequantize";
+	case KL_LOGISTIC:
+		return "Logistic";
+	case KL_K210_CONV:
+		return "K210Conv";
+	case KL_K210_ADD_PADDING:
+		return "K210AddPad";
+	case KL_K210_REMOVE_PADDING:
+		return "K210RemovePad";
+	case KL_K210_UPLOAD:
+		return "K210Upload";
+	default:
+		return "Unknown";
+	}
 }
 #endif
@@ -1663,210 +1196,241 @@
 static int kpu_kmodel_done(kpu_model_context_t *ctx)
 {
-    kpu->interrupt_clear.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 1,
-        .layer_cfg_almost_full_int = 1};
+	kpu->interrupt_clear.data = (kpu_config_interrupt_t){
+		.calc_done_int = 1,
+		.layer_cfg_almost_empty_int = 1,
+		.layer_cfg_almost_full_int = 1};
+	kpu->interrupt_mask.data = (kpu_config_interrupt_t){
+		.calc_done_int = 1,
+		.layer_cfg_almost_empty_int = 1,
+		.layer_cfg_almost_full_int = 1};
 #if KPU_DEBUG
-    uint32_t cnt_layer_id = ctx->current_layer - 1;
-    uint64_t time = sysctl_get_time_us();
-    if(last_time != 0)
-    {
-        uint64_t layer_time = time - last_time;
-        syslog(LOG_NOTICE, "layer %d [%s]: %f ms", cnt_layer_id, str_layer_type(last_layer_type), layer_time / 1000.0);
-        total_time += layer_time;
-        if(last_layer_type == KL_K210_CONV)
-            kpu_time += layer_time;
-    }
-
-    syslog(LOG_NOTICE, "KPU: %f ms", kpu_time / 1000.0);
-    syslog(LOG_NOTICE, "CPU: %f ms", (total_time - kpu_time) / 1000.0);
-    syslog(LOG_NOTICE, "Model: %f ms", total_time / 1000.0);
+	uint32_t cnt_layer_id = ctx->current_layer;
+	uint64_t time = sysctl_get_time_us();
+	if (last_time != 0)
+	{
+		uint64_t layer_time = time - last_time;
+		syslog(LOG_NOTICE, "layer %d/%d [%s]: %d.%03d ms", cnt_layer_id, ctx->layers_length, str_layer_type(last_layer_type), layer_time / 1000, layer_time % 1000);
+		total_time += layer_time;
+		if (last_layer_type == KL_K210_CONV)
+			kpu_time += layer_time;
+	}
+
+	syslog(LOG_NOTICE, "KPU: %d.%03d ms", kpu_time / 1000, kpu_time % 1000);
+	syslog(LOG_NOTICE, "CPU: %d.%03d ms", (total_time - kpu_time) / 1000, (total_time - kpu_time) % 1000);
+	syslog(LOG_NOTICE, "Model: %d.%03d ms", total_time / 1000, total_time % 1000);
 #endif
-    ctx->done_callback(ctx->userdata);
-    return 0;
+	ctx->done_callback(ctx->userdata);
+	return 0;
 }
 
 static int ai_step(void *userdata)
 {
-    kpu_model_context_t *ctx = (kpu_model_context_t *)userdata;
-
-    uint32_t cnt_layer_id = ctx->current_layer;
-    const uint8_t *layer_body = ctx->current_body;
-    const kpu_model_layer_header_t *cnt_layer_header = ctx->layer_headers + cnt_layer_id;
-    if (cnt_layer_id >= ctx->layers_length) {
-        //syslog(LOG_NOTICE, "overrun");
-        kpu_kmodel_done(ctx);
-        return -1;
-    }
-
-    ctx->current_layer++;
-    ctx->current_body += cnt_layer_header->body_size;
+	kpu_model_context_t *ctx = (kpu_model_context_t *)userdata;
+
+	uint32_t cnt_layer_id = ctx->current_layer;
+	const uint8_t *layer_body = ctx->current_body;
+	const kpu_model_layer_header_t *cnt_layer_header = ctx->layer_headers + cnt_layer_id;
+	if (cnt_layer_id >= ctx->layers_length)
+	{
+		//syslog(LOG_NOTICE, "overrun");
+		kpu_kmodel_done(ctx);
+		return -1;
+	}
+
+	ctx->current_layer++;
+	ctx->current_body += cnt_layer_header->body_size;
 
 #if KPU_DEBUG
-    uint64_t time = sysctl_get_time_us();
-    if(last_time != 0)
-    {
-        uint64_t layer_time = time - last_time;
-        syslog(LOG_NOTICE, "layer %d/%d [%s]: %d.%03d ms", cnt_layer_id, ctx->layers_length, str_layer_type(last_layer_type), layer_time / 1000, layer_time % 1000);
-        total_time += layer_time;
-        if(last_layer_type == KL_K210_CONV)
-            kpu_time += layer_time;
-    }
-
-    last_layer_type = cnt_layer_header->type;
-    last_time = sysctl_get_time_us();
+	uint64_t time = sysctl_get_time_us();
+	if (last_time != 0)
+	{
+		uint64_t layer_time = time - last_time;
+		syslog(LOG_NOTICE, "layer %d/%d [%s]: %d.%03d ms", cnt_layer_id, ctx->layers_length, str_layer_type(last_layer_type), layer_time / 1000, layer_time % 1000);
+		total_time += layer_time;
+		if (last_layer_type == KL_K210_CONV)
+			kpu_time += layer_time;
+	}
+
+	last_layer_type = cnt_layer_header->type;
+	last_time = sysctl_get_time_us();
 #endif
 
-    switch(cnt_layer_header->type)
-    {
-        case KL_ADD:
-            kpu_kmodel_add((const kpu_model_add_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_QUANTIZED_ADD:
-            kpu_quantized_add((const kpu_model_quant_add_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_GLOBAL_AVERAGE_POOL2D:
-            kpu_global_average_pool2d((const kpu_model_gap2d_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_QUANTIZED_MAX_POOL2D:
-            kpu_quantized_max_pool2d((const kpu_model_quant_max_pool2d_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_AVERAGE_POOL2D:
-            kpu_average_pool2d((const kpu_model_ave_pool2d_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_QUANTIZE:
-            kpu_quantize((const kpu_model_quantize_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_DEQUANTIZE:
-            kpu_kmodel_dequantize((const kpu_model_dequantize_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_REQUANTIZE:
-            kpu_requantize((const kpu_model_requantize_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_L2_NORMALIZATION:
-            kpu_l2_normalization((const kpu_model_l2_norm_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_SOFTMAX:
-            kpu_softmax((const kpu_model_softmax_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_CONCAT:
-        case KL_QUANTIZED_CONCAT:
-            kpu_concat((const kpu_model_concat_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_FULLY_CONNECTED:
-            kpu_kmodel_fully_connected((const kpu_model_fully_connected_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_TENSORFLOW_FLATTEN:
-            kpu_tf_flatten((const kpu_model_tf_flatten_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_RESIZE_NEAREST_NEIGHBOR:
-            kpu_resize_nearest_neighbor((const kpu_model_resize_nearest_neighbor_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR:
-            kpu_quant_resize_nearest_neighbor((const kpu_model_quant_resize_nearest_neighbor_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_CHANNELWISE_DEQUANTIZE:
-            kpu_kmodel_channelwise_dequantize((const kpu_model_channelwise_dequant_argument_t *)layer_body, ctx);
-            break;
-        case KL_LOGISTIC:
-            kpu_logistic((const kpu_model_logistic_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_K210_CONV:
-            kpu_conv((const kpu_model_conv_layer_argument_t *)layer_body, ctx);
-            return 0;
-        case KL_K210_ADD_PADDING:
-            kpu_add_padding((const kpu_model_add_padding_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_K210_REMOVE_PADDING:
-            kpu_remove_padding((const kpu_model_remove_padding_layer_argument_t *)layer_body, ctx);
-            break;
-        case KL_K210_UPLOAD:
-            kpu_upload((const kpu_model_upload_layer_argument_t *)layer_body, ctx);
-            break;
-        default:
-            assert(!"Layer is not supported.");
-            kpu_kmodel_done(ctx);
-            return -1;
-    }
-
-    if (ctx->current_layer < ctx->layers_length)
-        ai_step(userdata);
-    else
-        kpu_kmodel_done(ctx);
-    return 0;
+	switch (cnt_layer_header->type)
+	{
+	case KL_ADD:
+		kpu_kmodel_add((const kpu_model_add_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_QUANTIZED_ADD:
+		kpu_quantized_add((const kpu_model_quant_add_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_GLOBAL_AVERAGE_POOL2D:
+		kpu_global_average_pool2d((const kpu_model_gap2d_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_QUANTIZED_MAX_POOL2D:
+		kpu_quantized_max_pool2d((const kpu_model_quant_max_pool2d_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_AVERAGE_POOL2D:
+		kpu_average_pool2d((const kpu_model_ave_pool2d_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_QUANTIZE:
+		kpu_quantize((const kpu_model_quantize_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_DEQUANTIZE:
+		kpu_kmodel_dequantize((const kpu_model_dequantize_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_REQUANTIZE:
+		kpu_requantize((const kpu_model_requantize_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_L2_NORMALIZATION:
+		kpu_l2_normalization((const kpu_model_l2_norm_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_SOFTMAX:
+		kpu_softmax((const kpu_model_softmax_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_CONCAT:
+	case KL_QUANTIZED_CONCAT:
+		kpu_concat((const kpu_model_concat_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_FULLY_CONNECTED:
+		kpu_kmodel_fully_connected((const kpu_model_fully_connected_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_TENSORFLOW_FLATTEN:
+		kpu_tf_flatten((const kpu_model_tf_flatten_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_RESIZE_NEAREST_NEIGHBOR:
+		kpu_resize_nearest_neighbor((const kpu_model_resize_nearest_neighbor_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR:
+		kpu_quant_resize_nearest_neighbor((const kpu_model_quant_resize_nearest_neighbor_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_CHANNELWISE_DEQUANTIZE:
+		kpu_kmodel_channelwise_dequantize((const kpu_model_channelwise_dequant_argument_t *)layer_body, ctx);
+		break;
+	case KL_LOGISTIC:
+		kpu_logistic((const kpu_model_logistic_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_K210_CONV:
+		kpu_conv((const kpu_model_conv_layer_argument_t *)layer_body, ctx);
+		return 0;
+	case KL_K210_ADD_PADDING:
+		kpu_add_padding((const kpu_model_add_padding_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_K210_REMOVE_PADDING:
+		kpu_remove_padding((const kpu_model_remove_padding_layer_argument_t *)layer_body, ctx);
+		break;
+	case KL_K210_UPLOAD:
+		kpu_upload((const kpu_model_upload_layer_argument_t *)layer_body, ctx);
+		break;
+	default:
+		assert(!"Layer is not supported.");
+		kpu_kmodel_done(ctx);
+		return -1;
+	}
+
+	if (ctx->current_layer < (ctx->layers_length - 1))
+		ai_step(userdata);
+	else
+		kpu_kmodel_done(ctx);
+	return 0;
 }
 
 static void ai_step_not_isr(void *userdata)
 {
-    sysctl_disable_irq();
-    ai_step(userdata);
-    sysctl_enable_irq();
+	dis_int(INTNO_DMAAI);
+	dis_int(INTNO_AI);
+
+	ai_step(userdata);
+
+	ena_int(INTNO_DMAAI);
+	ena_int(INTNO_AI);
 }
 
 int kpu_run_kmodel(kpu_model_context_t *ctx, const uint8_t *src, dmac_channel_number_t dma_ch, kpu_done_callback_t done_callback, void *userdata)
 {
-    if(ctx->is_nncase)
-        return -1;
-
-    ctx->dma_ch = dma_ch;
-    ctx->done_callback = done_callback;
-    ctx->userdata = userdata;
-    ctx->current_layer = 0;
-    ctx->current_body = ctx->body_start;
+	ctx->dma_ch = dma_ch;
+	ctx->done_callback = done_callback;
+	ctx->userdata = userdata;
+	ctx->current_layer = 0;
+	ctx->current_body = ctx->body_start;
 #if KPU_DEBUG
-    last_time = 0;
-    total_time = 0;
-    kpu_time = 0;
+	last_time = 0;
+	total_time = 0;
+	kpu_time = 0;
 #endif
 
-    kpu_kmodel_header_t *header = (kpu_kmodel_header_t *)ctx->model_buffer;
-    kpu->interrupt_clear.reg = 7;
-    kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t){
-        .fifo_full_threshold = 10, .fifo_empty_threshold = 1};
-    kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t){
-        .eight_bit_mode = header->flags & 1};
-    kpu->interrupt_mask.data = (kpu_config_interrupt_t){
-        .calc_done_int = 1,
-        .layer_cfg_almost_empty_int = 0,
-        .layer_cfg_almost_full_int = 1};
-
-    plic_set_priority(INTNO_AI, 1);
-    plic_irq_register(INTNO_AI, ai_step, ctx);
-    plic_irq_enable(INTNO_AI);
-
-    const kpu_model_layer_header_t *first_layer_header = ctx->layer_headers;
-
-    switch(first_layer_header->type)
-    {
-        case KL_K210_CONV:
-        {
-            const kpu_model_conv_layer_argument_t *first_layer = (const kpu_model_conv_layer_argument_t *)ctx->body_start;
-            kpu_layer_argument_t layer_arg = *(volatile kpu_layer_argument_t *)(ctx->model_buffer + first_layer->layer_offset);
-
-            if((layer_arg.image_size.data.i_row_wid + 1) % 64 != 0)
-            {
-                kpu_kmodel_input_with_padding(&layer_arg, src);
-                ai_step_not_isr(ctx);
-            } else
-            {
-                kpu_input_dma(&layer_arg, src, ctx->dma_ch, ai_step, ctx);
-            }
-        }
-        break;
-        case KL_FULLY_CONNECTED:
-        {
-            const kpu_model_fully_connected_layer_argument_t *first_layer = (const kpu_model_fully_connected_layer_argument_t *)ctx->body_start;
-            kpu_kmodel_input_float((const float *)src, (float *)(ctx->main_buffer + first_layer->main_mem_in_address), first_layer->in_channels);
-            ai_step_not_isr(ctx);
-        }
-        break;
-        default:
-            return -1;
-    }
-
-    return 0;
-}
+	kpu_kmodel_header_t *header = (kpu_kmodel_header_t *)ctx->model_buffer;
+	kpu->interrupt_clear.reg = 7;
+	kpu->fifo_threshold.data = (kpu_config_fifo_threshold_t){
+		.fifo_full_threshold = 10, .fifo_empty_threshold = 1};
+	kpu->eight_bit_mode.data = (kpu_config_eight_bit_mode_t){
+		.eight_bit_mode = header->flags & 1};
+	kpu->interrupt_mask.data = (kpu_config_interrupt_t){
+		.calc_done_int = 1,
+		.layer_cfg_almost_empty_int = 0,
+		.layer_cfg_almost_full_int = 1};
+
+	//plic_set_priority(INTNO_AI, 1);
+	plic_irq_register(INTNO_AI, ai_step, ctx);
+	plic_irq_enable(INTNO_AI);
+
+	const kpu_model_layer_header_t *first_layer_header = ctx->layer_headers;
+
+	switch (first_layer_header->type)
+	{
+	case KL_K210_CONV:
+	{
+		const kpu_model_conv_layer_argument_t *first_layer = (const kpu_model_conv_layer_argument_t *)ctx->body_start;
+		kpu_layer_argument_t layer_arg = *(volatile kpu_layer_argument_t *)(ctx->model_buffer + first_layer->layer_offset);
+
+		if ((layer_arg.image_size.data.i_row_wid + 1) % 64 != 0)
+		{
+			kpu_kmodel_input_with_padding(&layer_arg, src);
+			ai_step_not_isr(ctx);
+		}
+		else
+		{
+			kpu_input_dma(&layer_arg, src, ctx->dma_ch, ai_step, ctx);
+		}
+	}
+	break;
+	case KL_FULLY_CONNECTED:
+	{
+		const kpu_model_fully_connected_layer_argument_t *first_layer = (const kpu_model_fully_connected_layer_argument_t *)ctx->body_start;
+		kpu_kmodel_input_float((const float *)src, (float *)(ctx->main_buffer + first_layer->main_mem_in_address), first_layer->in_channels);
+		ai_step_not_isr(ctx);
+	}
+	break;
+	default:
+		return -1;
+	}
+
+	return 0;
+}
+
+ER kpu_init(kpu_model_context_t *ctx)
+{
+	g_ai_hdma.chnum = AI_DMA_CH;
+	g_ai_hdma.xfercallback = ai_dma_done_isr;
+	g_ai_hdma.errorcallback = NULL;
+	g_ai_hdma.Init.Request = DMA_SELECT_AI_RX_REQ;		/* DMA選択 */
+	g_ai_hdma.Init.Direction = DMA_PERIPH_TO_MEMORY;	/* DMA転送方向 */
+	g_ai_hdma.Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;	/* ソースマルチブロックタイプ */
+	g_ai_hdma.Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;	/* デスティネーションマルチブロックタイプ */
+	g_ai_hdma.Init.SrcHandShake = DMAC_HS_HARDWARE;		/* ソースハンドシェイク */
+	g_ai_hdma.Init.DrcHandShake = DMAC_HS_SOFTWARE;		/* デスティネーションハンドシェイク */
+	g_ai_hdma.Init.SrcHwhsPol = DMAC_HWHS_POLARITY_LOW; /* ソースハードウェアハンドシェイク極性 */
+	g_ai_hdma.Init.DrcHwhsPol = DMAC_HWHS_POLARITY_LOW; /* デスティネーションハードウェアハンドシェイク極性 */
+	g_ai_hdma.Init.Priority = 4;						/* 優先度 */
+	g_ai_hdma.Init.SrcMaster = DMAC_MASTER1;			/* ソースマスター設定 */
+	g_ai_hdma.Init.DstMaster = DMAC_MASTER2;			/* デスティネーションマスター設定 */
+	g_ai_hdma.Init.SrcInc = DMAC_ADDR_NOCHANGE;			/* ソースインクリメント設定 */
+	g_ai_hdma.Init.DstInc = DMAC_ADDR_INCREMENT;		/* デスティネーションインクリメント設定 */
+	g_ai_hdma.Init.SrcTransWidth = DMAC_TRANS_WIDTH_32; /* ソース転送幅 */
+	g_ai_hdma.Init.DstTransWidth = DMAC_TRANS_WIDTH_32; /* デスティネーション転送幅 */
+	g_ai_hdma.Init.SrcBurstSize = DMAC_MSIZE_4;			/* ソースバーストサイズ */
+	g_ai_hdma.Init.DstBurstSize = DMAC_MSIZE_4;			/* デスティネーションバーストサイズ */
+	g_ai_hdma.Init.IocBlkTrans = 0;						/* IOCブロック転送 */
+	g_ai_hdma.localdata = (void *)ctx;
+
+	return dma_init(&g_ai_hdma);
+}
Index: azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/kpu.h	(revision 458)
@@ -24,6 +24,6 @@
 #endif
 
-#define kpu_matmul_begin kpu_conv2d_output
 #define IOMEM 0x40000000
+#define dmac_channel_number_t int
 
 typedef int (*plic_irq_callback_t)(void *ctx);
@@ -31,638 +31,616 @@
 typedef struct
 {
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t int_en : 1;
-            uint64_t ram_flag : 1;
-            uint64_t full_add : 1;
-            uint64_t depth_wise_layer : 1;
-            uint64_t reserved : 60;
-        } data;
-    } interrupt_enabe;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t image_src_addr : 15;
-            uint64_t reserved0 : 17;
-            uint64_t image_dst_addr : 15;
-            uint64_t reserved1 : 17;
-        } data;
-    } image_addr;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t i_ch_num : 10;
-            uint64_t reserved0 : 22;
-            uint64_t o_ch_num : 10;
-            uint64_t reserved1 : 6;
-            uint64_t o_ch_num_coef : 10;
-            uint64_t reserved2 : 6;
-        } data;
-    } image_channel_num;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t i_row_wid : 10;
-            uint64_t i_col_high : 9;
-            uint64_t reserved0 : 13;
-            uint64_t o_row_wid : 10;
-            uint64_t o_col_high : 9;
-            uint64_t reserved1 : 13;
-        } data;
-    } image_size;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t kernel_type : 3;
-            uint64_t pad_type : 1;
-            uint64_t pool_type : 4;
-            uint64_t first_stride : 1;
-            uint64_t bypass_conv : 1;
-            uint64_t load_para : 1;
-            uint64_t reserved0 : 5;
-            uint64_t dma_burst_size : 8;
-            uint64_t pad_value : 8;
-            uint64_t bwsx_base_addr : 32;
-        } data;
-    } kernel_pool_type_cfg;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t load_coor : 1;
-            uint64_t load_time : 6;
-            uint64_t reserved0 : 8;
-            uint64_t para_size : 17;
-            uint64_t para_start_addr : 32;
-        } data;
-    } kernel_load_cfg;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t coef_column_offset : 4;
-            uint64_t coef_row_offset : 12;
-            uint64_t reserved0 : 48;
-        } data;
-    } kernel_offset;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t channel_switch_addr : 15;
-            uint64_t reserved : 1;
-            uint64_t row_switch_addr : 4;
-            uint64_t coef_size : 8;
-            uint64_t coef_group : 3;
-            uint64_t load_act : 1;
-            uint64_t active_addr : 32;
-        } data;
-    } kernel_calc_type_cfg;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t wb_channel_switch_addr : 15;
-            uint64_t reserved0 : 1;
-            uint64_t wb_row_switch_addr : 4;
-            uint64_t wb_group : 3;
-            uint64_t reserved1 : 41;
-        } data;
-    } write_back_cfg;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t shr_w : 4;
-            uint64_t shr_x : 4;
-            uint64_t arg_w : 24;
-            uint64_t arg_x : 24;
-            uint64_t reserved0 : 8;
-        } data;
-    } conv_value;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t arg_add : 40;
-            uint64_t reserved : 24;
-        } data;
-    } conv_value2;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t send_data_out : 1;
-            uint64_t reserved : 15;
-            uint64_t channel_byte_num : 16;
-            uint64_t dma_total_byte : 32;
-        } data;
-    } dma_parameter;
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t int_en : 1;
+			uint64_t ram_flag : 1;
+			uint64_t full_add : 1;
+			uint64_t depth_wise_layer : 1;
+			uint64_t reserved : 60;
+		} data;
+	} interrupt_enabe;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t image_src_addr : 15;
+			uint64_t reserved0 : 17;
+			uint64_t image_dst_addr : 15;
+			uint64_t reserved1 : 17;
+		} data;
+	} image_addr;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t i_ch_num : 10;
+			uint64_t reserved0 : 22;
+			uint64_t o_ch_num : 10;
+			uint64_t reserved1 : 6;
+			uint64_t o_ch_num_coef : 10;
+			uint64_t reserved2 : 6;
+		} data;
+	} image_channel_num;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t i_row_wid : 10;
+			uint64_t i_col_high : 9;
+			uint64_t reserved0 : 13;
+			uint64_t o_row_wid : 10;
+			uint64_t o_col_high : 9;
+			uint64_t reserved1 : 13;
+		} data;
+	} image_size;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t kernel_type : 3;
+			uint64_t pad_type : 1;
+			uint64_t pool_type : 4;
+			uint64_t first_stride : 1;
+			uint64_t bypass_conv : 1;
+			uint64_t load_para : 1;
+			uint64_t reserved0 : 5;
+			uint64_t dma_burst_size : 8;
+			uint64_t pad_value : 8;
+			uint64_t bwsx_base_addr : 32;
+		} data;
+	} kernel_pool_type_cfg;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t load_coor : 1;
+			uint64_t load_time : 6;
+			uint64_t reserved0 : 8;
+			uint64_t para_size : 17;
+			uint64_t para_start_addr : 32;
+		} data;
+	} kernel_load_cfg;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t coef_column_offset : 4;
+			uint64_t coef_row_offset : 12;
+			uint64_t reserved0 : 48;
+		} data;
+	} kernel_offset;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t channel_switch_addr : 15;
+			uint64_t reserved : 1;
+			uint64_t row_switch_addr : 4;
+			uint64_t coef_size : 8;
+			uint64_t coef_group : 3;
+			uint64_t load_act : 1;
+			uint64_t active_addr : 32;
+		} data;
+	} kernel_calc_type_cfg;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t wb_channel_switch_addr : 15;
+			uint64_t reserved0 : 1;
+			uint64_t wb_row_switch_addr : 4;
+			uint64_t wb_group : 3;
+			uint64_t reserved1 : 41;
+		} data;
+	} write_back_cfg;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t shr_w : 4;
+			uint64_t shr_x : 4;
+			uint64_t arg_w : 24;
+			uint64_t arg_x : 24;
+			uint64_t reserved0 : 8;
+		} data;
+	} conv_value;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t arg_add : 40;
+			uint64_t reserved : 24;
+		} data;
+	} conv_value2;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t send_data_out : 1;
+			uint64_t reserved : 15;
+			uint64_t channel_byte_num : 16;
+			uint64_t dma_total_byte : 32;
+		} data;
+	} dma_parameter;
 } kpu_layer_argument_t;
 
 typedef struct
 {
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t shift_number : 8;
-            uint64_t y_mul : 16;
-            uint64_t x_start : 36;
-        } data;
-    } activate_para[16];
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint8_t result_bias[8];
-        } data;
-    } activate_para_bias0;
-
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint8_t result_bias[8];
-        } data;
-    } activate_para_bias1;
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t shift_number : 8;
+			uint64_t y_mul : 16;
+			uint64_t x_start : 36;
+		} data;
+	} activate_para[16];
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint8_t result_bias[8];
+		} data;
+	} activate_para_bias0;
+
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint8_t result_bias[8];
+		} data;
+	} activate_para_bias1;
 } kpu_activate_table_t;
 
 typedef struct
 {
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint64_t norm_mul : 24;
-            uint64_t norm_add : 32;
-            uint64_t norm_shift : 4;
-        } data;
-    } batchnorm;
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint64_t norm_mul : 24;
+			uint64_t norm_add : 32;
+			uint64_t norm_shift : 4;
+		} data;
+	} batchnorm;
 } kpu_batchnorm_argument_t;
 
 typedef struct
 {
-    union
-    {
-        uint64_t reg;
-        struct
-        {
-            uint16_t weight[9];
-        } data;
-    } weights;
+	union
+	{
+		uint64_t reg;
+		struct
+		{
+			uint16_t weight[9];
+		} data;
+	} weights;
 } kpu_weights_kernel_16_3x3_t;
 
 typedef struct
 {
-    uint64_t calc_done_int : 1;
-    uint64_t layer_cfg_almost_empty_int : 1;
-    uint64_t layer_cfg_almost_full_int : 1;
-    uint64_t reserved : 61;
+	uint64_t calc_done_int : 1;
+	uint64_t layer_cfg_almost_empty_int : 1;
+	uint64_t layer_cfg_almost_full_int : 1;
+	uint64_t reserved : 61;
 } kpu_config_interrupt_t;
 
 typedef struct
 {
-    uint64_t fifo_full_threshold : 4;
-    uint64_t fifo_empty_threshold : 4;
-    uint64_t reserved : 56;
+	uint64_t fifo_full_threshold : 4;
+	uint64_t fifo_empty_threshold : 4;
+	uint64_t reserved : 56;
 } kpu_config_fifo_threshold_t;
 
 typedef struct
 {
-    uint64_t dma_fifo_flush_n : 1;
-    uint64_t gs_fifo_flush_n : 1;
-    uint64_t cfg_fifo_flush_n : 1;
-    uint64_t cmd_fifo_flush_n : 1;
-    uint64_t resp_fifo_flush_n : 1;
-    uint64_t reserved : 59;
+	uint64_t dma_fifo_flush_n : 1;
+	uint64_t gs_fifo_flush_n : 1;
+	uint64_t cfg_fifo_flush_n : 1;
+	uint64_t cmd_fifo_flush_n : 1;
+	uint64_t resp_fifo_flush_n : 1;
+	uint64_t reserved : 59;
 } kpu_config_fifo_ctrl_t;
 
 typedef struct
 {
-    uint64_t eight_bit_mode : 1;
-    uint64_t reserved : 63;
+	uint64_t eight_bit_mode : 1;
+	uint64_t reserved : 63;
 } kpu_config_eight_bit_mode_t;
 
 typedef struct
 {
-    volatile uint64_t layer_argument_fifo;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_interrupt_t data;
-    } interrupt_status;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_interrupt_t data;
-    } interrupt_raw;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_interrupt_t data;
-    } interrupt_mask;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_interrupt_t data;
-    } interrupt_clear;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_fifo_threshold_t data;
-    } fifo_threshold;
-
-    volatile uint64_t fifo_data_out;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_fifo_ctrl_t data;
-    } fifo_ctrl;
-
-    volatile union
-    {
-        uint64_t reg;
-        kpu_config_eight_bit_mode_t data;
-    } eight_bit_mode;
+	volatile uint64_t layer_argument_fifo;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_interrupt_t data;
+	} interrupt_status;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_interrupt_t data;
+	} interrupt_raw;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_interrupt_t data;
+	} interrupt_mask;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_interrupt_t data;
+	} interrupt_clear;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_fifo_threshold_t data;
+	} fifo_threshold;
+
+	volatile uint64_t fifo_data_out;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_fifo_ctrl_t data;
+	} fifo_ctrl;
+
+	volatile union
+	{
+		uint64_t reg;
+		kpu_config_eight_bit_mode_t data;
+	} eight_bit_mode;
 } kpu_config_t;
 
-#define dmac_channel_number_t int
-
-typedef struct
-{
-    kpu_layer_argument_t *layers;
-    kpu_layer_argument_t *remain_layers;
-    plic_irq_callback_t callback;
-    void *ctx;
-    uint64_t *src;
-    uint64_t *dst;
-    uint32_t src_length;
-    uint32_t dst_length;
-    uint32_t layers_length;
-    uint32_t remain_layers_length;
-    dmac_channel_number_t dma_ch;
-    uint32_t eight_bit_mode;
-    float output_scale;
-    float output_bias;
-    float input_scale;
-    float input_bias;
-} kpu_task_t;
-
-typedef struct
-{
-    uint32_t version;
-    uint32_t flags;
-    uint32_t arch;
-    uint32_t layers_length;
-    uint32_t max_start_address;
-    uint32_t main_mem_usage;
-    uint32_t output_count;
+typedef struct
+{
+	uint32_t version;
+	uint32_t flags;
+	uint32_t arch;
+	uint32_t layers_length;
+	uint32_t max_start_address;
+	uint32_t main_mem_usage;
+	uint32_t output_count;
 } kpu_kmodel_header_t;
 
 typedef struct
 {
-    uint32_t version;
-    uint32_t flags;
-    uint32_t layers_length;
-    uint32_t max_start_address;
-    uint32_t layers_argument_start;
+	uint32_t version;
+	uint32_t flags;
+	uint32_t layers_length;
+	uint32_t max_start_address;
+	uint32_t layers_argument_start;
 } kpu_model_header_t;
 
 typedef struct
 {
-    uint32_t address;
-    uint32_t size;
+	uint32_t address;
+	uint32_t size;
 } kpu_model_output_t;
 
 typedef enum
 {
-    KL_INVALID = 0,
-    KL_ADD,
-    KL_QUANTIZED_ADD,
-    KL_GLOBAL_MAX_POOL2D,
-    KL_QUANTIZED_GLOBAL_MAX_POOL2D,
-    KL_GLOBAL_AVERAGE_POOL2D,
-    KL_QUANTIZED_GLOBAL_AVERAGE_POOL2D,
-    KL_MAX_POOL2D,
-    KL_QUANTIZED_MAX_POOL2D,
-    KL_AVERAGE_POOL2D,
-    KL_QUANTIZED_AVERAGE_POOL2D,
-    KL_QUANTIZE,
-    KL_DEQUANTIZE,
-    KL_REQUANTIZE,
-    KL_L2_NORMALIZATION,
-    KL_SOFTMAX,
-    KL_CONCAT,
-    KL_QUANTIZED_CONCAT,
-    KL_FULLY_CONNECTED,
-    KL_QUANTIZED_FULLY_CONNECTED,
-    KL_TENSORFLOW_FLATTEN,
-    KL_QUANTIZED_TENSORFLOW_FLATTEN,
-    KL_RESIZE_NEAREST_NEIGHBOR,
-    KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR,
-    KL_CHANNELWISE_DEQUANTIZE,
-    KL_LOGISTIC,
-    KL_K210_CONV = 10240,
-    KL_K210_ADD_PADDING,
-    KL_K210_REMOVE_PADDING,
-    KL_K210_UPLOAD
+	KL_INVALID = 0,
+	KL_ADD,
+	KL_QUANTIZED_ADD,
+	KL_GLOBAL_MAX_POOL2D,
+	KL_QUANTIZED_GLOBAL_MAX_POOL2D,
+	KL_GLOBAL_AVERAGE_POOL2D,
+	KL_QUANTIZED_GLOBAL_AVERAGE_POOL2D,
+	KL_MAX_POOL2D,
+	KL_QUANTIZED_MAX_POOL2D,
+	KL_AVERAGE_POOL2D,
+	KL_QUANTIZED_AVERAGE_POOL2D,
+	KL_QUANTIZE,
+	KL_DEQUANTIZE,
+	KL_REQUANTIZE,
+	KL_L2_NORMALIZATION,
+	KL_SOFTMAX,
+	KL_CONCAT,
+	KL_QUANTIZED_CONCAT,
+	KL_FULLY_CONNECTED,
+	KL_QUANTIZED_FULLY_CONNECTED,
+	KL_TENSORFLOW_FLATTEN,
+	KL_QUANTIZED_TENSORFLOW_FLATTEN,
+	KL_RESIZE_NEAREST_NEIGHBOR,
+	KL_QUANTIZED_RESIZE_NEAREST_NEIGHBOR,
+	KL_CHANNELWISE_DEQUANTIZE,
+	KL_LOGISTIC,
+	KL_K210_CONV = 10240,
+	KL_K210_ADD_PADDING,
+	KL_K210_REMOVE_PADDING,
+	KL_K210_UPLOAD
 } kpu_model_layer_type_t;
 
 typedef struct
 {
-    uint32_t type;
-    uint32_t body_size;
+	uint32_t type;
+	uint32_t body_size;
 } kpu_model_layer_header_t;
 
 typedef enum
 {
-    KLF_NONE = 0,
-    KLF_MAIN_MEM_OUT = 1
+	KLF_NONE = 0,
+	KLF_MAIN_MEM_OUT = 1
 } kpu_model_layer_flags_t;
 
 typedef enum
 {
-    KLP_SAME = 0,
-    KLP_VALID = 1
+	KLP_SAME = 0,
+	KLP_VALID = 1
 } kpu_model_padding_t;
 
 typedef enum
 {
-    KLA_LINEAR = 0,
-    KLA_RELU = 1,
-    KLA_RELU6 = 2
+	KLA_LINEAR = 0,
+	KLA_RELU = 1,
+	KLA_RELU6 = 2
 } kpu_model_activation_t;
 
 typedef struct
 {
-    float scale;
-    float bias;
+	float scale;
+	float bias;
 } kpu_model_quant_param_t;
 
 typedef struct
 {
-    uint32_t width;
-    uint32_t height;
-    uint32_t channels;
+	uint32_t width;
+	uint32_t height;
+	uint32_t channels;
 } kpu_model_shape_t;
 
 typedef struct
 {
-    uint32_t start;
-    uint32_t size;
+	uint32_t start;
+	uint32_t size;
 } kpu_model_memory_range_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_out_address;
-    uint32_t layer_offset;
-    uint32_t weights_offset;
-    uint32_t bn_offset;
-    uint32_t act_offset;
+	uint32_t flags;
+	uint32_t main_mem_out_address;
+	uint32_t layer_offset;
+	uint32_t weights_offset;
+	uint32_t bn_offset;
+	uint32_t act_offset;
 } kpu_model_conv_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_a_address;
-    uint32_t main_mem_in_b_address;
-    uint32_t main_mem_out_address;
-    uint32_t count;
+	uint32_t flags;
+	uint32_t main_mem_in_a_address;
+	uint32_t main_mem_in_b_address;
+	uint32_t main_mem_out_address;
+	uint32_t count;
 } kpu_model_add_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_a_address;
-    uint32_t main_mem_in_b_address;
-    uint32_t main_mem_out_address;
-    uint32_t count;
-    int32_t in_a_offset;
-    int32_t in_a_mul;
-    int32_t in_a_shift;
-    int32_t in_b_offset;
-    int32_t in_b_mul;
-    int32_t in_b_shift;
-    int32_t out_offset;
-    int32_t out_mul;
-    int32_t out_shift;
+	uint32_t flags;
+	uint32_t main_mem_in_a_address;
+	uint32_t main_mem_in_b_address;
+	uint32_t main_mem_out_address;
+	uint32_t count;
+	int32_t in_a_offset;
+	int32_t in_a_mul;
+	int32_t in_a_shift;
+	int32_t in_b_offset;
+	int32_t in_b_mul;
+	int32_t in_b_shift;
+	int32_t out_offset;
+	int32_t out_mul;
+	int32_t out_shift;
 } kpu_model_quant_add_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t kernel_size;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t kernel_size;
+	uint32_t channels;
 } kpu_model_gap2d_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    kpu_model_shape_t in_shape;
-    kpu_model_shape_t out_shape;
-    uint32_t kernel_width;
-    uint32_t kernel_height;
-    uint32_t stride_width;
-    uint32_t stride_height;
-    uint32_t padding_width;
-    uint32_t padding_height;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	kpu_model_shape_t in_shape;
+	kpu_model_shape_t out_shape;
+	uint32_t kernel_width;
+	uint32_t kernel_height;
+	uint32_t stride_width;
+	uint32_t stride_height;
+	uint32_t padding_width;
+	uint32_t padding_height;
 } kpu_model_quant_max_pool2d_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    kpu_model_shape_t in_shape;
-    kpu_model_shape_t out_shape;
-    uint32_t kernel_width;
-    uint32_t kernel_height;
-    uint32_t stride_width;
-    uint32_t stride_height;
-    uint32_t padding_width;
-    uint32_t padding_height;
-    kpu_model_activation_t act;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	kpu_model_shape_t in_shape;
+	kpu_model_shape_t out_shape;
+	uint32_t kernel_width;
+	uint32_t kernel_height;
+	uint32_t stride_width;
+	uint32_t stride_height;
+	uint32_t padding_width;
+	uint32_t padding_height;
+	kpu_model_activation_t act;
 } kpu_model_ave_pool2d_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t mem_out_address;
-    uint32_t count;
-    kpu_model_quant_param_t quant_param;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t mem_out_address;
+	uint32_t count;
+	kpu_model_quant_param_t quant_param;
 } kpu_model_quantize_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t count;
-    kpu_model_quant_param_t quant_param;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t count;
+	kpu_model_quant_param_t quant_param;
 } kpu_model_dequantize_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t count;
-    uint8_t table[256];
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t count;
+	uint8_t table[256];
 } kpu_model_requantize_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t kpu_mem_out_address;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t kpu_mem_out_address;
+	uint32_t channels;
 } kpu_model_add_padding_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t channels;
 } kpu_model_remove_padding_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t kpu_mem_out_address;
-    uint32_t width;
-    uint32_t height;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t kpu_mem_out_address;
+	uint32_t width;
+	uint32_t height;
+	uint32_t channels;
 } kpu_model_upload_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t channels;
 } kpu_model_l2_norm_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t channels;
 } kpu_model_softmax_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_out_address;
-    uint32_t input_count;
-    kpu_model_memory_range_t inputs_mem[0];
+	uint32_t flags;
+	uint32_t main_mem_out_address;
+	uint32_t input_count;
+	kpu_model_memory_range_t inputs_mem[0];
 } kpu_model_concat_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t in_channels;
-    uint32_t out_channels;
-    kpu_model_activation_t act;
-    float weights[0];
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t in_channels;
+	uint32_t out_channels;
+	kpu_model_activation_t act;
+	float weights[0];
 } kpu_model_fully_connected_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    kpu_model_shape_t shape;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	kpu_model_shape_t shape;
 } kpu_model_tf_flatten_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    kpu_model_shape_t in_shape;
-    uint32_t out_width;
-    uint32_t out_height;
-    uint32_t align_corners;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	kpu_model_shape_t in_shape;
+	uint32_t out_width;
+	uint32_t out_height;
+	uint32_t align_corners;
 } kpu_model_resize_nearest_neighbor_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    kpu_model_shape_t in_shape;
-    uint32_t out_width;
-    uint32_t out_height;
-    uint32_t align_corners;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	kpu_model_shape_t in_shape;
+	uint32_t out_width;
+	uint32_t out_height;
+	uint32_t align_corners;
 } kpu_model_quant_resize_nearest_neighbor_layer_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t channels;
-    uint32_t channel_size;
-    kpu_model_quant_param_t quant_params[0];
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t channels;
+	uint32_t channel_size;
+	kpu_model_quant_param_t quant_params[0];
 } kpu_model_channelwise_dequant_argument_t;
 
 typedef struct
 {
-    uint32_t flags;
-    uint32_t main_mem_in_address;
-    uint32_t main_mem_out_address;
-    uint32_t channels;
+	uint32_t flags;
+	uint32_t main_mem_in_address;
+	uint32_t main_mem_out_address;
+	uint32_t channels;
 } kpu_model_logistic_layer_argument_t;
 
@@ -671,299 +649,53 @@
 typedef struct
 {
-    int is_nncase;
-
-    union
-    {
-        struct
-        {
-            const uint8_t *model_buffer;
-            uint8_t *main_buffer;
-            uint32_t output_count;
-            const kpu_model_output_t *outputs;
-            const kpu_model_layer_header_t *layer_headers;
-            const uint8_t *body_start;
-            uint32_t layers_length;
-            volatile uint32_t current_layer;
-            const uint8_t *volatile current_body;
-            dmac_channel_number_t dma_ch;
-            kpu_done_callback_t done_callback;
-            void *userdata;
-        };
-
-        struct
-        {
-            void* nncase_ctx;
-        };
-    };
+	union
+	{
+		struct
+		{
+			const uint8_t *model_buffer;
+			uint8_t *main_buffer;
+			uint32_t output_count;
+			const kpu_model_output_t *outputs;
+			const kpu_model_layer_header_t *layer_headers;
+			const uint8_t *body_start;
+			uint32_t layers_length;
+			volatile uint32_t current_layer;
+			const uint8_t *volatile current_body;
+			dmac_channel_number_t dma_ch;
+			kpu_done_callback_t done_callback;
+			void *userdata;
+		};
+
+		struct
+		{
+			void* nncase_ctx;
+		};
+	};
 } kpu_model_context_t;
 
 typedef struct
 {
-    uint32_t weigths_offset;
-    uint32_t bn_offset;
-    uint32_t act_offset;
-    float input_scale;
-    float input_bias;
-    float output_scale;
-    float output_bias;
+	uint32_t weigths_offset;
+	uint32_t bn_offset;
+	uint32_t act_offset;
+	float input_scale;
+	float input_bias;
+	float output_scale;
+	float output_bias;
 } kpu_model_layer_metadata_t;
 
 typedef struct _quantize_param
 {
-    float scale;
-    float bias;
+	float scale;
+	float bias;
 } quantize_param_t;
 
 extern volatile kpu_config_t *const kpu;
 
-/**
- * @brief       Modle complier init kpu handler
- *
- * @param[in]   task            Kpu handler
- *
- * @return      Kpu handler
- */
-extern kpu_task_t *kpu_task_init(kpu_task_t *task);
-
-/**
- * @brief       Kpu run for AI
- *
- * @param[in]   task                Kpu handler
- * @param[in]   dma_ch              DMA for kpu
- * @param[in]   src                 The picture data
- * @param[in]   dest                The result of kpu
- * @param[in]   callback            The callback of kpu
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.Kpu is busy.
- */
-int kpu_run(kpu_task_t *task, dmac_channel_number_t dma_ch, const void *src, void *dest, plic_irq_callback_t callback);
-
-/**
- * @brief       Get kpu result buf
- *
- * @param[in]   task                Kpu handler
- *
- * @return      Kpu result buf
- */
-uint8_t *kpu_get_output_buf(kpu_task_t *task);
-
-/**
- * @brief       Release kpu output buf
- *
- * @param[in]   output_buf                Kpu output buf
- *
- */
-void kpu_release_output_buf(uint8_t *output_buf);
-
-/**
- * @brief       Kpu run for AI
- *
- * @param[in]   task                Kpu handler
-*
-* @return      result
-*     - 0      Success
-*     - Other  Fail.Kpu is busy.
-*/
-int kpu_start(kpu_task_t *task);
-
-/**
- * @brief      Initialize kpu handler
- *
- * @param[in]   task            Kpu handler
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
-int kpu_single_task_init(kpu_task_t *task);
-
-/**
- * @brief      Uninitialize kpu handler
- *
- * @param[in]   task            Kpu handler
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
-int kpu_single_task_deinit(kpu_task_t *task);
-
-/**
- * @brief      Load kmodel and init kpu task
- *
- * @param[in]   task            Kpu handler
- * @param[in]   buffer          Kmodel
- * @param[in]   meta            Test data
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
-int kpu_model_load_from_buffer(kpu_task_t *task, uint8_t *buffer, kpu_model_layer_metadata_t **meta);
-
-/**
- * @brief       Kpu initialize
- *
- * @param[in]   eight_bit_mode            0:16bit mode  1:8bit mode
- * @param[in]   callback                  Callback of kpu
- * @param[in]   userdata                  Data of callback
- *
- */
-void kpu_init(int eight_bit_mode, plic_irq_callback_t callback, void *userdata);
-
-/**
- * @brief       Kpu input data by dma
- *
- * @param[in]   layer                   Kpu task layer
- * @param[in]   src                     Image data
- * @param[in]   dma_ch                  Dmac channel
- * @param[in]   callback                Dmac complete callback
- * @param[in]   userdata                Data of callback
- *
- */
-void kpu_input_dma(const kpu_layer_argument_t *layer, const uint8_t *src, dmac_channel_number_t dma_ch, plic_irq_callback_t callback, void *userdata);
-
-/**
- * @brief       Kpu input data by cpu
- *
- * @param[in]   layer                   Kpu task layer
- * @param[in]   src                     Image data
- * @param[in]   width                   Image width
- * @param[in]   height                  Image heigth
- * @param[in]   channels                Color channel, RGB is 3
- *
- */
-void kpu_input_with_padding(kpu_layer_argument_t *layer, const uint8_t *src, int width, int height, int channels);
-
-/**
- * @brief       Kpu run only one layer
- *
- * @param[in]   layer                   Kpu task layer
- *
- */
-void kpu_conv2d(kpu_layer_argument_t *layer);
-
-/**
- * @brief       Kpu run only one layer then get the result by dma
- *
- * @param[in]   layer                   Kpu task layer
- * @param[in]   dma_ch                  Dmac channel
- * @param[in]   dest                    Result
- * @param[in]   callback                Dmac complete callback
- * @param[in]   userdata                Data of callback
- *
- */
-void kpu_conv2d_output(kpu_layer_argument_t *layer, dmac_channel_number_t dma_ch, uint8_t *dest, plic_irq_callback_t callback, void *userdata);
-
-/**
- * @brief       Kpu pooling
- *
- * @param[in]   src                        Source
- * @param[in]   src_param                  Source param
- * @param[in]   kernel_size                Kernel size, 7*7 is 49
- * @param[in]   channels                   Channels
- * @param[in]   dest                       Dest
- * @param[in]   dest_param                 Dest param
- *
- */
-void kpu_global_average_pool(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, uint8_t *dest, const quantize_param_t *dest_param);
-
-/**
- * @brief       Kpu pooling
- *
- * @param[in]   src                        Source
- * @param[in]   src_param                  Source param
- * @param[in]   kernel_size                Kernel size, 7*7 is 49
- * @param[in]   channels                   Channels
- * @param[in]   dest                       Dest
- *
- */
-void kpu_global_average_pool_float(const uint8_t *src, const quantize_param_t *src_param, int kernel_size, int channels, float *dest);
-
-/**
- * @brief       Kpu fullly connected by cpu
- *
- * @param[in]   src                                 Source
- * @param[in]   weights                             Weight
- * @param[in]   biases                              Biases
- * @param[in]   dest                                Dest
- * @param[in]   input_channels                      Input channels
- * @param[in]   output_channels                     Output channels
- *
- */
-void kpu_fully_connected(const float *src, const float *weights, const float *biases, float *dest, int input_channels, int output_channels);
-
-/**
- * @brief       Kpu matrix multiplication
- *
- * @param[in]   src                                 Source
- * @param[in]   channels                            Channels
- * @param[in]   dest                                Dest
- * @param[in]   dest_param                          Dest param
- *
- */
-void kpu_matmul_end(const uint8_t *src, int channels, float *dest, const quantize_param_t *dest_param);
-
-/**
- * @brief       Kpu dequantize
- *
- * @param[in]   src                                 Source
- * @param[in]   src_param                           Source param
- * @param[in]   count                               Dequantize count
- * @param[in]   dest                                Dest
- *
- */
-void kpu_dequantize(const uint8_t *src, const quantize_param_t *src_param, size_t count, float *dest);
-
-/**
- * @brief       Kpu load kmodel
- *
- * @param[in]   ctx                                 Kmodel object
- * @param[in]   buffer                              Kmodel buffer
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
+ER kpu_init(kpu_model_context_t *ctx);
 int kpu_load_kmodel(kpu_model_context_t *ctx, const uint8_t *buffer);
-
-/**
- * @brief       Kpu free kmodel buffer
- *
- * @param[in]   ctx                                 kmodel object
- *
- */
-void kpu_model_free(kpu_model_context_t *ctx);
-
-/**
- * @brief       Kpu load kmodel
- *
- * @param[in]   ctx                                 Kmodel object
- * @param[in]   index                               Output index
- * @param[in]   data                                Output data
- * @param[in]   size                                Output data size
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
 int kpu_get_output(kpu_model_context_t *ctx, uint32_t index, uint8_t **data, size_t *size);
-
-/**
- * @brief       Kpu run kmodel
- *
- * @param[in]   ctx                                 Kmodel object
- * @param[in]   src                                 Source data
- * @param[in]   dma_ch                              Dma channel
- * @param[in]   done_callback                       Kpu complete callback
- * @param[in]   userdata                            Data of callback
- *
- * @return      result
- *     - 0      Success
- *     - Other  Fail.
- */
 int kpu_run_kmodel(kpu_model_context_t *ctx, const uint8_t *src, dmac_channel_number_t dma_ch, kpu_done_callback_t done_callback, void *userdata);
+ER kpu_wait_done(kpu_model_context_t *ctx, TMO tmout);
 
 #ifdef __cplusplus
Index: azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/region_layer.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/region_layer.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/kendryte/region_layer.c	(revision 458)
@@ -6,15 +6,15 @@
 typedef struct
 {
-    float x;
-    float y;
-    float w;
-    float h;
+	float x;
+	float y;
+	float w;
+	float h;
 } box_t;
 
 typedef struct
 {
-    int index;
-    int class;
-    float **probs;
+	int index;
+	int class;
+	float **probs;
 } sortable_box_t;
 
@@ -22,384 +22,384 @@
 int region_layer_init(region_layer_t *rl, int width, int height, int channels, int origin_width, int origin_height)
 {
-    int flag = 0;
-
-    rl->coords = 4;
-    rl->image_width = 320;
-    rl->image_height = 240;
-
-    rl->classes = channels / 5 - 5;
-    rl->net_width = origin_width;
-    rl->net_height = origin_height;
-    rl->layer_width = width;
-    rl->layer_height = height;
-    rl->boxes_number = (rl->layer_width * rl->layer_height * rl->anchor_number); 
-    rl->output_number = (rl->boxes_number * (rl->classes + rl->coords + 1));
-
-    rl->output = malloc(rl->output_number * sizeof(float));
-    if (rl->output == NULL)
-    {
-        flag = -1;
-        goto malloc_error;
-    }
-    rl->boxes = malloc(rl->boxes_number * sizeof(box_t));
-    if (rl->boxes == NULL)
-    {
-        flag = -2;
-        goto malloc_error;
-    }
-    rl->probs_buf = malloc(rl->boxes_number * (rl->classes + 1) * sizeof(float));
-    if (rl->probs_buf == NULL)
-    {
-        flag = -3;
-        goto malloc_error;
-    }
-    rl->probs = malloc(rl->boxes_number * sizeof(float *));
-    if (rl->probs == NULL)
-    {
-        flag = -4;
-        goto malloc_error;
-    }
-    for (uint32_t i = 0; i < rl->boxes_number; i++)
-        rl->probs[i] = &(rl->probs_buf[i * (rl->classes + 1)]);
-    return 0;
+	int flag = 0;
+
+	rl->coords = 4;
+	rl->image_width = 320;
+	rl->image_height = 240;
+
+	rl->classes = channels / 5 - 5;
+	rl->net_width = origin_width;
+	rl->net_height = origin_height;
+	rl->layer_width = width;
+	rl->layer_height = height;
+	rl->boxes_number = (rl->layer_width * rl->layer_height * rl->anchor_number); 
+	rl->output_number = (rl->boxes_number * (rl->classes + rl->coords + 1));
+
+	rl->output = malloc(rl->output_number * sizeof(float));
+	if (rl->output == NULL)
+	{
+		flag = -1;
+		goto malloc_error;
+	}
+	rl->boxes = malloc(rl->boxes_number * sizeof(box_t));
+	if (rl->boxes == NULL)
+	{
+		flag = -2;
+		goto malloc_error;
+	}
+	rl->probs_buf = malloc(rl->boxes_number * (rl->classes + 1) * sizeof(float));
+	if (rl->probs_buf == NULL)
+	{
+		flag = -3;
+		goto malloc_error;
+	}
+	rl->probs = malloc(rl->boxes_number * sizeof(float *));
+	if (rl->probs == NULL)
+	{
+		flag = -4;
+		goto malloc_error;
+	}
+	for (uint32_t i = 0; i < rl->boxes_number; i++)
+		rl->probs[i] = &(rl->probs_buf[i * (rl->classes + 1)]);
+	return 0;
 malloc_error:
-    free(rl->output);
-    free(rl->boxes);
-    free(rl->probs_buf);
-    free(rl->probs);
-    return flag;
+	free(rl->output);
+	free(rl->boxes);
+	free(rl->probs_buf);
+	free(rl->probs);
+	return flag;
 }
 
 void region_layer_deinit(region_layer_t *rl)
 {
-    free(rl->output);
-    free(rl->boxes);
-    free(rl->probs_buf);
-    free(rl->probs);
+	free(rl->output);
+	free(rl->boxes);
+	free(rl->probs_buf);
+	free(rl->probs);
 }
 
 static inline float sigmoid(float x)
 {
-    return 1.f / (1.f + expf(-x));
+	return 1.f / (1.f + expf(-x));
 }
 
 static void activate_array(region_layer_t *rl, int index, int n)
 {
-    float *output = &rl->output[index];
-    float *input = &rl->input[index];
-
-    for (int i = 0; i < n; ++i)
-        output[i] = sigmoid(input[i]);
+	float *output = &rl->output[index];
+	float *input = &rl->input[index];
+
+	for (int i = 0; i < n; ++i)
+		output[i] = sigmoid(input[i]);
 }
 
 static int entry_index(region_layer_t *rl, int location, int entry)
 {
-    int wh = rl->layer_width * rl->layer_height;
-    int n   = location / wh;
-    int loc = location % wh;
-
-    return n * wh * (rl->coords + rl->classes + 1) + entry * wh + loc;
+	int wh = rl->layer_width * rl->layer_height;
+	int n   = location / wh;
+	int loc = location % wh;
+
+	return n * wh * (rl->coords + rl->classes + 1) + entry * wh + loc;
 }
 
 static void softmax(region_layer_t *rl, float *input, int n, int stride, float *output)
 {
-    int i;
-    float diff;
-    float e;
-    float sum = 0;
-    float largest_i = input[0];
-
-    for (i = 0; i < n; ++i)
-    {
-        if (input[i * stride] > largest_i)
-            largest_i = input[i * stride];
-    }
-
-    for (i = 0; i < n; ++i) {
-        diff = input[i * stride] - largest_i;
-        e = expf(diff);
-        sum += e;
-        output[i * stride] = e;
-    }
-    for (i = 0; i < n; ++i)
-        output[i * stride] /= sum;
+	int i;
+	float diff;
+	float e;
+	float sum = 0;
+	float largest_i = input[0];
+
+	for (i = 0; i < n; ++i)
+	{
+		if (input[i * stride] > largest_i)
+			largest_i = input[i * stride];
+	}
+
+	for (i = 0; i < n; ++i) {
+		diff = input[i * stride] - largest_i;
+		e = expf(diff);
+		sum += e;
+		output[i * stride] = e;
+	}
+	for (i = 0; i < n; ++i)
+		output[i * stride] /= sum;
 }
 
 static void softmax_cpu(region_layer_t *rl, float *input, int n, int batch, int batch_offset, int groups, int stride, float *output)
 {
-    int g, b;
-
-    for (b = 0; b < batch; ++b) {
-        for (g = 0; g < groups; ++g)
-            softmax(rl, input + b * batch_offset + g, n, stride, output + b * batch_offset + g);
-    }
+	int g, b;
+
+	for (b = 0; b < batch; ++b) {
+		for (g = 0; g < groups; ++g)
+			softmax(rl, input + b * batch_offset + g, n, stride, output + b * batch_offset + g);
+	}
 }
 
 static void forward_region_layer(region_layer_t *rl)
 {
-    int index;
-
-    for (index = 0; index < rl->output_number; index++)
-        rl->output[index] = rl->input[index];
-
-    for (int n = 0; n < rl->anchor_number; ++n)
-    {
-        index = entry_index(rl, n * rl->layer_width * rl->layer_height, 0);
-        activate_array(rl, index, 2 * rl->layer_width * rl->layer_height);
-        index = entry_index(rl, n * rl->layer_width * rl->layer_height, 4);
-        activate_array(rl, index, rl->layer_width * rl->layer_height);
-    }
-
-    index = entry_index(rl, 0, rl->coords + 1);
-    softmax_cpu(rl, rl->input + index, rl->classes, rl->anchor_number,
-            rl->output_number / rl->anchor_number, rl->layer_width * rl->layer_height,
-            rl->layer_width * rl->layer_height, rl->output + index);
+	int index;
+
+	for (index = 0; index < rl->output_number; index++)
+		rl->output[index] = rl->input[index];
+
+	for (int n = 0; n < rl->anchor_number; ++n)
+	{
+		index = entry_index(rl, n * rl->layer_width * rl->layer_height, 0);
+		activate_array(rl, index, 2 * rl->layer_width * rl->layer_height);
+		index = entry_index(rl, n * rl->layer_width * rl->layer_height, 4);
+		activate_array(rl, index, rl->layer_width * rl->layer_height);
+	}
+
+	index = entry_index(rl, 0, rl->coords + 1);
+	softmax_cpu(rl, rl->input + index, rl->classes, rl->anchor_number,
+			rl->output_number / rl->anchor_number, rl->layer_width * rl->layer_height,
+			rl->layer_width * rl->layer_height, rl->output + index);
 }
 
 static void correct_region_boxes(region_layer_t *rl, box_t *boxes)
 {
-    uint32_t net_width = rl->net_width;
-    uint32_t net_height = rl->net_height;
-    uint32_t image_width = rl->image_width;
-    uint32_t image_height = rl->image_height;
-    uint32_t boxes_number = rl->boxes_number;
-    int new_w = 0;
-    int new_h = 0;
-
-    if (((float)net_width / image_width) <
-        ((float)net_height / image_height)) {
-        new_w = net_width;
-        new_h = (image_height * net_width) / image_width;
-    } else {
-        new_h = net_height;
-        new_w = (image_width * net_height) / image_height;
-    }
-    for (int i = 0; i < boxes_number; ++i) {
-        box_t b = boxes[i];
-
-        b.x = (b.x - (net_width - new_w) / 2. / net_width) /
-              ((float)new_w / net_width);
-        b.y = (b.y - (net_height - new_h) / 2. / net_height) /
-              ((float)new_h / net_height);
-        b.w *= (float)net_width / new_w;
-        b.h *= (float)net_height / new_h;
-        boxes[i] = b;
-    }
+	uint32_t net_width = rl->net_width;
+	uint32_t net_height = rl->net_height;
+	uint32_t image_width = rl->image_width;
+	uint32_t image_height = rl->image_height;
+	uint32_t boxes_number = rl->boxes_number;
+	int new_w = 0;
+	int new_h = 0;
+
+	if (((float)net_width / image_width) <
+		((float)net_height / image_height)) {
+		new_w = net_width;
+		new_h = (image_height * net_width) / image_width;
+	} else {
+		new_h = net_height;
+		new_w = (image_width * net_height) / image_height;
+	}
+	for (int i = 0; i < boxes_number; ++i) {
+		box_t b = boxes[i];
+
+		b.x = (b.x - (net_width - new_w) / 2. / net_width) /
+			  ((float)new_w / net_width);
+		b.y = (b.y - (net_height - new_h) / 2. / net_height) /
+			  ((float)new_h / net_height);
+		b.w *= (float)net_width / new_w;
+		b.h *= (float)net_height / new_h;
+		boxes[i] = b;
+	}
 }
 
 static box_t get_region_box(float *x, float *biases, int n, int index, int i, int j, int w, int h, int stride)
 {
-    volatile box_t b;
-
-    b.x = (i + x[index + 0 * stride]) / w;
-    b.y = (j + x[index + 1 * stride]) / h;
-    b.w = expf(x[index + 2 * stride]) * biases[2 * n] / w;
-    b.h = expf(x[index + 3 * stride]) * biases[2 * n + 1] / h;
-    return b;
+	volatile box_t b;
+
+	b.x = (i + x[index + 0 * stride]) / w;
+	b.y = (j + x[index + 1 * stride]) / h;
+	b.w = expf(x[index + 2 * stride]) * biases[2 * n] / w;
+	b.h = expf(x[index + 3 * stride]) * biases[2 * n + 1] / h;
+	return b;
 }
 
 static void get_region_boxes(region_layer_t *rl, float *predictions, float **probs, box_t *boxes)
 {
-    uint32_t layer_width = rl->layer_width;
-    uint32_t layer_height = rl->layer_height;
-    uint32_t anchor_number = rl->anchor_number;
-    uint32_t classes = rl->classes;
-    uint32_t coords = rl->coords;
-    float threshold = rl->threshold;
-
-    for (int i = 0; i < layer_width * layer_height; ++i)
-    {
-        int row = i / layer_width;
-        int col = i % layer_width;
-
-        for (int n = 0; n < anchor_number; ++n)
-        {
-            int index = n * layer_width * layer_height + i;
-
-            for (int j = 0; j < classes; ++j)
-                probs[index][j] = 0;
-            int obj_index = entry_index(rl, n * layer_width * layer_height + i, coords);
-            int box_index = entry_index(rl, n * layer_width * layer_height + i, 0);
-            float scale  = predictions[obj_index];
-
-            boxes[index] = get_region_box(predictions, rl->anchor, n, box_index, col, row,
-                layer_width, layer_height, layer_width * layer_height);
-
-            float max = 0;
-
-            for (int j = 0; j < classes; ++j)
-            {
-                int class_index = entry_index(rl, n * layer_width * layer_height + i, coords + 1 + j);
-                float prob = scale * predictions[class_index];
-
-                probs[index][j] = (prob > threshold) ? prob : 0;
-                if (prob > max)
-                    max = prob;
-            }
-            probs[index][classes] = max;
-        }
-    }
-    correct_region_boxes(rl, boxes);
+	uint32_t layer_width = rl->layer_width;
+	uint32_t layer_height = rl->layer_height;
+	uint32_t anchor_number = rl->anchor_number;
+	uint32_t classes = rl->classes;
+	uint32_t coords = rl->coords;
+	float threshold = rl->threshold;
+
+	for (int i = 0; i < layer_width * layer_height; ++i)
+	{
+		int row = i / layer_width;
+		int col = i % layer_width;
+
+		for (int n = 0; n < anchor_number; ++n)
+		{
+			int index = n * layer_width * layer_height + i;
+
+			for (int j = 0; j < classes; ++j)
+				probs[index][j] = 0;
+			int obj_index = entry_index(rl, n * layer_width * layer_height + i, coords);
+			int box_index = entry_index(rl, n * layer_width * layer_height + i, 0);
+			float scale  = predictions[obj_index];
+
+			boxes[index] = get_region_box(predictions, rl->anchor, n, box_index, col, row,
+				layer_width, layer_height, layer_width * layer_height);
+
+			float max = 0;
+
+			for (int j = 0; j < classes; ++j)
+			{
+				int class_index = entry_index(rl, n * layer_width * layer_height + i, coords + 1 + j);
+				float prob = scale * predictions[class_index];
+
+				probs[index][j] = (prob > threshold) ? prob : 0;
+				if (prob > max)
+					max = prob;
+			}
+			probs[index][classes] = max;
+		}
+	}
+	correct_region_boxes(rl, boxes);
 }
 
 static int nms_comparator(void *pa, void *pb)
 {
-    sortable_box_t a = *(sortable_box_t *)pa;
-    sortable_box_t b = *(sortable_box_t *)pb;
-    float diff = a.probs[a.index][b.class] - b.probs[b.index][b.class];
-
-    if (diff < 0)
-        return 1;
-    else if (diff > 0)
-        return -1;
-    return 0;
+	sortable_box_t a = *(sortable_box_t *)pa;
+	sortable_box_t b = *(sortable_box_t *)pb;
+	float diff = a.probs[a.index][b.class] - b.probs[b.index][b.class];
+
+	if (diff < 0)
+		return 1;
+	else if (diff > 0)
+		return -1;
+	return 0;
 }
 
 static float overlap(float x1, float w1, float x2, float w2)
 {
-    float l1 = x1 - w1/2;
-    float l2 = x2 - w2/2;
-    float left = l1 > l2 ? l1 : l2;
-    float r1 = x1 + w1/2;
-    float r2 = x2 + w2/2;
-    float right = r1 < r2 ? r1 : r2;
-
-    return right - left;
+	float l1 = x1 - w1/2;
+	float l2 = x2 - w2/2;
+	float left = l1 > l2 ? l1 : l2;
+	float r1 = x1 + w1/2;
+	float r2 = x2 + w2/2;
+	float right = r1 < r2 ? r1 : r2;
+
+	return right - left;
 }
 
 static float box_intersection(box_t a, box_t b)
 {
-    float w = overlap(a.x, a.w, b.x, b.w);
-    float h = overlap(a.y, a.h, b.y, b.h);
-
-    if (w < 0 || h < 0)
-        return 0;
-    return w * h;
+	float w = overlap(a.x, a.w, b.x, b.w);
+	float h = overlap(a.y, a.h, b.y, b.h);
+
+	if (w < 0 || h < 0)
+		return 0;
+	return w * h;
 }
 
 static float box_union(box_t a, box_t b)
 {
-    float i = box_intersection(a, b);
-    float u = a.w * a.h + b.w * b.h - i;
-
-    return u;
+	float i = box_intersection(a, b);
+	float u = a.w * a.h + b.w * b.h - i;
+
+	return u;
 }
 
 static float box_iou(box_t a, box_t b)
 {
-    return box_intersection(a, b) / box_union(a, b);
+	return box_intersection(a, b) / box_union(a, b);
 }
 
 static void do_nms_sort(region_layer_t *rl, box_t *boxes, float **probs)
 {
-    uint32_t boxes_number = rl->boxes_number;
-    uint32_t classes = rl->classes;
-    float nms_value = rl->nms_value;
-    int i, j, k;
-    sortable_box_t s[boxes_number];
-
-    for (i = 0; i < boxes_number; ++i)
-    {
-        s[i].index = i;
-        s[i].class = 0;
-        s[i].probs = probs;
-    }
-
-    for (k = 0; k < classes; ++k)
-    {
-        for (i = 0; i < boxes_number; ++i)
-            s[i].class = k;
-        qsort(s, boxes_number, sizeof(sortable_box_t), nms_comparator);
-        for (i = 0; i < boxes_number; ++i)
-        {
-            if (probs[s[i].index][k] == 0)
-                continue;
-            box_t a = boxes[s[i].index];
-
-            for (j = i + 1; j < boxes_number; ++j)
-            {
-                box_t b = boxes[s[j].index];
-
-                if (box_iou(a, b) > nms_value)
-                    probs[s[j].index][k] = 0;
-            }
-        }
-    }
+	uint32_t boxes_number = rl->boxes_number;
+	uint32_t classes = rl->classes;
+	float nms_value = rl->nms_value;
+	int i, j, k;
+	sortable_box_t s[boxes_number];
+
+	for (i = 0; i < boxes_number; ++i)
+	{
+		s[i].index = i;
+		s[i].class = 0;
+		s[i].probs = probs;
+	}
+
+	for (k = 0; k < classes; ++k)
+	{
+		for (i = 0; i < boxes_number; ++i)
+			s[i].class = k;
+		qsort(s, boxes_number, sizeof(sortable_box_t), nms_comparator);
+		for (i = 0; i < boxes_number; ++i)
+		{
+			if (probs[s[i].index][k] == 0)
+				continue;
+			box_t a = boxes[s[i].index];
+
+			for (j = i + 1; j < boxes_number; ++j)
+			{
+				box_t b = boxes[s[j].index];
+
+				if (box_iou(a, b) > nms_value)
+					probs[s[j].index][k] = 0;
+			}
+		}
+	}
 }
 
 static int max_index(float *a, int n)
 {
-    int i, max_i = 0;
-    float max = a[0];
-
-    for (i = 1; i < n; ++i)
-    {
-        if (a[i] > max)
-        {
-            max   = a[i];
-            max_i = i;
-        }
-    }
-    return max_i;
+	int i, max_i = 0;
+	float max = a[0];
+
+	for (i = 1; i < n; ++i)
+	{
+		if (a[i] > max)
+		{
+			max   = a[i];
+			max_i = i;
+		}
+	}
+	return max_i;
 }
 
 static void region_layer_output(region_layer_t *rl, obj_info_t *obj_info)
 {
-    uint32_t obj_number = 0;
-    uint32_t image_width = rl->image_width;
-    uint32_t image_height = rl->image_height;
-    uint32_t boxes_number = rl->boxes_number;
-    float threshold = rl->threshold;
-    box_t *boxes = (box_t *)rl->boxes;
-    
-    for (int i = 0; i < rl->boxes_number; ++i)
-    {
-        int class  = max_index(rl->probs[i], rl->classes);
-        float prob = rl->probs[i][class];
-
-        if (prob > threshold)
-        {
-            box_t *b = boxes + i;
-            obj_info->obj[obj_number].x1 = b->x * image_width - (b->w * image_width / 2);
-            obj_info->obj[obj_number].y1 = b->y * image_height - (b->h * image_height / 2);
-            obj_info->obj[obj_number].x2 = b->x * image_width + (b->w * image_width / 2);
-            obj_info->obj[obj_number].y2 = b->y * image_height + (b->h * image_height / 2);
-            obj_info->obj[obj_number].class_id = class;
-            obj_info->obj[obj_number].prob = prob;
-            obj_number++;
-        }
-    }
-    obj_info->obj_number = obj_number;
+	uint32_t obj_number = 0;
+	uint32_t image_width = rl->image_width;
+	uint32_t image_height = rl->image_height;
+	uint32_t boxes_number = rl->boxes_number;
+	float threshold = rl->threshold;
+	box_t *boxes = (box_t *)rl->boxes;
+	
+	for (int i = 0; i < rl->boxes_number; ++i)
+	{
+		int class  = max_index(rl->probs[i], rl->classes);
+		float prob = rl->probs[i][class];
+
+		if (prob > threshold)
+		{
+			box_t *b = boxes + i;
+			obj_info->obj[obj_number].x1 = b->x * image_width - (b->w * image_width / 2);
+			obj_info->obj[obj_number].y1 = b->y * image_height - (b->h * image_height / 2);
+			obj_info->obj[obj_number].x2 = b->x * image_width + (b->w * image_width / 2);
+			obj_info->obj[obj_number].y2 = b->y * image_height + (b->h * image_height / 2);
+			obj_info->obj[obj_number].class_id = class;
+			obj_info->obj[obj_number].prob = prob;
+			obj_number++;
+		}
+	}
+	obj_info->obj_number = obj_number;
 }
 
 void region_layer_run(region_layer_t *rl, obj_info_t *obj_info)
 {
-    forward_region_layer(rl);
-    get_region_boxes(rl, rl->output, rl->probs, rl->boxes);
-    do_nms_sort(rl, rl->boxes, rl->probs);
-    // region_layer_output(rl, obj_info);
+	forward_region_layer(rl);
+	get_region_boxes(rl, rl->output, rl->probs, rl->boxes);
+	do_nms_sort(rl, rl->boxes, rl->probs);
+	// region_layer_output(rl, obj_info);
 }
 
 void region_layer_draw_boxes(region_layer_t *rl, callback_draw_box callback)
 {
-    uint32_t image_width = rl->image_width;
-    uint32_t image_height = rl->image_height;
-    float threshold = rl->threshold;
-    box_t *boxes = (box_t *)rl->boxes;
-
-    for (int i = 0; i < rl->boxes_number; ++i)
-    {
-        int class  = max_index(rl->probs[i], rl->classes);
-        float prob = rl->probs[i][class];
-
-        if (prob > threshold)
-        {
-            box_t *b = boxes + i;
-            uint32_t x1 = b->x * image_width - (b->w * image_width / 2);
-            uint32_t y1 = b->y * image_height - (b->h * image_height / 2);
-            uint32_t x2 = b->x * image_width + (b->w * image_width / 2);
-            uint32_t y2 = b->y * image_height + (b->h * image_height / 2);
-            callback(x1, y1, x2, y2, class, prob);
-        }
-    }
-}
+	uint32_t image_width = rl->image_width;
+	uint32_t image_height = rl->image_height;
+	float threshold = rl->threshold;
+	box_t *boxes = (box_t *)rl->boxes;
+
+	for (int i = 0; i < rl->boxes_number; ++i)
+	{
+		int class  = max_index(rl->probs[i], rl->classes);
+		float prob = rl->probs[i][class];
+
+		if (prob > threshold)
+		{
+			box_t *b = boxes + i;
+			uint32_t x1 = b->x * image_width - (b->w * image_width / 2);
+			uint32_t y1 = b->y * image_height - (b->h * image_height / 2);
+			uint32_t x2 = b->x * image_width + (b->w * image_width / 2);
+			uint32_t y2 = b->y * image_height + (b->h * image_height / 2);
+			callback(x1, y1, x2, y2, class, prob);
+		}
+	}
+}
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/command.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/command.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/command.c	(revision 458)
@@ -92,9 +92,9 @@
 void
 digitalWrite(uint8_t Pin, int dwVal){
-    int8_t gpio_pin = gpio_get_gpiohno(Pin, false);
+	int8_t gpio_pin = gpio_get_gpiohno(Pin, false);
 
-    if( gpio_pin >= 0){
-        gpio_set_pin(TADR_GPIOHS_BASE, (uint8_t)gpio_pin, dwVal);
-    }
+	if( gpio_pin >= 0){
+		gpio_set_pin(TADR_GPIOHS_BASE, (uint8_t)gpio_pin, dwVal);
+	}
 }
 
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/envcmd.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/envcmd.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/envcmd.c	(revision 458)
@@ -1,47 +1,43 @@
 /*
-*  TOPPERS/ASP Kernel
-*      Toyohashi Open Platform for Embedded Real-Time Systems/
-*      Advanced Standard Profile Kernel
-* 
-*  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
-*                              Toyohashi Univ. of Technology, JAPAN
-*  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
-*              Graduate School of Information Science, Nagoya Univ., JAPAN
-* 
-*  ãLì ÒÍCÈºÌ(1)`(4)Ìðð½·êÉÀèC{\tgEF
-*  Ai{\tgEFAðüÏµ½àÌðÜÞDÈº¯¶jðgpE¡»Eü
-*  ÏEÄzziÈºCpÆÄÔj·é±Æð³Åø·éD
-*  (1) {\tgEFAð\[XR[hÌ`Åp·éêÉÍCãLÌì
-*       \¦C±Ìpð¨æÑºLÌ³ÛØKèªC»ÌÜÜÌ`Å\[
-*      XR[hÉÜÜêÄ¢é±ÆD
-*  (2) {\tgEFAðCCu`®ÈÇC¼Ì\tgEFAJ­Ég
-*      pÅ«é`ÅÄzz·éêÉÍCÄzzÉº¤hL
-gip
-*      Ò}j
-AÈÇjÉCãLÌì \¦C±Ìpð¨æÑºL
-*      Ì³ÛØKèðfÚ·é±ÆD
-*  (3) {\tgEFAðC@íÉgÝÞÈÇC¼Ì\tgEFAJ­Ég
-*      pÅ«È¢`ÅÄzz·éêÉÍCÌ¢¸ê©Ìðð½·±
-*      ÆD
-*    (a) ÄzzÉº¤hL
-gipÒ}j
-AÈÇjÉCãLÌ
-*        ì \¦C±Ìpð¨æÑºLÌ³ÛØKèðfÚ·é±ÆD
-*    (b) ÄzzÌ`ÔðCÊÉèßéû@ÉæÁÄCTOPPERSvWFNgÉ
-*        ñ·é±ÆD
-*  (4) {\tgEFAÌpÉæè¼ÚIÜ½ÍÔÚIÉ¶¶é¢©Èé¹
-*      Q©çàCãLì Ò¨æÑTOPPERSvWFNgðÆÓ·é±ÆD
-*      Ü½C{\tgEFAÌ[UÜ½ÍGh[U©çÌ¢©Èé
-*      RÉîÃ­¿©çàCãLì Ò¨æÑTOPPERSvWFNgð
-*      ÆÓ·é±ÆD
-* 
-*  {\tgEFAÍC³ÛØÅñ³êÄ¢éàÌÅ éDãLì Ò¨
-*  æÑTOPPERSvWFNgÍC{\tgEFAÉÖµÄCÁèÌgpÚI
-*  ÉÎ·éK«àÜßÄC¢©ÈéÛØàsíÈ¢DÜ½C{\tgEF
-*  AÌpÉæè¼ÚIÜ½ÍÔÚIÉ¶¶½¢©Èé¹QÉÖµÄàC»
-*  ÌÓCðíÈ¢D
-* 
-*  $Id$
-*/
+ *  TOPPERS/ASP Kernel
+ *      Toyohashi Open Platform for Embedded Real-Time Systems/
+ *      Advanced Standard Profile Kernel
+ * 
+ *  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
+ *                              Toyohashi Univ. of Technology, JAPAN
+ *  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
+ *              Graduate School of Information Science, Nagoya Univ., JAPAN
+ * 
+ *  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
+ *  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
+ *  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
+ *  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
+ *      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
+ *      スコード中に含まれていること．
+ *  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
+ *      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
+ *      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
+ *      の無保証規定を掲載すること．
+ *  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
+ *      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
+ *      と．
+ *    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
+ *        作権表示，この利用条件および下記の無保証規定を掲載すること．
+ *    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
+ *        報告すること．
+ *  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
+ *      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
+ *      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
+ *      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
+ *      免責すること．
+ * 
+ *  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
+ *  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
+ *  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
+ *  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
+ *  の責任を負わない．
+ * 
+ *  $Id$
+ */
 #include <stdio.h>
 #include <stdlib.h>
@@ -222,5 +218,4 @@
 }
 
-
 int set_cs_main(int argc, char **argv)
 {
@@ -285,4 +280,5 @@
 	return 0;
 }
+
 int clear_proxy_main(int argc, char **argv)
 {
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.c	(revision 458)
@@ -1,43 +1,43 @@
 /*
-*  TOPPERS/ASP Kernel
-*      Toyohashi Open Platform for Embedded Real-Time Systems/
-*      Advanced Standard Profile Kernel
-* 
-*  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
-*                              Toyohashi Univ. of Technology, JAPAN
-*  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
-*              Graduate School of Information Science, Nagoya Univ., JAPAN
-* 
-*  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
-*  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
-*  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
-*  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
-*      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
-*      スコード中に含まれていること．
-*  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
-*      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
-*      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
-*      の無保証規定を掲載すること．
-*  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
-*      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
-*      と．
-*    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
-*        作権表示，この利用条件および下記の無保証規定を掲載すること．
-*    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
-*        報告すること．
-*  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
-*      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
-*      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
-*      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
-*      免責すること．
-* 
-*  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
-*  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
-*  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
-*  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
-*  の責任を負わない．
-* 
-*  $Id$
-*/
+ *  TOPPERS/ASP Kernel
+ *      Toyohashi Open Platform for Embedded Real-Time Systems/
+ *      Advanced Standard Profile Kernel
+ * 
+ *  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
+ *                              Toyohashi Univ. of Technology, JAPAN
+ *  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
+ *              Graduate School of Information Science, Nagoya Univ., JAPAN
+ * 
+ *  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
+ *  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
+ *  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
+ *  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
+ *      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
+ *      スコード中に含まれていること．
+ *  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
+ *      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
+ *      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
+ *      の無保証規定を掲載すること．
+ *  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
+ *      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
+ *      と．
+ *    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
+ *        作権表示，この利用条件および下記の無保証規定を掲載すること．
+ *    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
+ *        報告すること．
+ *  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
+ *      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
+ *      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
+ *      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
+ *      免責すること．
+ * 
+ *  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
+ *  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
+ *  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
+ *  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
+ *  の責任を負わない．
+ * 
+ *  $Id$
+ */
 #include <stddef.h>
 #include <stdbool.h>
@@ -306,10 +306,10 @@
 {
 	struct tm tm = {
-        0,  /* tm_sec */
-        0,  /* tm_min */
-        0,  /* tm_hour */
-        1,  /* tm_mday */
-        0,  /* tm_mon */
-        2020 - 1900,  /* tm_year */
+		0,  /* tm_sec */
+		0,  /* tm_min */
+		0,  /* tm_hour */
+		1,  /* tm_mday */
+		0,  /* tm_mon */
+		2020 - 1900,  /* tm_year */
 	};
 	MINIMUM_YEAR = mktime(&tm);
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/esp_at_socket.h	(revision 458)
@@ -1,43 +1,43 @@
 /*
-*  TOPPERS/ASP Kernel
-*      Toyohashi Open Platform for Embedded Real-Time Systems/
-*      Advanced Standard Profile Kernel
-* 
-*  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
-*                              Toyohashi Univ. of Technology, JAPAN
-*  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
-*              Graduate School of Information Science, Nagoya Univ., JAPAN
-* 
-*  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
-*  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
-*  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
-*  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
-*      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
-*      スコード中に含まれていること．
-*  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
-*      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
-*      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
-*      の無保証規定を掲載すること．
-*  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
-*      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
-*      と．
-*    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
-*        作権表示，この利用条件および下記の無保証規定を掲載すること．
-*    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
-*        報告すること．
-*  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
-*      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
-*      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
-*      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
-*      免責すること．
-* 
-*  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
-*  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
-*  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
-*  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
-*  の責任を負わない．
-* 
-*  $Id$
-*/
+ *  TOPPERS/ASP Kernel
+ *      Toyohashi Open Platform for Embedded Real-Time Systems/
+ *      Advanced Standard Profile Kernel
+ * 
+ *  Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory
+ *                              Toyohashi Univ. of Technology, JAPAN
+ *  Copyright (C) 2004-2012 by Embedded and Real-Time Systems Laboratory
+ *              Graduate School of Information Science, Nagoya Univ., JAPAN
+ * 
+ *  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
+ *  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
+ *  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
+ *  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
+ *      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
+ *      スコード中に含まれていること．
+ *  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
+ *      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
+ *      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
+ *      の無保証規定を掲載すること．
+ *  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
+ *      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
+ *      と．
+ *    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
+ *        作権表示，この利用条件および下記の無保証規定を掲載すること．
+ *    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
+ *        報告すること．
+ *  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
+ *      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
+ *      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
+ *      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
+ *      免責すること．
+ * 
+ *  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
+ *  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
+ *  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
+ *  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
+ *  の責任を負わない．
+ * 
+ *  $Id$
+ */
 
 #ifndef _ESP_AT_SOCKET_H_
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.c
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.c	(revision 458)
@@ -38,5 +38,5 @@
 *  の責任を負わない．
 * 
-*  $Id$
+*  $Id: kpu_main.c 2176 2020-08-19 23:50:05Z coas-nagasima $
 */
 
@@ -63,6 +63,4 @@
 #include "kpu.h"
 #include "region_layer.h"
-
-extern void ai_dma_done_isr(DMA_Handle_t *dma);
 
 /*
@@ -187,5 +185,5 @@
 static uint32_t lable_string_draw_ram[115 * 16 * 8 / 2];
 #endif
-extern uint8_t model_data[];
+extern const uint8_t model_data[];
 kpu_model_context_t g_task;
 static region_layer_t detect_rl;
@@ -234,7 +232,6 @@
 	OV2640_t        *hcmr;
 	DVP_Handle_t    *hdvp;
-	uint16_t        *lcd_buffer;
 	ER_UINT	ercd;
-	uint32_t i, count;
+	uint32_t i;
 	struct tm2 time;
 	unsigned long atmp;
@@ -371,5 +368,5 @@
 	syslog_1(LOG_NOTICE, "OV2640 id(%d)", ov2640_id(hcmr));
 
-	Init.WorkMode     = SPI_WORK_MODE_0;
+	Init.WorkMode     = SPI_WORK_MODE_2;
 	Init.FrameFormat  = SPI_FF_OCTAL;
 	Init.DataSize     = 8;
@@ -385,5 +382,5 @@
 	Init.SsPin        = SIPEED_ST7789_SS_PIN;
 	Init.SsNo         = SIPEED_ST7789_SS;
-	Init.TxDMAChannel = SIPEED_DMA_CH;
+	Init.TxDMAChannel = -1;
 	Init.RxDMAChannel = -1;
 	Init.semid        = SPI1TRN_SEM;
@@ -408,10 +405,5 @@
 	lcd_init(hlcd);
 	syslog_2(LOG_NOTICE, "width(%d) height(%d)", hlcd->_width, hlcd->_height);
-	count = hcmr->_width * hcmr->_height;
-	lcd_buffer = (uint16_t *)malloc(count * 2);
-	if(lcd_buffer == NULL){
-		syslog_0(LOG_ERROR, "no lcd buffer !");
-		slp_tsk();
-	}
+
 	DrawProp.BackColor = ST7789_WHITE;
 	DrawProp.TextColor = ST7789_BLACK;
@@ -466,29 +458,7 @@
 		syslog_0(LOG_ERROR, "SD-CARD INITAIL ERROR !");
 #endif
-	extern DMA_Handle_t g_ai_hdma;
-	g_ai_hdma.chnum = AI_DMA_CH;
-	g_ai_hdma.xfercallback = ai_dma_done_isr;
-	g_ai_hdma.errorcallback     = NULL;
-	g_ai_hdma.Init.Request      = DMA_SELECT_AI_RX_REQ;	/* DMA選択 */
-	g_ai_hdma.Init.Direction    = DMA_PERIPH_TO_MEMORY;	/* DMA転送方向 */
-	g_ai_hdma.Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;	/* ソースマルチブロックタイプ */
-	g_ai_hdma.Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;	/* デスティネーションマルチブロックタイプ */
-	g_ai_hdma.Init.SrcHandShake = DMAC_HS_HARDWARE;	/* ソースハンドシェイク */
-	g_ai_hdma.Init.DrcHandShake = DMAC_HS_SOFTWARE;	/* デスティネーションハンドシェイク */
-	g_ai_hdma.Init.SrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* ソースハードウェアハンドシェイク極性 */
-	g_ai_hdma.Init.DrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* デスティネーションハードウェアハンドシェイク極性 */
-	g_ai_hdma.Init.Priority     = 4;	/* 優先度 */
-	g_ai_hdma.Init.SrcMaster    = DMAC_MASTER1;	/* ソースマスター設定 */
-	g_ai_hdma.Init.DstMaster    = DMAC_MASTER2;	/* デスティネーションマスター設定 */
-	g_ai_hdma.Init.SrcInc       = DMAC_ADDR_NOCHANGE;	/* ソースインクリメント設定 */
-	g_ai_hdma.Init.DstInc       = DMAC_ADDR_INCREMENT;	/* デスティネーションインクリメント設定 */
-	g_ai_hdma.Init.SrcTransWidth = DMAC_TRANS_WIDTH_32;	/* ソース転送幅 */
-	g_ai_hdma.Init.DstTransWidth = DMAC_TRANS_WIDTH_32;	/* デスティネーション転送幅 */
-	g_ai_hdma.Init.SrcBurstSize = DMAC_MSIZE_4;	/* ソースバーストサイズ */
-	g_ai_hdma.Init.DstBurstSize = DMAC_MSIZE_4;	/* デスティネーションバーストサイズ */
-	g_ai_hdma.Init.IocBlkTrans  = 0;	/* IOCブロック転送 */
-	g_ai_hdma.localdata         = (void *)&g_task;
-	if ((ercd = dma_init(&g_ai_hdma)) != E_OK) {
-		syslog_0(LOG_ERROR, "AI-DMA INITAIL ERROR !");
+	if ((ercd = kpu_init(&g_task)) != E_OK) {
+		syslog_0(LOG_ERROR, "kpu init error");
+		slp_tsk();
 	}
 
@@ -502,5 +472,8 @@
 	detect_rl.threshold = 0.7;
 	detect_rl.nms_value = 0.3;
-	region_layer_init(&detect_rl, 10, 7, 125, 320, 240);
+	if (region_layer_init(&detect_rl, 10, 7, 125, 320, 240) != 0) {
+		syslog_0(LOG_ERROR, "region layer init error");
+		slp_tsk();
+	}
 
 	bool_t camok = true;
@@ -524,11 +497,4 @@
 			atmp = (unsigned long)hcmr->_aiBuffer - IOMEM;
 			kpu_run_kmodel(&g_task, (const uint8_t *)atmp, AI_DMA_CH, ai_done, NULL);
-
-			uint32_t *p = (uint32_t *)hcmr->_dataBuffer;
-			uint32_t *q = (uint32_t *)lcd_buffer;
-			uint32_t *e = (uint32_t *)&lcd_buffer[count];
-			for (; q < e ; p++, q++){
-				*q = SWAP_32(*p);
-			}
 		}
 
@@ -555,5 +521,5 @@
 		}
 
-		lcd_drawPicture(hlcd, 0, 0, hcmr->_width, hcmr->_height, lcd_buffer);
+		lcd_drawPicture(hlcd, 0, 0, hcmr->_width, hcmr->_height, (uint16_t *)hcmr->_dataBuffer);
 
 		/* draw boxs */
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/kpu_main.h	(revision 458)
@@ -38,5 +38,5 @@
  *  の責任を負わない．
  *
- *  $Id$
+ *  $Id: kpu_main.h 2173 2020-08-19 05:33:00Z coas-nagasima $
  */
 
@@ -55,6 +55,5 @@
  */
 
-#define KPU_PRIORITY	5		/* メインタスクの優先度 */
-								/* HIGH_PRIORITYより高くすること */
+#define KPU_PRIORITY	6		/* メインタスクの優先度 */
 
 /*
@@ -92,5 +91,5 @@
 #define INHNO_SPI     IRQ_VECTOR_SPI0	/* 割込みハンドラ番号 */
 #define INTNO_SPI     IRQ_VECTOR_SPI0	/* 割込み番号 */
-#define INTPRI_SPI    -5		/* 割込み優先度 */
+#define INTPRI_SPI    -6		/* 割込み優先度 */
 #define INTATR_SPI    0			/* 割込み属性 */
 
@@ -98,5 +97,5 @@
 #define INHNO_DMATX   IRQ_VECTOR_DMA3	/* 割込みハンドラ番号 */
 #define INTNO_DMATX   IRQ_VECTOR_DMA3	/* 割込み番号 */
-#define INTPRI_DMATX  -4		/* 割込み優先度 */
+#define INTPRI_DMATX  -6		/* 割込み優先度 */
 #define INTATR_DMATX  0			/* 割込み属性 */
 
@@ -104,5 +103,5 @@
 #define INHNO_SPIC    IRQ_VECTOR_SPI1	/* 割込みハンドラ番号 */
 #define INTNO_SPIC    IRQ_VECTOR_SPI1	/* 割込み番号 */
-#define INTPRI_SPIC   -5		/* 割込み優先度 */
+#define INTPRI_SPIC   -6		/* 割込み優先度 */
 #define INTATR_SPIC   0			/* 割込み属性 */
 
@@ -110,10 +109,10 @@
 #define INHNO_DMARX   IRQ_VECTOR_DMA2	/* 割込みハンドラ番号 */
 #define INTNO_DMARX   IRQ_VECTOR_DMA2	/* 割込み番号 */
-#define INTPRI_DMARX  -4		/* 割込み優先度 */
+#define INTPRI_DMARX  -6		/* 割込み優先度 */
 #define INTATR_DMARX  0			/* 割込み属性 */
 
 #define INHNO_AI      IRQ_VECTOR_AI	/* 割込みハンドラ番号 */
 #define INTNO_AI      IRQ_VECTOR_AI	/* 割込み番号 */
-#define INTPRI_AI     -4		/* 割込み優先度 */
+#define INTPRI_AI     -7		/* 割込み優先度 */
 #define INTATR_AI     0			/* 割込み属性 */
 
@@ -121,5 +120,5 @@
 #define INHNO_DMAAI   IRQ_VECTOR_DMA5	/* 割込みハンドラ番号 */
 #define INTNO_DMAAI   IRQ_VECTOR_DMA5	/* 割込み番号 */
-#define INTPRI_DMAAI  -4		/* 割込み優先度 */
+#define INTPRI_DMAAI  -7		/* 割込み優先度 */
 #define INTATR_DMAAI  0			/* 割込み属性 */
 
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/main.cfg
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/main.cfg	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/main.cfg	(revision 458)
@@ -11,4 +11,5 @@
 INCLUDE("syssvc/serial.cfg");
 INCLUDE("syssvc/logtask.cfg");
+INCLUDE("syssvc/malloc.cfg");
 INCLUDE("pdic/k210/device.cfg");
 INCLUDE("pdic/k210/dvp.cfg");
@@ -39,5 +40,5 @@
 
 CRE_TSK(MAIN_TASK, { TA_ACT, 0, main_task, MAIN_PRIORITY, STACK_SIZE, NULL });
-CRE_TSK(KPU_TASK, { TA_NULL, 0, kpu_task, KPU_PRIORITY, KPU_STACK_SIZE, NULL });
+CRE_TSK(KPU_TASK, { TA_ACT, 0, kpu_task, KPU_PRIORITY, KPU_STACK_SIZE, NULL });
 
 ATT_ISR({TA_NULL, SPI_PORTID, INTNO_SPI, spi_isr, 1 });
@@ -52,5 +53,5 @@
 
 ATT_ISR({TA_NULL, 0, INTNO_AI, ai_done_isr, 1 });
-CFG_INT(INTNO_AI, { TA_ENAINT | INTATR_AI, INTPRI_AI });
+CFG_INT(INTNO_AI, { INTATR_AI, INTPRI_AI });
 ATT_ISR({TA_NULL, AI_DMA_CH, INTNO_DMAAI, channel_dmac_isr, 1 });
 CFG_INT(INTNO_DMAAI, { TA_ENAINT | INTATR_DMAAI, INTPRI_DMAAI });
Index: azure_iot_hub_riscv/trunk/app_iothub_client/src/main.h
===================================================================
--- azure_iot_hub_riscv/trunk/app_iothub_client/src/main.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/app_iothub_client/src/main.h	(revision 458)
@@ -54,6 +54,5 @@
  */
 
-#define MAIN_PRIORITY	8		/* メインタスクの優先度 */
-								/* HIGH_PRIORITYより高くすること */
+#define MAIN_PRIORITY	5		/* メインタスクの優先度 */
 
 /*
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/Makefile
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/Makefile	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/Makefile	(revision 458)
@@ -215,9 +215,4 @@
 SYSSVC_LIBS := $(SYSSVC_LIBS)
 INCLUDES := $(INCLUDES) -I$(SRCDIR)/pdic/k210
-#LDFLAGS := $(LDFLAGS) \
-#	-Wl,--wrap=_malloc_r \
-#	-Wl,--wrap=_calloc_r \
-#	-Wl,--wrap=_free_r \
-#	-Wl,--wrap=_realloc_r
 
 #
@@ -489,7 +484,7 @@
   #
   ifdef GCC_TARGET
-    GCC_TARGET_PREFIX = $(GCC_TARGET)-
+	GCC_TARGET_PREFIX = $(GCC_TARGET)-
   else
-    GCC_TARGET_PREFIX =
+	GCC_TARGET_PREFIX =
   endif
   CC = $(GCC_TARGET_PREFIX)gcc
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.c	(revision 458)
@@ -275,7 +275,6 @@
 	OV2640_t        *hcmr;
 	DVP_Handle_t    *hdvp;
-	uint16_t        *lcd_buffer;
 	ER_UINT	ercd;
-	uint32_t i, count;
+	uint32_t i;
 	struct tm2 time;
 	unsigned long atmp;
@@ -465,10 +464,5 @@
 	lcd_init(hlcd);
 	syslog_2(LOG_NOTICE, "width(%d) height(%d)", hlcd->_width, hlcd->_height);
-	count = hcmr->_width * hcmr->_height;
-	lcd_buffer = (uint16_t *)malloc(count * 2);
-	if(lcd_buffer == NULL){
-		syslog_0(LOG_ERROR, "no lcd buffer !");
-		slp_tsk();
-	}
+
 	DrawProp.BackColor = ST7789_WHITE;
 	DrawProp.TextColor = ST7789_BLACK;
@@ -588,11 +582,5 @@
 			ercd = ov2640_snapshot(hcmr);
 			if(ercd == E_OK){
-				uint32_t *p = (uint32_t *)hcmr->_dataBuffer;
-				uint32_t *q = (uint32_t *)lcd_buffer;
-				uint32_t *e = (uint32_t *)&lcd_buffer[count];
-				for (; q < e ; p++, q++){
-					*q = SWAP_32(*p);
-				}
-				lcd_drawPicture(hlcd, 0, 0, hcmr->_width, hcmr->_height, lcd_buffer);
+				lcd_drawPicture(hlcd, 0, 0, hcmr->_width, hcmr->_height, (uint16_t *)hcmr->_dataBuffer);
 			}
 		}
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.cfg
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.cfg	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/OBJ/K210_GCC/DEMO/demo.cfg	(revision 458)
@@ -11,4 +11,5 @@
 INCLUDE("syssvc/serial.cfg");
 INCLUDE("syssvc/logtask.cfg");
+INCLUDE("syssvc/malloc.cfg");
 INCLUDE("pdic/k210/device.cfg");
 INCLUDE("pdic/k210/dvp.cfg");
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv32elf.ld
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv32elf.ld	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv32elf.ld	(revision 458)
@@ -2,18 +2,4 @@
  *  @(#) $Id$
  */
-
-MEMORY
-{
-  /*
-   * Memory with CPU cache.
-   *6M CPU SRAM
-   */
-  ram (wxa!ri) : ORIGIN = 0x80000000, LENGTH = (6 * 1024 * 1024)
-  /*
-   * Memory without CPU cache
-   * 6M CPU SRAM
-  */
-  ram_nocache (wxa!ri) : ORIGIN = 0x40000000, LENGTH = (6 * 1024 * 1024)
-}
 
 OUTPUT_ARCH(riscv)
@@ -22,6 +8,4 @@
 PROVIDE(software_init_hook = 0);
 PROVIDE(software_term_hook = 0);
-PROVIDE(__idata_start = 0);
-PROVIDE(__idata_end = 0);
 STARTUP(start.o)
 
@@ -33,5 +17,5 @@
     {
         KEEP (*(.init))
-    }>ram
+    }
     .text :
     {
@@ -39,9 +23,9 @@
         *(.text .stub .text.* .gnu.linkonce.t.*)
 
-    }>ram
+    }
     .fini :
     {
         KEEP (*(.fini))
-    }>ram
+    }
     _etext = . ;
     PROVIDE (etext = .) ;
@@ -49,17 +33,17 @@
     {
         *(.rodata .rodata.* .gnu.linkonce.r.*)
-    }>ram
+    }
     . = ALIGN(4) ;
-    .data : 
+    __idata_start = . ;
+    .data : AT(__idata_start)
     {
         __data_start = . ;
-        /* Writable data segment (.data segment) */
         *(.data .data.*)
-        *(.sdata .sdata.* .sdata2 .sdata2.*)
+        *(.sdata .sdata.* .sdata2.*)
         . = ALIGN(8);
-        PROVIDE( __global_pointer$ = ABSOLUTE(.) + 0x800);
-    }>ram
-    .eh_frame : { KEEP (*(.eh_frame)) }>ram
-    .gcc_except_table : { *(.gcc_except_table .gcc_except_table.*) }>ram
+        PROVIDE( __global_pointer$ = . + 0x800 );
+    }
+    .eh_frame : { KEEP (*(.eh_frame)) }
+    .gcc_except_table : { *(.gcc_except_table) }
     .ctors :
     {
@@ -68,5 +52,5 @@
         KEEP (*(SORT(.ctors.*)))
         KEEP (*(.ctors))
-    }>ram
+    }
     .dtors :
     {
@@ -75,29 +59,22 @@
         KEEP (*(SORT(.dtors.*)))
         KEEP (*(.dtors))
-    }>ram
+    }
+    __idata_end = __idata_start + SIZEOF(.data) ;
     _edata  = . ;
     PROVIDE (edata = .) ;
     . = ALIGN(4) ;
     __bss_start = . ;
-    _bss = .;
     .bss :
     {
         *(.bss .bss.*)
-        *(.sbss .sbss.* .sbss2 .sbss2.*)
+        *(.sbss .sbss.* .sbss2.*)
         *(COMMON)
-    }>ram
+    }
     _end = . ;
     __bss_end = . ;
-    _ebss = . ;
-    .stack (NOLOAD) :
+    .stack :
     {
     	*(.stack)
-    }>ram
-    .heap (NOLOAD) :
-    {
-        PROVIDE (_heap_start = .) ;
-        *(.heap)
-    }>ram
-    PROVIDE (_heap_end = .) ;
+    }
     PROVIDE (end = .) ;
     .comment        0 : { *(.comment) }
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv64elf.ld
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv64elf.ld	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/arch/riscv_gcc/riscv64elf.ld	(revision 458)
@@ -2,18 +2,4 @@
  *  @(#) $Id$
  */
-
-MEMORY
-{
-  /*
-   * Memory with CPU cache.
-   *6M CPU SRAM
-   */
-  ram (wxa!ri) : ORIGIN = 0x80000000, LENGTH = (6 * 1024 * 1024)
-  /*
-   * Memory without CPU cache
-   * 6M CPU SRAM
-  */
-  ram_nocache (wxa!ri) : ORIGIN = 0x40000000, LENGTH = (6 * 1024 * 1024)
-}
 
 OUTPUT_ARCH(riscv)
@@ -22,6 +8,4 @@
 PROVIDE(software_init_hook = 0);
 PROVIDE(software_term_hook = 0);
-PROVIDE(__idata_start = 0);
-PROVIDE(__idata_end = 0);
 STARTUP(start.o)
 
@@ -33,5 +17,5 @@
     {
         KEEP (*(.init))
-    }>ram
+    }
     .text :
     {
@@ -39,9 +23,9 @@
         *(.text .stub .text.* .gnu.linkonce.t.*)
 
-    }>ram
+    }
     .fini :
     {
         KEEP (*(.fini))
-    }>ram
+    }
     _etext = . ;
     PROVIDE (etext = .) ;
@@ -49,17 +33,18 @@
     {
         *(.rodata .rodata.* .gnu.linkonce.r.*)
-    }>ram
+    }
     . = ALIGN(8);
-    .data : 
+    __idata_start = . ;
+    .data :
     {
         __data_start = . ;
         /* Writable data segment (.data segment) */
         *(.data .data.*)
-        *(.sdata .sdata.* .sdata2 .sdata2.*)
+        *(.sdata .sdata.* .sdata2.*)
         . = ALIGN(8);
         PROVIDE( __global_pointer$ = ABSOLUTE(.) + 0x800);
-    }>ram
-    .eh_frame : { KEEP (*(.eh_frame)) }>ram
-    .gcc_except_table : { *(.gcc_except_table .gcc_except_table.*) }>ram
+    }
+    .eh_frame : { KEEP (*(.eh_frame)) }
+    .gcc_except_table : { *(.gcc_except_table) }
     .ctors :
     {
@@ -68,5 +53,5 @@
         KEEP (*(SORT(.ctors.*)))
         KEEP (*(.ctors))
-    }>ram
+    }
     .dtors :
     {
@@ -75,29 +60,22 @@
         KEEP (*(SORT(.dtors.*)))
         KEEP (*(.dtors))
-    }>ram
+    }
+    __idata_end = __idata_start + SIZEOF(.data) ;
     _edata  = . ;
     PROVIDE (edata = .) ;
     . = ALIGN(8) ;
     __bss_start = . ;
-    _bss = .;
     .bss :
     {
         *(.bss .bss.*)
-        *(.sbss .sbss.* .sbss2 .sbss2.*)
+        *(.sbss .sbss.* .sbss2.*)
         *(COMMON)
-    }>ram
+    }
     _end = . ;
     __bss_end = . ;
-    _ebss = . ;
-    .stack (NOLOAD) :
+    .stack :
     {
     	*(.stack)
-    }>ram
-    .heap (NOLOAD) :
-    {
-        PROVIDE (_heap_start = .) ;
-        *(.heap)
-    }>ram
-    PROVIDE (_heap_end = .) ;
+    }
     PROVIDE (end = .) ;
     .comment        0 : { *(.comment) }
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_ov2640/sipeed_ov2640.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_ov2640/sipeed_ov2640.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_ov2640/sipeed_ov2640.c	(revision 458)
@@ -750,5 +750,5 @@
 			dly_tsk(1);
 	}
-	reverse_u32pixel((uint32_t*)hcmr->_dataBuffer, hcmr->_width * hcmr->_height/2);
+	//reverse_u32pixel((uint32_t*)hcmr->_dataBuffer, hcmr->_width * hcmr->_height/2);
 	return E_OK;
 }
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_st7789/sipeed_st7789.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_st7789/sipeed_st7789.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/gdic/sipeed_st7789/sipeed_st7789.c	(revision 458)
@@ -83,10 +83,10 @@
 static void set_dcx_control(LCD_Handler_t *hlcd)
 {
-    gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_LOW);
+	gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_LOW);
 }
 
 static void set_dcx_data(LCD_Handler_t *hlcd)
 {
-    gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_HIGH);
+	gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_HIGH);
 }
 
@@ -101,9 +101,9 @@
 
 	aTxBuffer[0] = c;
-    set_dcx_control(hlcd);
+	set_dcx_control(hlcd);
 	hspi->Init.DataSize = 8;
 	hspi->Init.InstLength = 8;
 	hspi->Init.AddrLength = 0;
-    ercd = spi_core_transmit(hspi, hlcd->cs_sel, (uint8_t *)(aTxBuffer), 1);
+	ercd = spi_core_transmit(hspi, hlcd->cs_sel, (uint8_t *)(aTxBuffer), 1);
 #if SPI_WAIT_TIME == 0
 	if(ercd == E_OK)
@@ -128,5 +128,5 @@
 		aTxBuffer[i] = buf[i];
 
-    set_dcx_data(hlcd);
+	set_dcx_data(hlcd);
 	hspi->Init.DataSize = 8;
 	hspi->Init.InstLength = 8;
@@ -146,5 +146,5 @@
 	ER ercd = E_OK;
 
-    set_dcx_data(hlcd);
+	set_dcx_data(hlcd);
 	hspi->Init.DataSize = 8;
 	hspi->Init.InstLength = 8;
@@ -167,5 +167,5 @@
 	ER ercd = E_OK;
 
-    set_dcx_data(hlcd);
+	set_dcx_data(hlcd);
 	hspi->Init.DataSize = 16;
 	hspi->Init.InstLength = 16;
@@ -188,5 +188,5 @@
 	ER ercd = E_OK;
 
-    set_dcx_data(hlcd);
+	set_dcx_data(hlcd);
 	hspi->Init.DataSize = 32;
 	hspi->Init.InstLength = 0;
@@ -206,5 +206,5 @@
 {
 	GPIO_Init_t init = {0};
-    uint8_t data = 0;
+	uint8_t data[2] = {0};
 
 	/*
@@ -214,6 +214,6 @@
 	init.mode = GPIO_MODE_OUTPUT;
 	init.pull = GPIO_PULLDOWN;
-    gpio_setup(TADR_GPIO_BASE, &init, hlcd->dcx_no);
-    gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_HIGH);
+	gpio_setup(TADR_GPIO_BASE, &init, hlcd->dcx_no);
+	gpio_set_pin(TADR_GPIO_BASE, hlcd->dcx_no, PORT_HIGH);
 
 	/*
@@ -227,6 +227,6 @@
 		gpio_set_pin(TADR_GPIO_BASE, hlcd->rst_no, PORT_HIGH);
 
-	    gpio_set_pin(TADR_GPIO_BASE, hlcd->rst_no, 0);
-	    gpio_set_pin(TADR_GPIO_BASE, hlcd->rst_no, 1);
+		gpio_set_pin(TADR_GPIO_BASE, hlcd->rst_no, 0);
+		gpio_set_pin(TADR_GPIO_BASE, hlcd->rst_no, 1);
 	}
 
@@ -245,6 +245,6 @@
 	 */
 	lcd_writecommand(hlcd, PIXEL_FORMAT_SET);
-	data = 0x55;
-    lcd_writebyte(hlcd, &data, 1);
+	data[0] = 0x55;
+	lcd_writebyte(hlcd, &data, 1);
 	if(hlcd->dir & DIR_XY_MASK){
 		hlcd->_width = ST7789_TFTHEIGHT;
@@ -259,5 +259,10 @@
 
 	lcd_writecommand(hlcd, MEMORY_ACCESS_CTL);
-    lcd_writebyte(hlcd, (uint8_t *)&hlcd->dir, 1);
+	lcd_writebyte(hlcd, (uint8_t *)&hlcd->dir, 1);
+
+	//lcd_writecommand(hlcd, RGB_IF_SIGNAL_CTL);
+	//data[0] = 0x00;
+	//data[1] = 0xF8;
+	//lcd_writebyte(hlcd, &data, 2);
 
 	/*
@@ -274,19 +279,19 @@
 lcd_setAddrWindow(LCD_Handler_t *hlcd,  uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
 {
-    uint8_t data[4] = {0};
-
-    data[0] = (uint8_t)(x0 >> 8);
-    data[1] = (uint8_t)(x0);
-    data[2] = (uint8_t)(x1 >> 8);
-    data[3] = (uint8_t)(x1);
+	uint8_t data[4] = {0};
+
+	data[0] = (uint8_t)(x0 >> 8);
+	data[1] = (uint8_t)(x0);
+	data[2] = (uint8_t)(x1 >> 8);
+	data[3] = (uint8_t)(x1);
 	lcd_writecommand(hlcd, HORIZONTAL_ADDRESS_SET);
-    lcd_writebyte(hlcd, data, 4);
-
-    data[0] = (uint8_t)(y0 >> 8);
-    data[1] = (uint8_t)(y0);
-    data[2] = (uint8_t)(y1 >> 8);
-    data[3] = (uint8_t)(y1);
+	lcd_writebyte(hlcd, data, 4);
+
+	data[0] = (uint8_t)(y0 >> 8);
+	data[1] = (uint8_t)(y0);
+	data[2] = (uint8_t)(y1 >> 8);
+	data[3] = (uint8_t)(y1);
 	lcd_writecommand(hlcd, VERTICAL_ADDRESS_SET);
-    lcd_writebyte(hlcd, data, 4);
+	lcd_writebyte(hlcd, data, 4);
 
 	SVC_PERROR(lcd_writecommand(hlcd, MEMORY_WRITE));
@@ -305,5 +310,5 @@
 lcd_fillRect(LCD_Handler_t *hlcd, int16_t x, int16_t y, int16_t w, int16_t h, color_t color)
 {
-    uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
+	uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
 	// rudimentary clipping (drawChar w/big text requires this)
 	if((x >= hlcd->_width) || (y >= hlcd->_height)) return;
@@ -312,5 +317,5 @@
 
 	lcd_setAddrWindow(hlcd, x, y, x+w-1, y+h-1);
-    SVC_PERROR(lcd_filldata(hlcd, &data, (h*w+1)/2));
+	SVC_PERROR(lcd_filldata(hlcd, &data, (h*w+1)/2));
 }
 
@@ -326,5 +331,5 @@
 {
 	uint32_t data = color;
-    lcd_setAddrWindow(hlcd, x, y, x, y);
+	lcd_setAddrWindow(hlcd, x, y, x, y);
 	SVC_PERROR(lcd_writehalf(hlcd, &data, 1));
 }
@@ -341,5 +346,5 @@
 lcd_drawFastVLine(LCD_Handler_t *hlcd, int16_t x, int16_t y, int16_t h, color_t color)
 {
-    uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
+	uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
 	// Rudimentary clipping
 	if(h == 0) return;
@@ -347,5 +352,5 @@
 	if((y+h-1) >= hlcd->_height) h = hlcd->_height-y;
 	lcd_setAddrWindow(hlcd, x, y, x, y+h-1);
-    SVC_PERROR(lcd_filldata(hlcd, &data, (h+1)/2));
+	SVC_PERROR(lcd_filldata(hlcd, &data, (h+1)/2));
 }
 
@@ -360,5 +365,5 @@
 void lcd_drawFastHLine(LCD_Handler_t *hlcd, int16_t x, int16_t y, int16_t w, color_t color)
 {
-    uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
+	uint32_t data = ((uint32_t)color << 16) | (uint32_t)color;
 	// Rudimentary clipping
 	if(w == 0) return;
@@ -366,5 +371,5 @@
 	if((x+w-1) >= hlcd->_width)  w = hlcd->_width-x;
 	lcd_setAddrWindow(hlcd, x, y, x+w-1, y);
-    SVC_PERROR(lcd_filldata(hlcd, &data, (w+1)/2));
+	SVC_PERROR(lcd_filldata(hlcd, &data, (w+1)/2));
 }
 
@@ -462,5 +467,5 @@
 
 	lcd_setAddrWindow(hlcd, x, y, x+width-1, y+height-1);
-    set_dcx_data(hlcd);
+	set_dcx_data(hlcd);
 	hspi->Init.DataSize = 32;
 	hspi->Init.InstLength = 0;
@@ -533,5 +538,5 @@
 {
 	LCD_Handler_t *hlcd = pDrawProp->hlcd;
- 	int32_t   decision;    /* Decision Variable */ 
+	int32_t   decision;    /* Decision Variable */ 
 	uint32_t  current_x;   /* Current X Value */
 	uint32_t  current_y;   /* Current Y Value */
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/dvp.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/dvp.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/dvp.c	(revision 458)
@@ -66,5 +66,5 @@
 
 #define DEAFULT_CLEAR_INT       (DVP_STS_FRAME_START  | DVP_STS_FRAME_START_WE | \
-                                 DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE)
+								 DVP_STS_FRAME_FINISH | DVP_STS_FRAME_FINISH_WE)
 
 
@@ -75,6 +75,6 @@
 {
 	uint32_t clk_sel0 = sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_CLK_SEL0));
-    uint32_t source = 0;
-    uint32_t result = 0;
+	uint32_t source = 0;
+	uint32_t result = 0;
 	uint32_t threshold = 0;
 
@@ -97,5 +97,5 @@
 	result = source / (threshold + 1);
 	syslog_2(LOG_NOTICE, "## dvp_clock_get_freq req(%d) result(%d) ##", clock, result);
-    return result;
+	return result;
 }
 
@@ -104,8 +104,8 @@
 {
 	while(sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS)) & DVP_STS_SCCB_EN)
-        ;
+		;
 	sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS), (DVP_STS_SCCB_EN | DVP_STS_SCCB_EN_WE));
-    while (sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS)) & DVP_STS_SCCB_EN)
-        ;
+	while (sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS)) & DVP_STS_SCCB_EN)
+		;
 }
 
@@ -150,5 +150,5 @@
 	tmp = sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CFG)) & (~DVP_SCCB_BYTE_NUM_MASK);
 
-    if (hdvp->Init.num_sccb_reg == 8)
+	if (hdvp->Init.num_sccb_reg == 8)
 		tmp |= DVP_SCCB_BYTE_NUM_2;
 	else
@@ -164,9 +164,9 @@
 	sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CTL), tmp);
 
-    dvp_sccb_start_transfer(hdvp);
+	dvp_sccb_start_transfer(hdvp);
 
 	sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CTL), addr);
 
-    dvp_sccb_start_transfer(hdvp);
+	dvp_sccb_start_transfer(hdvp);
 
 	tmp = sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CFG));
@@ -182,5 +182,5 @@
 dvp_init(DVP_Handle_t *hdvp)
 {
-    uint32_t v_apb1_clk, v_period;
+	uint32_t v_apb1_clk, v_period;
 
 	if(hdvp == NULL)
@@ -201,10 +201,10 @@
 	fpioa_set_function(hdvp->Init.SccbSdaPin, FUNC_SCCB_SDA);
 
-    /* Do a power cycle */
-    dvp_dcmi_powerdown(hdvp, false);
-    dly_tsk(10);
-
-    dvp_dcmi_powerdown(hdvp, true);
-    dly_tsk(100);
+	/* Do a power cycle */
+	dvp_dcmi_powerdown(hdvp, false);
+	dly_tsk(10);
+
+	dvp_dcmi_powerdown(hdvp, true);
+	dly_tsk(100);
 
 	/*
@@ -372,12 +372,12 @@
 	cfg  = sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_CFG));
 	cfg &= ~(DVP_CFG_HREF_BURST_NUM_MASK | DVP_CFG_LINE_NUM_MASK);
-    cfg |= hdvp->Init.Height << 20;
-
-    if((cfg & DVP_CFG_BURST_SIZE_4BEATS) != 0)
+	cfg |= hdvp->Init.Height << 20;
+
+	if((cfg & DVP_CFG_BURST_SIZE_4BEATS) != 0)
 		divw = 4;
 	else
 		divw = 1;
 	cfg |= (hdvp->Init.Width / 8 / divw) << 12;
-    sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_CFG), cfg);
+	sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_CFG), cfg);
 	return E_OK;
 }
@@ -403,6 +403,6 @@
 
 	sccb_cfg  = sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CFG));
-    sccb_cfg &= ~(DVP_SCCB_SCL_LCNT_MASK | DVP_SCCB_SCL_HCNT_MASK);
-    sccb_cfg |= (v_period_clk_cnt << 8) | (v_period_clk_cnt << 16);
+	sccb_cfg &= ~(DVP_SCCB_SCL_LCNT_MASK | DVP_SCCB_SCL_HCNT_MASK);
+	sccb_cfg |= (v_period_clk_cnt << 8) | (v_period_clk_cnt << 16);
 	sil_wrw_mem((uint32_t *)(hdvp->base+TOFF_DVP_SCCB_CFG), sccb_cfg);
 	return dvp_clock_get_freq(DVP_CLOCK_REQ) / (v_period_clk_cnt * 2);
@@ -454,11 +454,15 @@
 	uint32_t istatus, estatus;
 
-	if(hdvp == NULL)
+	if (hdvp == NULL) {
+		syslog_0(LOG_NOTICE, "dvp_handler hdvp == NULL");
 		return;
+	}
 	istatus = sil_rew_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS));
-	if(istatus == 0)
+	if (istatus == 0) {
+		syslog_0(LOG_DEBUG, "dvp_handler istatus == 0");
 		return;
+	}
 	estatus = istatus;
-	syslog_2(LOG_DEBUG, "sensor_irq istatus[%08x] hdvp->state(%d)", istatus, hdvp->state);
+	syslog_2(LOG_DEBUG, "dvp_handler istatus[%08x] hdvp->state(%d)", istatus, hdvp->state);
 	if((istatus & DVP_STS_FRAME_FINISH) != 0){	//frame end
 		estatus |= DVP_STS_FRAME_FINISH_WE;
@@ -469,5 +473,5 @@
 	if((istatus & DVP_STS_FRAME_START) != 0){	//frame start
 		estatus |= DVP_STS_FRAME_START_WE;
-        if(hdvp->state == DVP_STATE_ACTIVATE){  //only we finish the convert, do transmit again
+		if(hdvp->state == DVP_STATE_ACTIVATE){  //only we finish the convert, do transmit again
 			/*
 			 *  コンバートスタート
@@ -479,4 +483,2 @@
 	sil_orw_mem((uint32_t *)(hdvp->base+TOFF_DVP_STS), estatus);
 }
-
-
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.c	(revision 458)
@@ -56,26 +56,26 @@
 sil_rel_mem(const uint64_t *mem)
 {
-	uint64_t	data;
-
-	data = *((const volatile uint64_t *) mem);
-	return(data);
-}
-
-#define sil_orw_mem(a, b)		sil_wrw_mem((a), sil_rew_mem(a) | (b))
-#define sil_andw_mem(a, b)		sil_wrw_mem((a), sil_rew_mem(a) & ~(b))
-#define sil_modw_mem(a, b, c)	sil_wrw_mem((a), (sil_rew_mem(a) & (~b)) | (c))
+	uint64_t data;
+
+	data = *((const volatile uint64_t *)mem);
+	return (data);
+}
+
+#define sil_orw_mem(a, b) sil_wrw_mem((a), sil_rew_mem(a) | (b))
+#define sil_andw_mem(a, b) sil_wrw_mem((a), sil_rew_mem(a) & ~(b))
+#define sil_modw_mem(a, b, c) sil_wrw_mem((a), (sil_rew_mem(a) & (~b)) | (c))
 
 /*
  *  SPIOポートIDから管理ブロックを取り出すためのマクロ
  */
-#define INDEX_SPI(spiid)        ((uint_t)((spiid) - 1))
-
-#define get_framewidth(l)       (((l)+7)/8)
-
-#define SPI_SSIENR_DISABLE      0x00000000
-#define SPI_SSIENR_ENABLE       0x00000001
-
-#define SPI_DMACR_RXENABLE      0x00000001
-#define SPI_DMACR_TXENABLE      0x00000002
+#define INDEX_SPI(spiid) ((uint_t)((spiid)-1))
+
+#define get_framewidth(l) (((l) + 7) / 8)
+
+#define SPI_SSIENR_DISABLE 0x00000000
+#define SPI_SSIENR_ENABLE 0x00000001
+
+#define SPI_DMACR_RXENABLE 0x00000001
+#define SPI_DMACR_TXENABLE 0x00000002
 
 /*
@@ -83,17 +83,17 @@
  */
 
-typedef struct _SPI_PortControlBlock{
-	unsigned long         base;
-	int16_t               func_data;
-	int16_t               func_ss;
-	int16_t               func_arb;
-	int16_t               func_sclk;
+typedef struct _SPI_PortControlBlock {
+	unsigned long base;
+	int16_t func_data;
+	int16_t func_ss;
+	int16_t func_arb;
+	int16_t func_sclk;
 } SPI_PortControlBlock;
 
 static const SPI_PortControlBlock spi_pcb[NUM_SPIPORT] = {
-	{TADR_SPI0_BASE, FUNC_SPI0_D0,      FUNC_SPI0_SS0,     FUNC_SPI0_ARB, FUNC_SPI0_SCLK     },
-	{TADR_SPI1_BASE, FUNC_SPI1_D0,      FUNC_SPI1_SS0,     FUNC_SPI1_ARB, FUNC_SPI1_SCLK     },
+	{TADR_SPI0_BASE, FUNC_SPI0_D0,      FUNC_SPI0_SS0,     FUNC_SPI0_ARB, FUNC_SPI0_SCLK},
+	{TADR_SPI1_BASE, FUNC_SPI1_D0,      FUNC_SPI1_SS0,     FUNC_SPI1_ARB, FUNC_SPI1_SCLK},
 	{TADR_SPIS_BASE, FUNC_SPI_SLAVE_D0, FUNC_SPI_SLAVE_SS, -1,            FUNC_SPI_SLAVE_SCLK},
-	{TADR_SPI2_BASE, -1,                -1,                -1,            -1                 }
+	{TADR_SPI2_BASE, -1,                -1,                -1,            -1}
 };
 
@@ -109,9 +109,9 @@
 {
 	SPI_Init_t *init;
-    uint32_t inst_l = 4;
-    uint32_t addr_l;
+	uint32_t inst_l = 4;
+	uint32_t addr_l;
 
 	init = &hspi->Init;
-    switch (init->InstLength){
+	switch (init->InstLength) {
 	case 0:
 		inst_l = 0;
@@ -128,14 +128,14 @@
 	default:
 		break;
-    }
-	if(inst_l == 4)
+	}
+	if (inst_l == 4)
 		return E_PAR;
 
 	addr_l = init->AddrLength / 4;
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_CTRLR0), (init->WorkMode << hspi->work_mode_offset) | \
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_CTRLR0), (init->WorkMode << hspi->work_mode_offset) |
 		(init->FrameFormat << hspi->frf_offset) | ((init->DataSize - 1) << hspi->dfs_offset));
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SPI_CTRLR0),
-		((init->WaitCycles << 11) | (inst_l << 8) | (addr_l << 2) | init->IATransMode));
-	sil_modw_mem((uint32_t *)(hspi->base+TOFF_SPI_CTRLR0), (3 << hspi->tmod_offset), (tmod << hspi->tmod_offset));
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SPI_CTRLR0),
+				((init->WaitCycles << 11) | (inst_l << 8) | (addr_l << 2) | init->IATransMode));
+	sil_modw_mem((uint32_t *)(hspi->base + TOFF_SPI_CTRLR0), (3 << hspi->tmod_offset), (tmod << hspi->tmod_offset));
 	return E_OK;
 }
@@ -148,5 +148,5 @@
 {
 	SPI_Handle_t *hspi = (SPI_Handle_t *)hdma->localdata;
-	if(hspi != NULL && hspi->Init.semdmaid != 0){
+	if (hspi != NULL && hspi->Init.semdmaid != 0) {
 		isig_sem(hspi->Init.semdmaid);
 	}
@@ -158,39 +158,39 @@
 DMA_Handle_t *
 spi_dmac_set_single_mode(SPI_Handle_t *hspi, uint8_t rtx,
-						  int8_t  ss_no, const void *src, void *dest,
-						  uint8_t src_inc, uint8_t dest_inc,
-                          uint8_t dmac_burst_size, uint8_t dmac_trans_width,
-                          size_t block_size)
+						 int8_t ss_no, const void *src, void *dest,
+						 uint8_t src_inc, uint8_t dest_inc,
+						 uint8_t dmac_burst_size, uint8_t dmac_trans_width,
+						 size_t block_size)
 {
 	DMA_Handle_t *hdma;
-    int mem_type_src, mem_type_dest;
-    uint8_t flow_control;
-
-	if(rtx == 0){
+	int mem_type_src, mem_type_dest;
+	uint8_t flow_control;
+
+	if (rtx == 0) {
 		hdma = hspi->hdmatx;
-        flow_control = DMA_MEMORY_TO_PERIPH;
+		flow_control = DMA_MEMORY_TO_PERIPH;
 		mem_type_src = 1;
 		mem_type_dest = 0;
 	}
-	else{
+	else {
 		hdma = hspi->hdmarx;
-        flow_control = DMA_PERIPH_TO_MEMORY;
+		flow_control = DMA_PERIPH_TO_MEMORY;
 		mem_type_src = 0;
 		mem_type_dest = 1;
 	}
-	if(ss_no < 0)
+	if (ss_no < 0)
 		ss_no = 0;
 
-	hdma->Init.Direction    = flow_control;	/* DMA転送方向 */
-	hdma->Init.SrcHandShake = (mem_type_src ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	/* ソースハンドシェイク */
-	hdma->Init.DrcHandShake = (mem_type_dest ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	/* デスティネーションハンドシェイク */
-	hdma->Init.SrcInc       = src_inc;	/* ソースインクリメント設定 */
-	hdma->Init.DstInc       = dest_inc;	/* デスティネーションインクリメント設定 */
-	hdma->Init.SrcTransWidth = dmac_trans_width;	/* ソース転送幅 */
-	hdma->Init.DstTransWidth = dmac_trans_width;	/* デスティネーション転送幅 */
-	hdma->Init.SrcBurstSize = dmac_burst_size;	/* ソースバーストサイズ */
-	hdma->Init.DstBurstSize = dmac_burst_size;	/* デスティネーションバーストサイズ */
+	hdma->Init.Direction = flow_control;											 /* DMA転送方向 */
+	hdma->Init.SrcHandShake = (mem_type_src ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE);	 /* ソースハンドシェイク */
+	hdma->Init.DrcHandShake = (mem_type_dest ? DMAC_HS_SOFTWARE : DMAC_HS_HARDWARE); /* デスティネーションハンドシェイク */
+	hdma->Init.SrcInc = src_inc;													 /* ソースインクリメント設定 */
+	hdma->Init.DstInc = dest_inc;													 /* デスティネーションインクリメント設定 */
+	hdma->Init.SrcTransWidth = dmac_trans_width;									 /* ソース転送幅 */
+	hdma->Init.DstTransWidth = dmac_trans_width;									 /* デスティネーション転送幅 */
+	hdma->Init.SrcBurstSize = dmac_burst_size;										 /* ソースバーストサイズ */
+	hdma->Init.DstBurstSize = dmac_burst_size;										 /* デスティネーションバーストサイズ */
 	dma_reset(hdma);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SER), (1 << ss_no));
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), (1 << ss_no));
 	dma_start(hdma, (uintptr_t)src, (uintptr_t)dest, block_size);
 	return hdma;
@@ -201,5 +201,5 @@
  */
 ER
-spi_dmac_wait_done(DMA_Handle_t * hdma)
+spi_dmac_wait_done(DMA_Handle_t *hdma)
 {
 	SPI_Handle_t *hspi = (SPI_Handle_t *)hdma->localdata;
@@ -207,7 +207,7 @@
 	int tick = DMA_TRS_TIMEOUT;
 
-	while((hdma->status == DMA_STATUS_BUSY) && tick > 0){
-		if(hspi != NULL && hspi->Init.semdmaid != 0){
-	 		ercd = twai_sem(hspi->Init.semdmaid, 5);
+	while ((hdma->status == DMA_STATUS_BUSY) && tick > 0) {
+		if (hspi != NULL && hspi->Init.semdmaid != 0) {
+			ercd = twai_sem(hspi->Init.semdmaid, 5);
 		}
 		else
@@ -216,7 +216,7 @@
 	}
 	dma_end(hdma);
-	if(hdma->ErrorCode != 0)
+	if (hdma->ErrorCode != 0)
 		ercd = E_OBJ;
-	else if(tick == 0)
+	else if (tick == 0)
 		ercd = E_TMOUT;
 	return ercd;
@@ -232,18 +232,20 @@
 	int tick = timeout;
 
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR), 0x0011);
-    while((sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_SR)) & 0x05) != 0x04 && tick > 0){
-		if(hspi->Init.semid != 0)
-			twai_sem(hspi->Init.semid, 5);
-		else
-			dly_tsk(1);
-		tick--;
-	}
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SER), 0x00000000);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
-
-	if(hspi->ErrorCode != 0)
+	if (hspi->hdmatx != NULL) {
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_IMR), 0x0011);
+		while ((sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_SR)) & 0x05) != 0x04 && tick > 0) {
+			if (hspi->Init.semid != 0)
+				twai_sem(hspi->Init.semid, 5);
+			else
+				dly_tsk(1);
+			tick--;
+		}
+	}
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), 0x00000000);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
+
+	if (hspi->ErrorCode != 0)
 		ercd = E_OBJ;
-	else if(tick == 0)
+	else if (tick == 0)
 		ercd = E_TMOUT;
 	hspi->TxXferCount = 0;
@@ -266,19 +268,19 @@
 	const SPI_PortControlBlock *spcb;
 	unsigned long base;
-	uint8_t  spi_num;
+	uint8_t spi_num;
 	uint32_t spi_baudr, clk_th1, threshold;
-    uint8_t  dfs_offset, frf_offset, work_mode_offset, tmod_offset;
+	uint8_t dfs_offset, frf_offset, work_mode_offset, tmod_offset;
 	uint32_t dsize_err = 0;
-    uint32_t inst_l = 4;
-    uint32_t addr_l;
-
-	if(port < SPI1_PORTID || port > NUM_SPIPORT)
+	uint32_t inst_l = 4;
+	uint32_t addr_l;
+
+	if (port < SPI1_PORTID || port > NUM_SPIPORT)
 		return NULL;
 	spi_num = INDEX_SPI(port);
-	if(init == NULL)
+	if (init == NULL)
 		return NULL;
-	if(init->DataSize < 4 && init->DataSize > 32)
+	if (init->DataSize < 4 && init->DataSize > 32)
 		return NULL;
-	if(init->AddrLength % 4 != 0 && init->AddrLength > 60)
+	if (init->AddrLength % 4 != 0 && init->AddrLength > 60)
 		return NULL;
 
@@ -286,13 +288,13 @@
 	 *  クロック設定
 	 */
-    if(spi_num == 3){
-		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_CLK_SEL0), SYSCTL_CLK_SEL0_SPI3_CLK_SEL);
-	}
-	if(spi_num < 2)
-		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_CENT), SYSCTL_CLK_EN_CENT_APB2_CLK_EN);
-	else if(spi_num == 2)
-		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_CENT), SYSCTL_CLK_EN_CENT_APB0_CLK_EN);
-	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_PERI), (SYSCTL_CLK_EN_PERI_SPI0_CLK_EN<<spi_num));
-	sil_andw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_TH1), 0xFF << (spi_num*8));
+	if (spi_num == 3) {
+		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_CLK_SEL0), SYSCTL_CLK_SEL0_SPI3_CLK_SEL);
+	}
+	if (spi_num < 2)
+		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_CENT), SYSCTL_CLK_EN_CENT_APB2_CLK_EN);
+	else if (spi_num == 2)
+		sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_CENT), SYSCTL_CLK_EN_CENT_APB0_CLK_EN);
+	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_PERI), (SYSCTL_CLK_EN_PERI_SPI0_CLK_EN << spi_num));
+	sil_andw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_TH1), 0xFF << (spi_num * 8));
 
 	/*
@@ -300,19 +302,18 @@
 	 */
 	spcb = &spi_pcb[spi_num];
-	if(spcb->func_ss >= 0 && init->SsPin >= 0)
+	if (spcb->func_ss >= 0 && init->SsPin >= 0)
 		fpioa_set_function(init->SsPin, (uint8_t)(spcb->func_ss + init->SsNo));
-	if(spcb->func_sclk >= 0 && init->SclkPin >= 0)
+	if (spcb->func_sclk >= 0 && init->SclkPin >= 0)
 		fpioa_set_function(init->SclkPin, (uint8_t)(spcb->func_sclk));
-	if(spcb->func_data >= 0){
-		if(init->MosiPin >= 0)
+	if (spcb->func_data >= 0) {
+		if (init->MosiPin >= 0)
 			fpioa_set_function(init->MosiPin, (uint8_t)(spcb->func_data));
-		if(init->MisoPin >= 0)
-			fpioa_set_function(init->MisoPin, (uint8_t)(spcb->func_data+1));
-
+		if (init->MisoPin >= 0)
+			fpioa_set_function(init->MisoPin, (uint8_t)(spcb->func_data + 1));
 	}
 	hspi = &SpiHandle[spi_num];
 	base = spcb->base;
 
-    switch(spi_num){
+	switch (spi_num) {
 	case 0:
 	case 1:
@@ -331,15 +332,15 @@
 	}
 
-	switch(init->FrameFormat){
+	switch (init->FrameFormat) {
 	case SPI_FF_DUAL:
-		if(init->DataSize % 2 != 0)
+		if (init->DataSize % 2 != 0)
 			dsize_err = 1;
 		break;
 	case SPI_FF_QUAD:
-		if(init->DataSize % 4 != 0)
+		if (init->DataSize % 4 != 0)
 			dsize_err = 1;
 		break;
 	case SPI_FF_OCTAL:
-		if(init->DataSize % 8 != 0)
+		if (init->DataSize % 8 != 0)
 			dsize_err = 1;
 		break;
@@ -348,5 +349,5 @@
 	}
 
-	switch(init->InstLength){
+	switch (init->InstLength) {
 	case 0:
 		inst_l = 0;
@@ -364,5 +365,5 @@
 		break;
 	}
-	if(inst_l == 4 || dsize_err){
+	if (inst_l == 4 || dsize_err) {
 		syslog_0(LOG_ERROR, "Invalid instruction length");
 		return NULL;
@@ -372,37 +373,36 @@
 	memcpy(&hspi->Init, init, sizeof(SPI_Init_t));
 
-    if(sil_rew_mem((uint32_t *)(base+TOFF_SPI_BAUDR)) == 0)
-		sil_wrw_mem((uint32_t *)(base+TOFF_SPI_BAUDR), 0x14);
+	if (sil_rew_mem((uint32_t *)(base + TOFF_SPI_BAUDR)) == 0)
+		sil_wrw_mem((uint32_t *)(base + TOFF_SPI_BAUDR), 0x14);
 	/*
 	 *  割込み不許可
 	 */
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_IMR), 0x00000000);
-
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_DMACR), 0x00000000);
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_DMATDLR), 0x00000010);
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_DMARDLR), 0x00000000);
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_SER), 0x00000000);
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_CTRLR0), (init->WorkMode << work_mode_offset) | \
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_IMR), 0x00000000);
+
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_DMACR), 0x00000000);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_DMATDLR), 0x00000010);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_DMARDLR), 0x00000000);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_SER), 0x00000000);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_CTRLR0), (init->WorkMode << work_mode_offset) |
 		(init->FrameFormat << frf_offset) | ((init->DataSize - 1) << dfs_offset));
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_SPI_CTRLR0),
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_SPI_CTRLR0),
 		((init->WaitCycles << 11) | (inst_l << 8) | (addr_l << 2) | init->IATransMode));
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_ENDIAN), init->SignBit);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_ENDIAN), init->SignBit);
 
 	/*
 	 *  転送クロック設定
 	 */
-	clk_th1 = sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_TH1));
+	clk_th1 = sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_TH1));
 	threshold = (clk_th1 >> (spi_num * 8)) & 0xff;
 	spi_baudr = (get_pll_clock(0) / ((threshold + 1) * 2)) / init->Prescaler;
 
-
-	if(spi_baudr < 2 ){
+	if (spi_baudr < 2) {
 		spi_baudr = 2;
 	}
-	else if(spi_baudr > 65534){
+	else if (spi_baudr > 65534) {
 		spi_baudr = 65534;
 	}
-	sil_wrw_mem((uint32_t *)(base+TOFF_SPI_BAUDR), spi_baudr);
+	sil_wrw_mem((uint32_t *)(base + TOFF_SPI_BAUDR), spi_baudr);
 
 	/*
@@ -411,69 +411,69 @@
 	hspi->base = base;
 	hspi->spi_num = spi_num;
-	hspi->dfs_offset  = dfs_offset;
-	hspi->frf_offset  = frf_offset;
+	hspi->dfs_offset = dfs_offset;
+	hspi->frf_offset = frf_offset;
 	hspi->work_mode_offset = work_mode_offset;
 	hspi->tmod_offset = tmod_offset;
 	hspi->hdmatx = NULL;
 	hspi->hdmarx = NULL;
-	if(init->TxDMAChannel >= 0){
+	if (init->TxDMAChannel >= 0) {
 		hdma = &spi_dma_handle[init->TxDMAChannel][0];
 		hdma->chnum = init->TxDMAChannel;
-		if(init->RxDMAChannel >= 0)
-			hdma->xfercallback      = NULL;
+		if (init->RxDMAChannel >= 0)
+			hdma->xfercallback = NULL;
 		else
-			hdma->xfercallback      = spi_dma_comp;
-		hdma->errorcallback     = NULL;
-		hdma->Init.Request      = DMA_SELECT_SSI0_TX_REQ + spi_num * 2;	/* DMA選択 */
-		hdma->Init.Direction    = DMA_MEMORY_TO_PERIPH;	/* DMA転送方向 */
-		hdma->Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;	/* ソースマルチブロックタイプ */
-		hdma->Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;	/* デスティネーションマルチブロックタイプ */
-		hdma->Init.SrcHandShake = DMAC_HS_SOFTWARE;	/* ソースハンドシェイク */
-		hdma->Init.DrcHandShake = DMAC_HS_HARDWARE;	/* デスティネーションハンドシェイク */
-		hdma->Init.SrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* ソースハードウェアハンドシェイク極性 */
-		hdma->Init.DrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* デスティネーションハードウェアハンドシェイク極性 */
-		hdma->Init.Priority     = 4;	/* 優先度 */
-		hdma->Init.SrcMaster    = DMAC_MASTER1;	/* ソースマスター設定 */
-		hdma->Init.DstMaster    = DMAC_MASTER2;	/* デスティネーションマスター設定 */
-		hdma->Init.SrcInc       = DMAC_ADDR_INCREMENT;	/* ソースインクリメント設定 */
-		hdma->Init.DstInc       = DMAC_ADDR_NOCHANGE;	/* デスティネーションインクリメント設定 */
-		hdma->Init.SrcTransWidth = DMAC_TRANS_WIDTH_32;	/* ソース転送幅 */
-		hdma->Init.DstTransWidth = DMAC_TRANS_WIDTH_32;	/* デスティネーション転送幅 */
-		hdma->Init.SrcBurstSize = DMAC_MSIZE_4;	/* ソースバーストサイズ */
-		hdma->Init.DstBurstSize = DMAC_MSIZE_4;	/* デスティネーションバーストサイズ */
-		hdma->Init.IocBlkTrans  = 0;	/* IOCブロック転送 */
-		hdma->localdata         = (void *)hspi;
+			hdma->xfercallback = spi_dma_comp;
+		hdma->errorcallback = NULL;
+		hdma->Init.Request = DMA_SELECT_SSI0_TX_REQ + spi_num * 2; /* DMA選択 */
+		hdma->Init.Direction = DMA_MEMORY_TO_PERIPH;			   /* DMA転送方向 */
+		hdma->Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;			   /* ソースマルチブロックタイプ */
+		hdma->Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;			   /* デスティネーションマルチブロックタイプ */
+		hdma->Init.SrcHandShake = DMAC_HS_SOFTWARE;				   /* ソースハンドシェイク */
+		hdma->Init.DrcHandShake = DMAC_HS_HARDWARE;				   /* デスティネーションハンドシェイク */
+		hdma->Init.SrcHwhsPol = DMAC_HWHS_POLARITY_LOW;			   /* ソースハードウェアハンドシェイク極性 */
+		hdma->Init.DrcHwhsPol = DMAC_HWHS_POLARITY_LOW;			   /* デスティネーションハードウェアハンドシェイク極性 */
+		hdma->Init.Priority = 4;								   /* 優先度 */
+		hdma->Init.SrcMaster = DMAC_MASTER1;					   /* ソースマスター設定 */
+		hdma->Init.DstMaster = DMAC_MASTER2;					   /* デスティネーションマスター設定 */
+		hdma->Init.SrcInc = DMAC_ADDR_INCREMENT;				   /* ソースインクリメント設定 */
+		hdma->Init.DstInc = DMAC_ADDR_NOCHANGE;					   /* デスティネーションインクリメント設定 */
+		hdma->Init.SrcTransWidth = DMAC_TRANS_WIDTH_32;			   /* ソース転送幅 */
+		hdma->Init.DstTransWidth = DMAC_TRANS_WIDTH_32;			   /* デスティネーション転送幅 */
+		hdma->Init.SrcBurstSize = DMAC_MSIZE_4;					   /* ソースバーストサイズ */
+		hdma->Init.DstBurstSize = DMAC_MSIZE_4;					   /* デスティネーションバーストサイズ */
+		hdma->Init.IocBlkTrans = 0;								   /* IOCブロック転送 */
+		hdma->localdata = (void *)hspi;
 		dma_init(hdma);
 		hspi->hdmatx = hdma;
 	}
-	if(init->RxDMAChannel >= 0){
+	if (init->RxDMAChannel >= 0) {
 		hdma = &spi_dma_handle[init->RxDMAChannel][1];
 		hdma->chnum = init->RxDMAChannel;
-		hdma->xfercallback      = spi_dma_comp;
-		hdma->errorcallback     = NULL;
-		hdma->Init.Request      = DMA_SELECT_SSI0_RX_REQ + spi_num * 2;	/* DMA選択 */
-		hdma->Init.Direction    = DMA_PERIPH_TO_MEMORY;	/* DMA転送方向 */
-		hdma->Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;	/* ソースマルチブロックタイプ */
-		hdma->Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;	/* デスティネーションマルチブロックタイプ */
-		hdma->Init.SrcHandShake = DMAC_HS_HARDWARE;	/* ソースハンドシェイク */
-		hdma->Init.DrcHandShake = DMAC_HS_SOFTWARE;	/* デスティネーションハンドシェイク */
-		hdma->Init.SrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* ソースハードウェアハンドシェイク極性 */
-		hdma->Init.DrcHwhsPol   = DMAC_HWHS_POLARITY_LOW;	/* デスティネーションハードウェアハンドシェイク極性 */
-		hdma->Init.Priority     = 4;	/* 優先度 */
-		hdma->Init.SrcMaster    = DMAC_MASTER1;	/* ソースマスター設定 */
-		hdma->Init.DstMaster    = DMAC_MASTER2;	/* デスティネーションマスター設定 */
-		hdma->Init.SrcInc       = DMAC_ADDR_NOCHANGE;	/* ソースインクリメント設定 */
-		hdma->Init.DstInc       = DMAC_ADDR_INCREMENT;	/* デスティネーションインクリメント設定 */
-		hdma->Init.SrcTransWidth = DMAC_TRANS_WIDTH_32;	/* ソース転送幅 */
-		hdma->Init.DstTransWidth = DMAC_TRANS_WIDTH_32;	/* デスティネーション転送幅 */
-		hdma->Init.SrcBurstSize = DMAC_MSIZE_4;	/* ソースバーストサイズ */
-		hdma->Init.DstBurstSize = DMAC_MSIZE_4;	/* デスティネーションバーストサイズ */
-		hdma->Init.IocBlkTrans  = 0;	/* IOCブロック転送 */
-		hdma->localdata         = (void *)hspi;
+		hdma->xfercallback = spi_dma_comp;
+		hdma->errorcallback = NULL;
+		hdma->Init.Request = DMA_SELECT_SSI0_RX_REQ + spi_num * 2; /* DMA選択 */
+		hdma->Init.Direction = DMA_PERIPH_TO_MEMORY;			   /* DMA転送方向 */
+		hdma->Init.SrcMultBlock = DMAC_MULTBLOCK_CONT;			   /* ソースマルチブロックタイプ */
+		hdma->Init.DrcMultBlock = DMAC_MULTBLOCK_CONT;			   /* デスティネーションマルチブロックタイプ */
+		hdma->Init.SrcHandShake = DMAC_HS_HARDWARE;				   /* ソースハンドシェイク */
+		hdma->Init.DrcHandShake = DMAC_HS_SOFTWARE;				   /* デスティネーションハンドシェイク */
+		hdma->Init.SrcHwhsPol = DMAC_HWHS_POLARITY_LOW;			   /* ソースハードウェアハンドシェイク極性 */
+		hdma->Init.DrcHwhsPol = DMAC_HWHS_POLARITY_LOW;			   /* デスティネーションハードウェアハンドシェイク極性 */
+		hdma->Init.Priority = 4;								   /* 優先度 */
+		hdma->Init.SrcMaster = DMAC_MASTER1;					   /* ソースマスター設定 */
+		hdma->Init.DstMaster = DMAC_MASTER2;					   /* デスティネーションマスター設定 */
+		hdma->Init.SrcInc = DMAC_ADDR_NOCHANGE;					   /* ソースインクリメント設定 */
+		hdma->Init.DstInc = DMAC_ADDR_INCREMENT;				   /* デスティネーションインクリメント設定 */
+		hdma->Init.SrcTransWidth = DMAC_TRANS_WIDTH_32;			   /* ソース転送幅 */
+		hdma->Init.DstTransWidth = DMAC_TRANS_WIDTH_32;			   /* デスティネーション転送幅 */
+		hdma->Init.SrcBurstSize = DMAC_MSIZE_4;					   /* ソースバーストサイズ */
+		hdma->Init.DstBurstSize = DMAC_MSIZE_4;					   /* デスティネーションバーストサイズ */
+		hdma->Init.IocBlkTrans = 0;								   /* IOCブロック転送 */
+		hdma->localdata = (void *)hspi;
 		dma_init(hdma);
 		hspi->hdmarx = hdma;
 	}
 	hspi->status = SPI_STATUS_READY;
-	hspi->xmode  = 0;
+	hspi->xmode = 0;
 	return hspi;
 }
@@ -487,16 +487,16 @@
 spi_deinit(SPI_Handle_t *hspi)
 {
-	if(hspi == NULL)
+	if (hspi == NULL)
 		return E_PAR;
 
-	if(hspi->hdmatx != NULL){
+	if (hspi->hdmatx != NULL) {
 		dma_deinit(hspi->hdmatx);
 		hspi->hdmatx = NULL;
 	}
-	if(hspi->hdmarx != NULL){
+	if (hspi->hdmarx != NULL) {
 		dma_deinit(hspi->hdmarx);
 		hspi->hdmarx = NULL;
 	}
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
 
 	hspi->ErrorCode = SPI_ERROR_NONE;
@@ -509,58 +509,79 @@
  */
 static void
-spi_send_data_normal2(SPI_Handle_t *hspi, int8_t ss_no, const uint8_t *tx_buff, size_t tx_len)
-{
-	size_t index, fifo_len;
+spi_send_data_normal(SPI_Handle_t *hspi, int8_t ss_no, const uint8_t *tx_buff, size_t tx_len)
+{
+	size_t fifo_len;
+	const uint32_t *src = (const uint32_t *)tx_buff;
+
+	if (ss_no < 0)
+		ss_no = 0;
+
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), (1 << ss_no));
+	while (tx_len > 0) {
+		fifo_len = 32 - sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_TXFLR));
+		fifo_len = fifo_len < tx_len ? fifo_len : tx_len;
+		uint32_t *dst = (uint32_t *)(hspi->base + TOFF_SPI_DR);
+		uint32_t *end = &dst[fifo_len];
+		for (; dst < end; src++, dst++) {
+			sil_wrw_mem(dst, *src);
+		}
+		tx_len -= fifo_len;
+
+		int tick = 200;
+		//sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR), 0x0011);
+		while ((sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_SR)) & 0x05) != 0x04 && tick > 0) {
+			//if(hspi->Init.semid != 0)
+			//	twai_sem(hspi->Init.semid, 1);
+			//else
+			//	dly_tsk(1);
+			tick--;
+		}
+	}
+}
+
+/*
+ *  ポーリングデータ送信
+ */
+static void
+spi_send_data_normal2(SPI_Handle_t *hspi, int8_t ss_no, uint32_t tx_data, size_t tx_len)
+{
+	size_t fifo_len;
 	uint8_t frame_width = get_framewidth(hspi->Init.DataSize);
-	uint8_t v_misalign_flag = 0;
-	uint32_t v_send_data;
-	uint32_t i = 0;
-
-	if((uintptr_t)tx_buff % frame_width){
-		v_misalign_flag = 1;
-	}
-	if(ss_no < 0)
+
+	switch (frame_width)
+	{
+	case 2:
+		tx_data = (tx_data << 16) | (tx_data & 0xFFFF);
+		break;
+	case 1:
+		tx_data = (tx_data << 24) | ((tx_data << 16) & 0xFF0000) | ((tx_data << 8) & 0xFF00) | (tx_data & 0xFF);
+		break;
+	}
+
+	if (ss_no < 0)
 		ss_no = 0;
 
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SER), (1 << ss_no));
-	while(tx_len > 0){
-		fifo_len = 32 - sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_TXFLR));
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), (1 << ss_no));
+	while (tx_len > 0) {
+		fifo_len = 32 - sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_TXFLR));
 		fifo_len = fifo_len < tx_len ? fifo_len : tx_len;
-		switch(frame_width){
-		case SPI_TRANS_INT:
-			fifo_len = fifo_len / 4 * 4;
-			if(v_misalign_flag){
-				for(index = 0; index < fifo_len; index +=4){
-					memcpy(&v_send_data, tx_buff + i , 4);
-					sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), v_send_data);
-					i += 4;
-				}
-			}
-			else{
-				for(index = 0; index < fifo_len / 4; index++)
-					sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), ((uint32_t *)tx_buff)[i++]);
-			}
-			break;
-		case SPI_TRANS_SHORT:
-			fifo_len = fifo_len / 2 * 2;
-			if(v_misalign_flag){
-				for(index = 0; index < fifo_len; index +=2){
-					memcpy(&v_send_data, tx_buff + i, 2);
-					sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), v_send_data);
-					i += 2;
-				}
-			}
-			else{
-				for(index = 0; index < fifo_len / 2; index++)
-					sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), ((uint16_t *)tx_buff)[i++]);
-			}
-			break;
-		default:
-			for(index = 0; index < fifo_len; index++)
-				sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), tx_buff[i++]);
-			break;
- 		}
+		uint32_t *dst = (uint32_t *)(hspi->base + TOFF_SPI_DR);
+		uint32_t *end = &dst[fifo_len];
+		for (; dst < end; dst++) {
+			sil_wrw_mem(dst, tx_data);
+		}
 		tx_len -= fifo_len;
+
+		int tick = 200;
+		//sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR), 0x0011);
+		while ((sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_SR)) & 0x05) != 0x04 && tick > 0) {
+			//if(hspi->Init.semid != 0)
+			//	twai_sem(hspi->Init.semid, 1);
+			//else
+			//	dly_tsk(1);
+			tick--;
+		}
 	}
 }
@@ -580,21 +601,22 @@
 	ER ercd = E_OK;
 
-	if(hspi == NULL)
+	if (hspi == NULL)
 		return E_PAR;
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		wai_sem(hspi->Init.semlock);
+
 	hspi->xmode = SPI_XMODE_TX;
-    spi_set_tmod(hspi, SPI_TMOD_TRANS);
-	if(hspi->hdmatx != NULL){
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DMACR), SPI_DMACR_TXENABLE);
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-		hdma = spi_dmac_set_single_mode(hspi, 0, ss_no, (const void *)pdata, 
-							(void *)(hspi->base+TOFF_SPI_DR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE,
-							DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, length);
+	spi_set_tmod(hspi, SPI_TMOD_TRANS);
+	if (hspi->hdmatx != NULL) {
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DMACR), SPI_DMACR_TXENABLE);
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+		hdma = spi_dmac_set_single_mode(hspi, 0, ss_no, (const void *)pdata,
+										(void *)(hspi->base + TOFF_SPI_DR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE,
+										DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, length);
 		spi_dmac_wait_done(hdma);
 	}
-	else{
-		spi_send_data_normal2(hspi, ss_no, (const void *)pdata, length);
+	else {
+		spi_send_data_normal(hspi, ss_no, (const void *)pdata, length);
 	}
 
@@ -602,5 +624,5 @@
 	ercd = spi_inwait(hspi, SPI_WAIT_TIME * length);
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		sig_sem(hspi->Init.semlock);
 #endif
@@ -622,23 +644,28 @@
 	ER ercd = E_OK;
 
-	if(hspi == NULL)
+	if (hspi == NULL)
 		return E_PAR;
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		wai_sem(hspi->Init.semlock);
 
 	hspi->xmode = SPI_XMODE_TX;
 	spi_set_tmod(hspi, SPI_TMOD_TRANS);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DMACR), SPI_DMACR_TXENABLE);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-
-    hdmatx = spi_dmac_set_single_mode(hspi, 0, ss_no, tx_buff, (void *)(hspi->base+TOFF_SPI_DR), DMAC_ADDR_NOCHANGE, DMAC_ADDR_NOCHANGE,
-                                DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, tx_len);
-    spi_dmac_wait_done(hdmatx);
-
+	if (hspi->hdmatx != NULL) {
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DMACR), SPI_DMACR_TXENABLE);
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+
+		hdmatx = spi_dmac_set_single_mode(hspi, 0, ss_no, tx_buff,
+			(void *)(hspi->base + TOFF_SPI_DR), DMAC_ADDR_NOCHANGE, DMAC_ADDR_NOCHANGE,
+			DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, tx_len);
+		spi_dmac_wait_done(hdmatx);
+	}
+	else {
+		spi_send_data_normal2(hspi, ss_no, *tx_buff, tx_len);
+	}
 #if SPI_WAIT_TIME != 0
 	ercd = spi_inwait(hspi, SPI_WAIT_TIME * tx_len);
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		sig_sem(hspi->Init.semlock);
 #endif
@@ -657,11 +684,11 @@
 spi_core_receive(SPI_Handle_t *hspi, int8_t ss_no, void *rx_buff, size_t rx_len)
 {
-	DMA_Handle_t * hdmarx;
+	DMA_Handle_t *hdmarx;
 	ER ercd = E_OK;
 
-	if(hspi == NULL || hspi->spi_num == 2)
+	if (hspi == NULL || hspi->spi_num == 2)
 		return E_PAR;
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		wai_sem(hspi->Init.semlock);
 
@@ -669,21 +696,22 @@
 	spi_set_tmod(hspi, SPI_TMOD_RECV);
 
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_CTRLR1), (rx_len - 1));
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DMACR), SPI_DMACR_RXENABLE);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-
-    hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no, (void *)(hspi->base+TOFF_SPI_DR), rx_buff, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                           DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, rx_len);
-    if(hspi->Init.FrameFormat == SPI_FF_STANDARD)
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DR), 0xFFFFFFFF);
-    spi_dmac_wait_done(hdmarx);
-
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SER), 0x00000000);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_CTRLR1), (rx_len - 1));
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DMACR), SPI_DMACR_RXENABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+
+	hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no,
+		(void *)(hspi->base + TOFF_SPI_DR), rx_buff, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
+		DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, rx_len);
+	if (hspi->Init.FrameFormat == SPI_FF_STANDARD)
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DR), 0xFFFFFFFF);
+	spi_dmac_wait_done(hdmarx);
+
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), 0x00000000);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
 
 #if SPI_WAIT_TIME != 0
 	ercd = spi_inwait(hspi, SPI_WAIT_TIME * rx_len);
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		sig_sem(hspi->Init.semlock);
 #endif
@@ -703,47 +731,47 @@
 spi_core_transrecv(SPI_Handle_t *hspi, int8_t ss_no, const uint8_t *tx_buf, uint8_t *rx_buf, size_t len)
 {
-	DMA_Handle_t * hdmarx, *hdmatx;
-    uint8_t frame_width = get_framewidth(hspi->Init.DataSize);
-    size_t v_len = len / frame_width;
+	DMA_Handle_t *hdmarx, *hdmatx;
+	uint8_t frame_width = get_framewidth(hspi->Init.DataSize);
+	size_t v_len = len / frame_width;
 	ER ercd = E_OK;
 
-	if(hspi == NULL)
+	if (hspi == NULL)
 		return E_PAR;
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		wai_sem(hspi->Init.semlock);
 
 	hspi->xmode = SPI_XMODE_TXRX;
-    spi_set_tmod(hspi, SPI_TMOD_TRANS_RECV);
-
-
-	if(hspi->hdmatx != NULL){
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DMACR), (SPI_DMACR_TXENABLE | SPI_DMACR_RXENABLE));
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-
-	    hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no, (void *)(hspi->base+TOFF_SPI_DR), rx_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                           DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, v_len);
-	    hdmatx = spi_dmac_set_single_mode(hspi, 0, -1, tx_buf, (void *)(hspi->base+TOFF_SPI_DR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE,
-                           DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, v_len);
-
-	    spi_dmac_wait_done(hdmatx);
-	}
-	else{
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_DMACR), SPI_DMACR_RXENABLE);
-		sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
-
-	    hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no, (void *)(hspi->base+TOFF_SPI_DR), rx_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
-                           DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, v_len);
-		spi_send_data_normal2(hspi, -1, (const void *)tx_buf, len);
+	spi_set_tmod(hspi, SPI_TMOD_TRANS_RECV);
+
+	if (hspi->hdmatx != NULL) {
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DMACR), (SPI_DMACR_TXENABLE | SPI_DMACR_RXENABLE));
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+
+		hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no, (void *)(hspi->base + TOFF_SPI_DR), rx_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
+										  DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, v_len);
+		hdmatx = spi_dmac_set_single_mode(hspi, 0, -1, tx_buf, (void *)(hspi->base + TOFF_SPI_DR), DMAC_ADDR_INCREMENT, DMAC_ADDR_NOCHANGE,
+										  DMAC_MSIZE_4, DMAC_TRANS_WIDTH_32, v_len);
+
+		spi_dmac_wait_done(hdmatx);
+	}
+	else {
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_DMACR), SPI_DMACR_RXENABLE);
+		sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_ENABLE);
+
+		hdmarx = spi_dmac_set_single_mode(hspi, 1, ss_no,
+			(void *)(hspi->base + TOFF_SPI_DR), rx_buf, DMAC_ADDR_NOCHANGE, DMAC_ADDR_INCREMENT,
+			DMAC_MSIZE_1, DMAC_TRANS_WIDTH_32, v_len);
+		spi_send_data_normal(hspi, -1, (const void *)tx_buf, len);
 	}
 	spi_dmac_wait_done(hdmarx);
 
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SER), 0x00000000);
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SER), 0x00000000);
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_SSIENR), SPI_SSIENR_DISABLE);
 
 #if SPI_WAIT_TIME != 0
 	ercd = spi_inwait(hspi, SPI_WAIT_TIME * len);
 
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		sig_sem(hspi->Init.semlock);
 #endif
@@ -760,8 +788,8 @@
 
 #if SPI_WAIT_TIME == 0
-	if(hspi == NULL)
+	if (hspi == NULL)
 		return E_PAR;
 	ercd = spi_inwait(hspi, timeout);
-	if(hspi->Init.semlock != 0)
+	if (hspi->Init.semlock != 0)
 		sig_sem(hspi->Init.semlock);
 #endif
@@ -769,5 +797,4 @@
 }
 
-
 /*
  *  SPI割込みサービスルーチン
@@ -776,13 +803,14 @@
 spi_handler(SPI_Handle_t *hspi)
 {
-	volatile uint32_t imr, isr, tmp;
-
-	imr = sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR));
-	isr = sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_ISR));
-	sil_wrw_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR), 0);
-
-	syslog_2(LOG_DEBUG, "spi_handler imr[%08x] isr[%08x]", imr, isr);
-	tmp = sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_ICR));
-	if(hspi->Init.semid != 0)
+	//volatile uint32_t imr, isr;
+	volatile uint32_t tmp;
+
+	//imr = sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_IMR));
+	//isr = sil_rew_mem((uint32_t *)(hspi->base+TOFF_SPI_ISR));
+	sil_wrw_mem((uint32_t *)(hspi->base + TOFF_SPI_IMR), 0);
+
+	//syslog_2(LOG_DEBUG, "spi_handler imr[%08x] isr[%08x]", imr, isr);
+	tmp = sil_rew_mem((uint32_t *)(hspi->base + TOFF_SPI_ICR));
+	if (hspi->Init.semid != 0)
 		isig_sem(hspi->Init.semid);
 	(void)(tmp);
@@ -794,6 +822,4 @@
 void spi_isr(intptr_t exinf)
 {
-  spi_handler(&SpiHandle[INDEX_SPI((uint32_t)exinf)]);
-}
-
-
+	spi_handler(&SpiHandle[INDEX_SPI((uint32_t)exinf)]);
+}
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.h
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi.h	(revision 458)
@@ -49,5 +49,5 @@
 
 #ifdef __cplusplus
- extern "C" {
+extern "C" {
 #endif
 
@@ -55,160 +55,156 @@
  *  SPIポート定義
  */
-#define SPI1_PORTID             1
-#define SPI2_PORTID             2
-#define SPI3_PORTID             3
-#define SPI4_PORTID             3
-#define NUM_SPIPORT             4
-
+#define SPI1_PORTID 1
+#define SPI2_PORTID 2
+#define SPI3_PORTID 3
+#define SPI4_PORTID 3
+#define NUM_SPIPORT 4
 
 /*
  *  SPI状態定義
  */
-#define SPI_STATUS_RESET        0x0000	/* SPI未使用状態 */
-#define SPI_STATUS_READY        0x0001	/* SPIレディ状態 */
-#define SPI_STATUS_ERROR        0x0002	/* SPIエラー状態 */
-#define SPI_STATUS_BUSY         0x0004	/* SPI処理中 */
+#define SPI_STATUS_RESET 0x0000 /* SPI未使用状態 */
+#define SPI_STATUS_READY 0x0001 /* SPIレディ状態 */
+#define SPI_STATUS_ERROR 0x0002 /* SPIエラー状態 */
+#define SPI_STATUS_BUSY 0x0004	/* SPI処理中 */
 
 /*
  *  SPI転送モード
  */
-#define SPI_XMODE_TX            0x0000	/* 送信モード */
-#define SPI_XMODE_RX            0x0001	/* 受信モード */
-#define SPI_XMODE_TXRX          0x0002	/* 送受信モード */
+#define SPI_XMODE_TX 0x0000	  /* 送信モード */
+#define SPI_XMODE_RX 0x0001	  /* 受信モード */
+#define SPI_XMODE_TXRX 0x0002 /* 送受信モード */
 
 /*
  *  SPIエラー定義
  */
-#define SPI_ERROR_NONE          0x00000000	/* No error */
-#define SPI_ERROR_MODF          0x00000001	/* MODF error */
-#define SPI_ERROR_CRC           0x00000002	/* CRC error */
-#define SPI_ERROR_OVR           0x00000004	/* OVR error */
-#define SPI_ERROR_FRE           0x00000008	/* FRE error */
-#define SPI_ERROR_DMA           0x00000010	/* DMA transfer error */
-#define SPI_ERROR_TIMEOUT       0x00000020
+#define SPI_ERROR_NONE 0x00000000 /* No error */
+#define SPI_ERROR_MODF 0x00000001 /* MODF error */
+#define SPI_ERROR_CRC 0x00000002  /* CRC error */
+#define SPI_ERROR_OVR 0x00000004  /* OVR error */
+#define SPI_ERROR_FRE 0x00000008  /* FRE error */
+#define SPI_ERROR_DMA 0x00000010  /* DMA transfer error */
+#define SPI_ERROR_TIMEOUT 0x00000020
 
 /*
  *  SPIワークモード定義
  */
-#define SPI_WORK_MODE_0         0x00000000
-#define SPI_WORK_MODE_1         0x00000001
-#define SPI_WORK_MODE_2         0x00000002
-#define SPI_WORK_MODE_3         0x00000003
+#define SPI_WORK_MODE_0 0x00000000
+#define SPI_WORK_MODE_1 0x00000001
+#define SPI_WORK_MODE_2 0x00000002
+#define SPI_WORK_MODE_3 0x00000003
 
 /*
  *  SPIフレームフォーマット定義
  */
-#define SPI_FF_STANDARD         0x00000000
-#define SPI_FF_DUAL             0x00000001
-#define SPI_FF_QUAD             0x00000002
-#define SPI_FF_OCTAL            0x00000003
+#define SPI_FF_STANDARD 0x00000000
+#define SPI_FF_DUAL 0x00000001
+#define SPI_FF_QUAD 0x00000002
+#define SPI_FF_OCTAL 0x00000003
 
 /*
  *  SPIインストラクションアドレスモード
  */
-#define SPI_AITM_STANDARD        0x00000000
-#define SPI_AITM_ADDR_STANDARD   0x00000001
+#define SPI_AITM_STANDARD 0x00000000
+#define SPI_AITM_ADDR_STANDARD 0x00000001
 #define SPI_AITM_AS_FRAME_FORMAT 0x00000002
 
-
 /*
  *  SPI転送モード定義
  */
-#define SPI_TMOD_TRANS_RECV     0x00000000
-#define SPI_TMOD_TRANS          0x00000001
-#define SPI_TMOD_RECV           0x00000002
-#define SPI_TMOD_EEROM          0x00000003
+#define SPI_TMOD_TRANS_RECV 0x00000000
+#define SPI_TMOD_TRANS 0x00000001
+#define SPI_TMOD_RECV 0x00000002
+#define SPI_TMOD_EEROM 0x00000003
 
 /*
  *  SPI転送データ長定義
  */
-#define SPI_TRANS_CHAR          0x01
-#define SPI_TRANS_SHORT         0x02
-#define SPI_TRANS_INT           0x04
+#define SPI_TRANS_CHAR 0x01
+#define SPI_TRANS_SHORT 0x02
+#define SPI_TRANS_INT 0x04
 
 /*
  *  SPI CS選択定義
  */
-#define SPI_CHIP_SELECT_0       0x00
-#define SPI_CHIP_SELECT_1       0x01
-#define SPI_CHIP_SELECT_2       0x02
-#define SPI_CHIP_SELECT_3       0x03
-#define SPI_CHIP_SELECT_MAX     4
-
-/*
+#define SPI_CHIP_SELECT_0 0x00
+#define SPI_CHIP_SELECT_1 0x01
+#define SPI_CHIP_SELECT_2 0x02
+#define SPI_CHIP_SELECT_3 0x03
+#define SPI_CHIP_SELECT_MAX 4
+
+	/*
  *  SPI 設定初期設定構造体
  */
-typedef struct
-{
-	uint32_t              WorkMode;
-	uint32_t              FrameFormat;
-    uint32_t              DataSize;			/* SPI転送データサイズ */
-	uint32_t              Prescaler;		/* SPIクロック分周設定 */
-	uint32_t              SignBit;			/* SPI MSB/LSB設定 */
-	uint32_t              InstLength;		/* SPI Instraction Length */
-	uint32_t              AddrLength;		/* SPI Address Length */
-	uint32_t              WaitCycles;		/* SPI WaitCycles */
-	uint32_t              IATransMode;		/* SPI 転送モード */
-	int32_t               SclkPin;			/* SPI SCLK-PIN */
-	int32_t               MosiPin;			/* SPI MOSI-PIN */
-	int32_t               MisoPin;			/* SPI MISO-PIN */
-	int32_t               SsPin;			/* SPI Slave Select-PIN */
-	int32_t               SsNo;				/* SPI Slave Select-Number */
-	int32_t               TxDMAChannel;		/* SPI TxDMAチャンネル */
-	int32_t               RxDMAChannel;		/* SPI RxDMAチャンネル */
-	int                   semid;			/* SPI 通信用セマフォ値 */
-	int                   semlock;			/* SPI ロックセマフォ値 */
-	int                   semdmaid;			/* SPI DMA通信用セマフォ値 */
-}SPI_Init_t;
-
-/*
+	typedef struct
+	{
+		uint32_t WorkMode;
+		uint32_t FrameFormat;
+		uint32_t DataSize;	  /* SPI転送データサイズ */
+		uint32_t Prescaler;	  /* SPIクロック分周設定 */
+		uint32_t SignBit;	  /* SPI MSB/LSB設定 */
+		uint32_t InstLength;  /* SPI Instraction Length */
+		uint32_t AddrLength;  /* SPI Address Length */
+		uint32_t WaitCycles;  /* SPI WaitCycles */
+		uint32_t IATransMode; /* SPI 転送モード */
+		int32_t SclkPin;	  /* SPI SCLK-PIN */
+		int32_t MosiPin;	  /* SPI MOSI-PIN */
+		int32_t MisoPin;	  /* SPI MISO-PIN */
+		int32_t SsPin;		  /* SPI Slave Select-PIN */
+		int32_t SsNo;		  /* SPI Slave Select-Number */
+		int32_t TxDMAChannel; /* SPI TxDMAチャンネル */
+		int32_t RxDMAChannel; /* SPI RxDMAチャンネル */
+		int semid;			  /* SPI 通信用セマフォ値 */
+		int semlock;		  /* SPI ロックセマフォ値 */
+		int semdmaid;		  /* SPI DMA通信用セマフォ値 */
+	} SPI_Init_t;
+
+	/*
  *  SPIハンドラ
  */
-typedef struct _SPI_Handle_t
-{
-	unsigned long         base;				/* SPI registers base address */
-	SPI_Init_t            Init;				/* SPI communication parameters */
-	uint8_t               spi_num;
-	uint8_t               dfs_offset;
-	uint8_t               frf_offset;
-	uint8_t               work_mode_offset;
-	uint8_t               tmod_offset;
-	uint8_t               dummy[3];
-	uint8_t               *pTxBuffPtr;		/* Pointer to SPI Tx transfer Buffer */
-	uint32_t              TxXferSize;		/* SPI Tx transfer size */
-	uint32_t              TxXferCount;		/* SPI Tx Transfer Counter */
-	uint8_t               *pRxBuffPtr;		/* Pointer to SPI Rx transfer Buffer */
-	uint32_t              RxXferSize;		/* SPI Rx transfer size */
-	uint32_t              RxXferCount;		/* SPI Rx Transfer Counter */
-	DMA_Handle_t          *hdmatx;			/* SPI Tx DMA handle parameters */
-	DMA_Handle_t          *hdmarx;			/* SPI Rx DMA handle parameters */
-	uint16_t              xmode;			/* SPI Transfar mode */
-	volatile uint16_t     status;			/* SPI communication state */
-	volatile uint32_t     ErrorCode;		/* SPI Error code */
-}SPI_Handle_t;
-
-
-extern SPI_Handle_t *spi_init(ID port, const SPI_Init_t *init);
-extern ER spi_deinit(SPI_Handle_t *hspi);
-extern ER spi_core_transmit(SPI_Handle_t *hspi, int8_t ss_no, uint8_t *pdata, uint16_t length);
-extern ER spi_core_transmit_fill(SPI_Handle_t *hspi, int8_t ss_no, const uint32_t *tx_buff, size_t tx_len);
-extern ER spi_core_receive(SPI_Handle_t *hspi, int8_t ss_no, void *rx_buff, size_t rx_len);
-extern ER spi_core_transrecv(SPI_Handle_t *hspi, int8_t ss_no, const uint8_t *tx_buf, uint8_t *rx_buf, size_t len);
-extern ER spi_transmit(SPI_Handle_t *hspi, uint8_t *pdata, uint16_t length);
-extern ER spi_receive(SPI_Handle_t *hspi, uint8_t *pdata, uint16_t length);
-extern ER spi_transrecv(SPI_Handle_t *hspi, uint8_t *ptxData, uint8_t *prxData, uint16_t length);
-extern ER spi_wait(SPI_Handle_t *hspi, uint32_t timeout);
-extern void spi_handler(SPI_Handle_t *hspi);
-extern void spi_isr(intptr_t exinf);
-extern DMA_Handle_t *spi_dmac_set_single_mode(SPI_Handle_t *hspi, 
-                          uint8_t rtx,
-						  int8_t  ss_no,
-                          const void *src, void *dest, uint8_t src_inc,
-                          uint8_t dest_inc,
-                          uint8_t dmac_burst_size,
-                          uint8_t dmac_trans_width,
-                          size_t block_size);
-extern ER spi_dmac_wait_done(DMA_Handle_t * hdma);
-
+	typedef struct _SPI_Handle_t
+	{
+		unsigned long base; /* SPI registers base address */
+		SPI_Init_t Init;	/* SPI communication parameters */
+		uint8_t spi_num;
+		uint8_t dfs_offset;
+		uint8_t frf_offset;
+		uint8_t work_mode_offset;
+		uint8_t tmod_offset;
+		uint8_t dummy[3];
+		uint8_t *pTxBuffPtr;		 /* Pointer to SPI Tx transfer Buffer */
+		uint32_t TxXferSize;		 /* SPI Tx transfer size */
+		uint32_t TxXferCount;		 /* SPI Tx Transfer Counter */
+		uint8_t *pRxBuffPtr;		 /* Pointer to SPI Rx transfer Buffer */
+		uint32_t RxXferSize;		 /* SPI Rx transfer size */
+		uint32_t RxXferCount;		 /* SPI Rx Transfer Counter */
+		DMA_Handle_t *hdmatx;		 /* SPI Tx DMA handle parameters */
+		DMA_Handle_t *hdmarx;		 /* SPI Rx DMA handle parameters */
+		uint16_t xmode;				 /* SPI Transfar mode */
+		volatile uint16_t status;	 /* SPI communication state */
+		volatile uint32_t ErrorCode; /* SPI Error code */
+	} SPI_Handle_t;
+
+	extern SPI_Handle_t *spi_init(ID port, const SPI_Init_t *init);
+	extern ER spi_deinit(SPI_Handle_t *hspi);
+	extern ER spi_core_transmit(SPI_Handle_t *hspi, int8_t ss_no, uint8_t *pdata, uint16_t length);
+	extern ER spi_core_transmit_fill(SPI_Handle_t *hspi, int8_t ss_no, const uint32_t *tx_buff, size_t tx_len);
+	extern ER spi_core_receive(SPI_Handle_t *hspi, int8_t ss_no, void *rx_buff, size_t rx_len);
+	extern ER spi_core_transrecv(SPI_Handle_t *hspi, int8_t ss_no, const uint8_t *tx_buf, uint8_t *rx_buf, size_t len);
+	extern ER spi_transmit(SPI_Handle_t *hspi, uint8_t *pdata, uint16_t length);
+	extern ER spi_receive(SPI_Handle_t *hspi, uint8_t *pdata, uint16_t length);
+	extern ER spi_transrecv(SPI_Handle_t *hspi, uint8_t *ptxData, uint8_t *prxData, uint16_t length);
+	extern ER spi_wait(SPI_Handle_t *hspi, uint32_t timeout);
+	extern void spi_handler(SPI_Handle_t *hspi);
+	extern void spi_isr(intptr_t exinf);
+	extern DMA_Handle_t *spi_dmac_set_single_mode(SPI_Handle_t *hspi,
+												  uint8_t rtx,
+												  int8_t ss_no,
+												  const void *src, void *dest, uint8_t src_inc,
+												  uint8_t dest_inc,
+												  uint8_t dmac_burst_size,
+												  uint8_t dmac_trans_width,
+												  size_t block_size);
+	extern ER spi_dmac_wait_done(DMA_Handle_t *hdma);
 
 #ifdef __cplusplus
@@ -216,4 +212,3 @@
 #endif
 
-#endif	/* _SPI_H_ */
-
+#endif /* _SPI_H_ */
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi_reg.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi_reg.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/pdic/k210/spi_reg.c	(revision 458)
@@ -169,3 +169,2 @@
 	return ercd;
 }
-
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/logtask.h
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/logtask.h	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/logtask.h	(revision 458)
@@ -62,5 +62,5 @@
 
 #ifndef LOGTASK_STACK_SIZE
-#define LOGTASK_STACK_SIZE	1024	/* スタック領域のサイズ */
+#define LOGTASK_STACK_SIZE	2048	/* スタック領域のサイズ */
 #endif /* LOGTASK_STACK_SIZE */
 
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.c	(revision 458)
@@ -307,7 +307,8 @@
 		ER ret;
 		if (sense_context())
-			ret = iloc_cpu();
+			//ret = iloc_cpu();
+			ret = E_CTX;
 		else
-			ret = loc_cpu();
+			ret = wai_sem(MALLOC_SEM);
 		if (ret != E_OK)
 			syslog_1(LOG_ERROR, "__malloc_unlock: count[%d] loc_cpu", malloc_lock_count);
@@ -322,7 +323,8 @@
 		ER ret;
 		if (sense_context())
-			ret = iunl_cpu();
+			//ret = iunl_cpu();
+			ret = E_CTX;
 		else
-			ret = unl_cpu();
+			ret = sig_sem(MALLOC_SEM);
 		if (ret != E_OK)
 			syslog_1(LOG_ERROR, "__malloc_unlock: count[%d] unl_cpu error !", malloc_lock_count);
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.cfg
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.cfg	(revision 458)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/malloc.cfg	(revision 458)
@@ -0,0 +1,5 @@
+/*
+ *  $Id$
+ */
+CRE_SEM(MALLOC_SEM, { TA_NULL, 1, 1 });
+
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/serial.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/serial.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/syssvc/serial.c	(revision 458)
@@ -56,56 +56,56 @@
  */
 #ifndef SERIAL_RCV_BUFSZ1
-#define	SERIAL_RCV_BUFSZ1	256			/* ポート1の受信バッファサイズ */
-#endif /* SERIAL_RCV_BUFSZ1 */
+#define SERIAL_RCV_BUFSZ1 256 /* ポート1の受信バッファサイズ */
+#endif						  /* SERIAL_RCV_BUFSZ1 */
 
 #ifndef SERIAL_SND_BUFSZ1
-#define	SERIAL_SND_BUFSZ1	256			/* ポート1の送信バッファサイズ */
-#endif /* SERIAL_SND_BUFSZ1 */
-
-static char	rcv_buffer1[SERIAL_RCV_BUFSZ1];
-static char	snd_buffer1[SERIAL_SND_BUFSZ1];
-
-#if TNUM_PORT >= 2						/* ポート2に関する定義 */
+#define SERIAL_SND_BUFSZ1 256 /* ポート1の送信バッファサイズ */
+#endif						  /* SERIAL_SND_BUFSZ1 */
+
+static char rcv_buffer1[SERIAL_RCV_BUFSZ1];
+static char snd_buffer1[SERIAL_SND_BUFSZ1];
+
+#if TNUM_PORT >= 2 /* ポート2に関する定義 */
 
 #ifndef SERIAL_RCV_BUFSZ2
-#define	SERIAL_RCV_BUFSZ2	256			/* ポート2の受信バッファサイズ */
-#endif /* SERIAL_RCV_BUFSZ2 */
+#define SERIAL_RCV_BUFSZ2 256 /* ポート2の受信バッファサイズ */
+#endif						  /* SERIAL_RCV_BUFSZ2 */
 
 #ifndef SERIAL_SND_BUFSZ2
-#define	SERIAL_SND_BUFSZ2	256			/* ポート2の送信バッファサイズ */
-#endif /* SERIAL_SND_BUFSZ2 */
-
-static char	rcv_buffer2[SERIAL_RCV_BUFSZ2];
-static char	snd_buffer2[SERIAL_SND_BUFSZ2];
+#define SERIAL_SND_BUFSZ2 256 /* ポート2の送信バッファサイズ */
+#endif						  /* SERIAL_SND_BUFSZ2 */
+
+static char rcv_buffer2[SERIAL_RCV_BUFSZ2];
+static char snd_buffer2[SERIAL_SND_BUFSZ2];
 
 #endif /* TNUM_PORT >= 2 */
 
-#if TNUM_PORT >= 3						/* ポート3に関する定義 */
+#if TNUM_PORT >= 3 /* ポート3に関する定義 */
 
 #ifndef SERIAL_RCV_BUFSZ3
-#define	SERIAL_RCV_BUFSZ3	256			/* ポート3の受信バッファサイズ */
-#endif /* SERIAL_RCV_BUFSZ3 */
+#define SERIAL_RCV_BUFSZ3 256 /* ポート3の受信バッファサイズ */
+#endif						  /* SERIAL_RCV_BUFSZ3 */
 
 #ifndef SERIAL_SND_BUFSZ3
-#define	SERIAL_SND_BUFSZ3	256			/* ポート3の送信バッファサイズ */
-#endif /* SERIAL_SND_BUFSZ3 */
-
-static char	rcv_buffer3[SERIAL_RCV_BUFSZ3];
-static char	snd_buffer3[SERIAL_SND_BUFSZ3];
+#define SERIAL_SND_BUFSZ3 256 /* ポート3の送信バッファサイズ */
+#endif						  /* SERIAL_SND_BUFSZ3 */
+
+static char rcv_buffer3[SERIAL_RCV_BUFSZ3];
+static char snd_buffer3[SERIAL_SND_BUFSZ3];
 
 #endif /* TNUM_PORT >= 3 */
 
-#if TNUM_PORT >= 4						/* ポート4に関する定義 */
+#if TNUM_PORT >= 4 /* ポート4に関する定義 */
 
 #ifndef SERIAL_RCV_BUFSZ4
-#define	SERIAL_RCV_BUFSZ4	256			/* ポート4の受信バッファサイズ */
-#endif /* SERIAL_RCV_BUFSZ4 */
+#define SERIAL_RCV_BUFSZ4 256 /* ポート4の受信バッファサイズ */
+#endif						  /* SERIAL_RCV_BUFSZ4 */
 
 #ifndef SERIAL_SND_BUFSZ4
-#define	SERIAL_SND_BUFSZ4	256			/* ポート4の送信バッファサイズ */
-#endif /* SERIAL_SND_BUFSZ4 */
-
-static char	rcv_buffer4[SERIAL_RCV_BUFSZ4];
-static char	snd_buffer4[SERIAL_SND_BUFSZ4];
+#define SERIAL_SND_BUFSZ4 256 /* ポート4の送信バッファサイズ */
+#endif						  /* SERIAL_SND_BUFSZ4 */
+
+static char rcv_buffer4[SERIAL_RCV_BUFSZ4];
+static char snd_buffer4[SERIAL_SND_BUFSZ4];
 
 #endif /* TNUM_PORT >= 4 */
@@ -118,9 +118,9 @@
  *  フロー制御に関連する定数とマクロ
  */
-#define	FC_STOP			'\023'		/* コントロール-S */
-#define	FC_START		'\021'		/* コントロール-Q */
-
-#define BUFCNT_STOP(bufsz)		((bufsz) * 3 / 4)	/* STOPを送る基準文字数 */
-#define BUFCNT_START(bufsz)		((bufsz) / 2)		/* STARTを送る基準文字数 */
+#define FC_STOP '\023'	/* コントロール-S */
+#define FC_START '\021' /* コントロール-Q */
+
+#define BUFCNT_STOP(bufsz) ((bufsz)*3 / 4) /* STOPを送る基準文字数 */
+#define BUFCNT_START(bufsz) ((bufsz) / 2)  /* STARTを送る基準文字数 */
 
 /*
@@ -128,30 +128,30 @@
  */
 typedef struct serial_port_initialization_block {
-	ID		rcv_semid;		/* 受信バッファ管理用セマフォのID */
-	ID		snd_semid;		/* 送信バッファ管理用セマフォのID */
-	uint_t	rcv_bufsz;		/* 受信バッファサイズ */
-	char	*rcv_buffer;	/* 受信バッファ */
-	uint_t	snd_bufsz;		/* 送信バッファサイズ */
-	char	*snd_buffer;	/* 送信バッファ */
+	ID rcv_semid;	  /* 受信バッファ管理用セマフォのID */
+	ID snd_semid;	  /* 送信バッファ管理用セマフォのID */
+	uint_t rcv_bufsz; /* 受信バッファサイズ */
+	char *rcv_buffer; /* 受信バッファ */
+	uint_t snd_bufsz; /* 送信バッファサイズ */
+	char *snd_buffer; /* 送信バッファ */
 } SPINIB;
 
 static const SPINIB spinib_table[TNUM_PORT] = {
-	{ SERIAL_RCV_SEM1, SERIAL_SND_SEM1,
-	  SERIAL_RCV_BUFSZ1, rcv_buffer1,
-	  SERIAL_SND_BUFSZ1, snd_buffer1 },
+	{SERIAL_RCV_SEM1, SERIAL_SND_SEM1,
+	 SERIAL_RCV_BUFSZ1, rcv_buffer1,
+	 SERIAL_SND_BUFSZ1, snd_buffer1},
 #if TNUM_PORT >= 2
-	{ SERIAL_RCV_SEM2, SERIAL_SND_SEM2,
-	  SERIAL_RCV_BUFSZ2, rcv_buffer2,
-	  SERIAL_SND_BUFSZ2, snd_buffer2 },
+	{SERIAL_RCV_SEM2, SERIAL_SND_SEM2,
+	 SERIAL_RCV_BUFSZ2, rcv_buffer2,
+	 SERIAL_SND_BUFSZ2, snd_buffer2},
 #endif /* TNUM_PORT >= 2 */
 #if TNUM_PORT >= 3
-	{ SERIAL_RCV_SEM3, SERIAL_SND_SEM3,
-	  SERIAL_RCV_BUFSZ3, rcv_buffer3,
-	  SERIAL_SND_BUFSZ3, snd_buffer3 },
+	{SERIAL_RCV_SEM3, SERIAL_SND_SEM3,
+	 SERIAL_RCV_BUFSZ3, rcv_buffer3,
+	 SERIAL_SND_BUFSZ3, snd_buffer3},
 #endif /* TNUM_PORT >= 3 */
 #if TNUM_PORT >= 4
-	{ SERIAL_RCV_SEM4, SERIAL_SND_SEM4,
-	  SERIAL_RCV_BUFSZ4, rcv_buffer4,
-	  SERIAL_SND_BUFSZ4, snd_buffer4 },
+	{SERIAL_RCV_SEM4, SERIAL_SND_SEM4,
+	 SERIAL_RCV_BUFSZ4, rcv_buffer4,
+	 SERIAL_SND_BUFSZ4, snd_buffer4},
 #endif /* TNUM_PORT >= 4 */
 };
@@ -161,38 +161,38 @@
  */
 typedef struct serial_port_control_block {
-	const SPINIB *p_spinib;		/* シリアルポート初期化ブロック */
-	SIOPCB	*p_siopcb;			/* シリアルI/Oポート管理ブロック */
-	bool_t	openflag;			/* オープン済みフラグ */
-	bool_t	errorflag;			/* エラーフラグ */
-	uint_t	ioctl;				/* 動作制御の設定値 */
-
-	uint_t	rcv_read_ptr;		/* 受信バッファ読出しポインタ */
-	uint_t	rcv_write_ptr;		/* 受信バッファ書込みポインタ */
-	uint_t	rcv_count;			/* 受信バッファ中の文字数 */
-	char	rcv_fc_chr;			/* 送るべきSTART/STOP */
-	bool_t	rcv_stopped;		/* STOPを送った状態か？ */
-
-	uint_t	snd_read_ptr;		/* 送信バッファ読出しポインタ */
-	uint_t	snd_write_ptr;		/* 送信バッファ書込みポインタ */
-	uint_t	snd_count;			/* 送信バッファ中の文字数 */
-	bool_t	snd_stopped;		/* STOPを受け取った状態か？ */
+	const SPINIB *p_spinib; /* シリアルポート初期化ブロック */
+	SIOPCB *p_siopcb;		/* シリアルI/Oポート管理ブロック */
+	bool_t openflag;		/* オープン済みフラグ */
+	bool_t errorflag;		/* エラーフラグ */
+	uint_t ioctl;			/* 動作制御の設定値 */
+
+	uint_t rcv_read_ptr;  /* 受信バッファ読出しポインタ */
+	uint_t rcv_write_ptr; /* 受信バッファ書込みポインタ */
+	uint_t rcv_count;	  /* 受信バッファ中の文字数 */
+	char rcv_fc_chr;	  /* 送るべきSTART/STOP */
+	bool_t rcv_stopped;	  /* STOPを送った状態か？ */
+
+	uint_t snd_read_ptr;  /* 送信バッファ読出しポインタ */
+	uint_t snd_write_ptr; /* 送信バッファ書込みポインタ */
+	uint_t snd_count;	  /* 送信バッファ中の文字数 */
+	bool_t snd_stopped;	  /* STOPを受け取った状態か？ */
 } SPCB;
 
-static SPCB	spcb_table[TNUM_PORT];
+static SPCB spcb_table[TNUM_PORT];
 
 /*
  *  シリアルポートIDからシリアルポート管理ブロックを取り出すためのマクロ
  */
-#define INDEX_PORT(portid)	((uint_t)((portid) - 1))
-#define get_spcb(portid)	(&(spcb_table[INDEX_PORT(portid)]))
+#define INDEX_PORT(portid) ((uint_t)((portid)-1))
+#define get_spcb(portid) (&(spcb_table[INDEX_PORT(portid)]))
 
 /*
  *  ポインタのインクリメント
  */
-#define INC_PTR(ptr, bufsz) do {	\
-	if (++(ptr) == (bufsz)) {		\
-		(ptr) = 0;					\
-	 }								\
-} while (false)
+#define INC_PTR(ptr, bufsz) do {   \
+		if (++(ptr) == (bufsz)) {  \
+			(ptr) = 0;             \
+		}                          \
+	} while (false)
 
 /*
@@ -202,10 +202,10 @@
  *  合には，ercにercd_expを評価した値を代入し，error_exitにgotoする．
  */
-#define SVC(exp, ercd_exp) do {		\
-	if ((exp) < 0) {				\
-		ercd = (ercd_exp);			\
-		goto error_exit;			\
-	}								\
-} while (false)
+#define SVC(exp, ercd_exp) do {    \
+		if ((exp) < 0) {           \
+			ercd = (ercd_exp);     \
+			goto error_exit;       \
+		}                          \
+	} while (false)
 
 /*
@@ -216,5 +216,5 @@
 {
 	p_spcb->errorflag = true;
-	return(E_SYS);
+	return (E_SYS);
 }
 
@@ -228,8 +228,8 @@
 	case E_RLWAI:
 	case E_DLT:
-		return(rercd);
+		return (rercd);
 	default:
 		p_spcb->errorflag = true;
-		return(E_SYS);
+		return (E_SYS);
 	}
 }
@@ -241,6 +241,6 @@
 serial_initialize(intptr_t exinf)
 {
-	uint_t	i;
-	SPCB	*p_spcb;
+	uint_t i;
+	SPCB *p_spcb;
 
 	for (i = 0; i < TNUM_PORT; i++) {
@@ -257,17 +257,17 @@
 serial_opn_por(ID portid)
 {
-	SPCB	*p_spcb;
-	ER		ercd;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+	ER ercd;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 	p_spcb = get_spcb(portid);
 
 	SVC(dis_dsp(), gen_ercd_sys(p_spcb));
-	if (p_spcb->openflag) {			/* オープン済みかのチェック */
+	if (p_spcb->openflag) { /* オープン済みかのチェック */
 		ercd = E_OBJ;
 	}
@@ -292,5 +292,5 @@
 		 *  これ以降，割込みを禁止する．
 		 */
-		if (loc_cpu() < 0) {
+		if (loc_cpu() < 0) 	{
 			ercd = E_SYS;
 			goto error_exit_enadsp;
@@ -300,5 +300,5 @@
 		 *  ハードウェア依存のオープン処理
 		 */
-		p_spcb->p_siopcb = sio_opn_por(portid, (intptr_t) p_spcb);
+		p_spcb->p_siopcb = sio_opn_por(portid, (intptr_t)p_spcb);
 
 		/*
@@ -317,9 +317,9 @@
 	}
 
-  error_exit_enadsp:
+error_exit_enadsp:
 	SVC(ena_dsp(), gen_ercd_sys(p_spcb));
 
-  error_exit:
-	return(ercd);
+error_exit:
+	return (ercd);
 }
 
@@ -330,18 +330,18 @@
 serial_cls_por(ID portid)
 {
-	SPCB	*p_spcb;
-	ER		ercd;
-	bool_t	eflag = false;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+	ER ercd;
+	bool_t eflag = false;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 	p_spcb = get_spcb(portid);
 
 	SVC(dis_dsp(), gen_ercd_sys(p_spcb));
-	if (!(p_spcb->openflag)) {		/* オープン済みかのチェック */
+	if (!(p_spcb->openflag)) { /* オープン済みかのチェック */
 		ercd = E_OBJ;
 	}
@@ -381,6 +381,6 @@
 	SVC(ena_dsp(), gen_ercd_sys(p_spcb));
 
-  error_exit:
-	return(ercd);
+error_exit:
+	return (ercd);
 }
 
@@ -397,9 +397,9 @@
 {
 	if (sio_snd_chr(p_spcb->p_siopcb, c)) {
-		return(true);
+		return (true);
 	}
 	else {
 		sio_ena_cbr(p_spcb->p_siopcb, SIO_RDY_SND);
-		return(false);
+		return (false);
 	}
 }
@@ -411,6 +411,6 @@
 serial_wri_chr(SPCB *p_spcb, char c)
 {
-	bool_t	buffer_full;
-	ER		ercd, rercd;
+	bool_t buffer_full;
+	ER ercd, rercd;
 
 	/*
@@ -424,7 +424,7 @@
 		 */
 		SVC(rercd = serial_wri_chr(p_spcb, '\r'), rercd);
-		if ((bool_t) rercd) {
+		if ((bool_t)rercd) {
 			SVC(rercd = wai_sem(p_spcb->p_spinib->snd_semid),
-										gen_ercd_wait(rercd, p_spcb));
+				gen_ercd_wait(rercd, p_spcb));
 		}
 	}
@@ -432,5 +432,5 @@
 	SVC(loc_cpu(), gen_ercd_sys(p_spcb));
 	if (p_spcb->snd_count == 0U && !(p_spcb->snd_stopped)
-								&& serial_snd_chr(p_spcb, c)) {
+		&& serial_snd_chr(p_spcb, c)) {
 		/*
 		 *  シリアルI/Oデバイスの送信レジスタに文字を入れることに成功し
@@ -450,8 +450,8 @@
 
 	SVC(unl_cpu(), gen_ercd_sys(p_spcb));
-	ercd = (ER_BOOL) buffer_full;
-
-  error_exit:
-	return(ercd);
+	ercd = (ER_BOOL)buffer_full;
+
+error_exit:
+	return (ercd);
 }
 
@@ -462,33 +462,33 @@
 serial_wri_dat(ID portid, const char *buf, uint_t len)
 {
-	SPCB	*p_spcb;
-	bool_t	buffer_full;
-	uint_t	wricnt = 0U;
-	ER		ercd, rercd;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+	bool_t buffer_full;
+	uint_t wricnt = 0U;
+	ER ercd, rercd;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 
 	p_spcb = get_spcb(portid);
-	if (!(p_spcb->openflag)) {		/* オープン済みかのチェック */
-		return(E_OBJ);
-	}
-	if (p_spcb->errorflag) {		/* エラー状態かのチェック */
-		return(E_SYS);
-	}
-
-	buffer_full = true;				/* ループの1回めはwai_semする */
+	if (!(p_spcb->openflag)) { /* オープン済みかのチェック */
+		return (E_OBJ);
+	}
+	if (p_spcb->errorflag) { /* エラー状態かのチェック */
+		return (E_SYS);
+	}
+
+	buffer_full = true; /* ループの1回めはwai_semする */
 	while (wricnt < len) {
 		if (buffer_full) {
 			SVC(rercd = wai_sem(p_spcb->p_spinib->snd_semid),
-										gen_ercd_wait(rercd, p_spcb));
+				gen_ercd_wait(rercd, p_spcb));
 		}
 		SVC(rercd = serial_wri_chr(p_spcb, *buf++), rercd);
 		wricnt++;
-		buffer_full = (bool_t) rercd;
+		buffer_full = (bool_t)rercd;
 	}
 	if (!buffer_full) {
@@ -497,6 +497,6 @@
 	ercd = E_OK;
 
-  error_exit:
-	return(wricnt > 0U ? (ER_UINT) wricnt : ercd);
+error_exit:
+	return (wricnt > 0U ? (ER_UINT)wricnt : ercd);
 }
 
@@ -507,6 +507,6 @@
 serial_rea_chr(SPCB *p_spcb, char *p_c)
 {
-	bool_t	buffer_empty;
-	ER		ercd;
+	bool_t buffer_empty;
+	ER ercd;
 
 	SVC(loc_cpu(), gen_ercd_sys(p_spcb));
@@ -523,6 +523,6 @@
 	 *  STARTを送信する．
 	 */
-	if (p_spcb->rcv_stopped && p_spcb->rcv_count
-								<= BUFCNT_START(p_spcb->p_spinib->rcv_bufsz)) {
+	if (p_spcb->rcv_stopped
+		&& p_spcb->rcv_count <= BUFCNT_START(p_spcb->p_spinib->rcv_bufsz)) {
 		if (!serial_snd_chr(p_spcb, FC_START)) {
 			p_spcb->rcv_fc_chr = FC_START;
@@ -532,8 +532,8 @@
 
 	SVC(unl_cpu(), gen_ercd_sys(p_spcb));
-	ercd = (ER_BOOL) buffer_empty;
-
-  error_exit:
-	return(ercd);
+	ercd = (ER_BOOL)buffer_empty;
+
+error_exit:
+	return (ercd);
 }
 
@@ -544,35 +544,35 @@
 serial_rea_dat(ID portid, char *buf, uint_t len)
 {
-	SPCB	*p_spcb;
-	bool_t	buffer_empty;
-	uint_t	reacnt = 0U;
-	char	c = '\0';		/* コンパイラの警告を抑止するために初期化する */
-	ER		ercd, rercd;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+	bool_t buffer_empty;
+	uint_t reacnt = 0U;
+	char c = '\0'; /* コンパイラの警告を抑止するために初期化する */
+	ER ercd, rercd;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 
 	p_spcb = get_spcb(portid);
-	if (!(p_spcb->openflag)) {		/* オープン済みかのチェック */
-		return(E_OBJ);
-	}
-	if (p_spcb->errorflag) {		/* エラー状態かのチェック */
-		return(E_SYS);
-	}
-
-	buffer_empty = true;			/* ループの1回めはwai_semする */
+	if (!(p_spcb->openflag)) { /* オープン済みかのチェック */
+		return (E_OBJ);
+	}
+	if (p_spcb->errorflag) { /* エラー状態かのチェック */
+		return (E_SYS);
+	}
+
+	buffer_empty = true; /* ループの1回めはwai_semする */
 	while (reacnt < len) {
 		if (buffer_empty) {
 			SVC(rercd = wai_sem(p_spcb->p_spinib->rcv_semid),
-										gen_ercd_wait(rercd, p_spcb));
+				gen_ercd_wait(rercd, p_spcb));
 		}
 		SVC(rercd = serial_rea_chr(p_spcb, &c), rercd);
 		*buf++ = c;
 		reacnt++;
-		buffer_empty = (bool_t) rercd;
+		buffer_empty = (bool_t)rercd;
 
 		/*
@@ -581,9 +581,9 @@
 		if ((p_spcb->ioctl & IOCTL_ECHO) != 0U) {
 			SVC(rercd = wai_sem(p_spcb->p_spinib->snd_semid),
-										gen_ercd_wait(rercd, p_spcb));
+				gen_ercd_wait(rercd, p_spcb));
 			SVC(rercd = serial_wri_chr(p_spcb, c), rercd);
-			if (!((bool_t) rercd)) {
+			if (!((bool_t)rercd)) {
 				SVC(sig_sem(p_spcb->p_spinib->snd_semid),
-										gen_ercd_sys(p_spcb));
+					gen_ercd_sys(p_spcb));
 			}
 		}
@@ -594,6 +594,6 @@
 	ercd = E_OK;
 
-  error_exit:
-	return(reacnt > 0U ? (ER_UINT) reacnt : ercd);
+error_exit:
+	return (reacnt > 0U ? (ER_UINT)reacnt : ercd);
 }
 
@@ -604,23 +604,23 @@
 serial_ctl_por(ID portid, uint_t ioctl)
 {
-	SPCB	*p_spcb;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 
 	p_spcb = get_spcb(portid);
-	if (!(p_spcb->openflag)) {		/* オープン済みかのチェック */
-		return(E_OBJ);
-	}
-	if (p_spcb->errorflag) {		/* エラー状態かのチェック */
-		return(E_SYS);
+	if (!(p_spcb->openflag)) { /* オープン済みかのチェック */
+		return (E_OBJ);
+	}
+	if (p_spcb->errorflag) { /* エラー状態かのチェック */
+		return (E_SYS);
 	}
 
 	p_spcb->ioctl = ioctl;
-	return(E_OK);
+	return (E_OK);
 }
 
@@ -631,24 +631,24 @@
 serial_ref_por(ID portid, T_SERIAL_RPOR *pk_rpor)
 {
-	SPCB	*p_spcb;
-
-	if (sns_dpn()) {				/* コンテキストのチェック */
-		return(E_CTX);
+	SPCB *p_spcb;
+
+	if (sns_dpn()) { /* コンテキストのチェック */
+		return (E_CTX);
 	}
 	if (!(1 <= portid && portid <= TNUM_PORT)) {
-		return(E_ID);				/* ポート番号のチェック */
+		return (E_ID); /* ポート番号のチェック */
 	}
 
 	p_spcb = get_spcb(portid);
-	if (!(p_spcb->openflag)) {		/* オープン済みかのチェック */
-		return(E_OBJ);
-	}
-	if (p_spcb->errorflag) {		/* エラー状態かのチェック */
-		return(E_SYS);
+	if (!(p_spcb->openflag)) { /* オープン済みかのチェック */
+		return (E_OBJ);
+	}
+	if (p_spcb->errorflag) { /* エラー状態かのチェック */
+		return (E_SYS);
 	}
 
 	pk_rpor->reacnt = p_spcb->rcv_count;
 	pk_rpor->wricnt = p_spcb->snd_count;
-	return(E_OK);
+	return (E_OK);
 }
 
@@ -659,33 +659,38 @@
 sio_irdy_snd(intptr_t exinf)
 {
-	SPCB	*p_spcb;
-
-	p_spcb = (SPCB *) exinf;
-	if (p_spcb->rcv_fc_chr != '\0') {
-		/*
-		 *  START/STOP を送信する．
-		 */
-		(void) sio_snd_chr(p_spcb->p_siopcb, p_spcb->rcv_fc_chr);
-		p_spcb->rcv_fc_chr = '\0';
-	}
-	else if (!(p_spcb->snd_stopped) && p_spcb->snd_count > 0U) {
-		/*
-		 *  送信バッファ中から文字を取り出して送信する．
-		 */
-		(void) sio_snd_chr(p_spcb->p_siopcb,
-					p_spcb->p_spinib->snd_buffer[p_spcb->snd_read_ptr]);
-		INC_PTR(p_spcb->snd_read_ptr, p_spcb->p_spinib->snd_bufsz);
-		if (p_spcb->snd_count == p_spcb->p_spinib->snd_bufsz) {
-			if (isig_sem(p_spcb->p_spinib->snd_semid) < 0) {
-				p_spcb->errorflag = true;
+	SPCB *p_spcb;
+
+	p_spcb = (SPCB *)exinf;
+	for (;;) {
+		if (p_spcb->rcv_fc_chr != '\0') {
+			/*
+			*  START/STOP を送信する．
+			*/
+			if (!sio_snd_chr(p_spcb->p_siopcb, p_spcb->rcv_fc_chr))
+				break;
+			p_spcb->rcv_fc_chr = '\0';
+		}
+		else if (!(p_spcb->snd_stopped) && p_spcb->snd_count > 0U) {
+			/*
+			*  送信バッファ中から文字を取り出して送信する．
+			*/
+			if (!sio_snd_chr(p_spcb->p_siopcb,
+							 p_spcb->p_spinib->snd_buffer[p_spcb->snd_read_ptr]))
+				break;
+			INC_PTR(p_spcb->snd_read_ptr, p_spcb->p_spinib->snd_bufsz);
+			if (p_spcb->snd_count == p_spcb->p_spinib->snd_bufsz) {
+				if (isig_sem(p_spcb->p_spinib->snd_semid) < 0) {
+					p_spcb->errorflag = true;
+				}
 			}
-		}
-		p_spcb->snd_count--;
-	}
-	else {
-		/*
-		 *  送信すべき文字がない場合は，送信可能コールバックを禁止する．
-		 */
-		sio_dis_cbr(p_spcb->p_siopcb, SIO_RDY_SND);
+			p_spcb->snd_count--;
+		}
+		else {
+			/*
+			*  送信すべき文字がない場合は，送信可能コールバックを禁止する．
+			*/
+			sio_dis_cbr(p_spcb->p_siopcb, SIO_RDY_SND);
+			break;
+		}
 	}
 }
@@ -697,67 +702,70 @@
 sio_irdy_rcv(intptr_t exinf)
 {
-	SPCB	*p_spcb;
-	char	c;
-
-	p_spcb = (SPCB *) exinf;
-	c = (char) sio_rcv_chr(p_spcb->p_siopcb);
-	if ((p_spcb->ioctl & IOCTL_FCSND) != 0U && c == FC_STOP) {
-		/*
-		 *  送信を一時停止する．送信中の文字はそのまま送信する．
-		 */
-		p_spcb->snd_stopped = true;
-	}
-	else if (p_spcb->snd_stopped && (c == FC_START
-				|| (p_spcb->ioctl & IOCTL_FCANY) != 0U)) {
-		/*
-		 *  送信を再開する．
-		 */
-		p_spcb->snd_stopped = false;
-		if (p_spcb->snd_count > 0U) {
-			c = p_spcb->p_spinib->snd_buffer[p_spcb->snd_read_ptr];
-			if (serial_snd_chr(p_spcb, c)) {
-				INC_PTR(p_spcb->snd_read_ptr, p_spcb->p_spinib->snd_bufsz);
-				if (p_spcb->snd_count == p_spcb->p_spinib->snd_bufsz) {
-					if (isig_sem(p_spcb->p_spinib->snd_semid) < 0) {
-						p_spcb->errorflag = true;
+	SPCB *p_spcb;
+	int_t c;
+
+	p_spcb = (SPCB *)exinf;
+	for (;;) {
+		c = sio_rcv_chr(p_spcb->p_siopcb);
+		if (c < 0)
+			break;
+		if ((p_spcb->ioctl & IOCTL_FCSND) != 0U && c == FC_STOP) {
+			/*
+			*  送信を一時停止する．送信中の文字はそのまま送信する．
+			*/
+			p_spcb->snd_stopped = true;
+		}
+		else if (p_spcb->snd_stopped && (c == FC_START
+			|| (p_spcb->ioctl & IOCTL_FCANY) != 0U)) {
+			/*
+			*  送信を再開する．
+			*/
+			p_spcb->snd_stopped = false;
+			if (p_spcb->snd_count > 0U) {
+				c = p_spcb->p_spinib->snd_buffer[p_spcb->snd_read_ptr];
+				if (serial_snd_chr(p_spcb, c)) {
+					INC_PTR(p_spcb->snd_read_ptr, p_spcb->p_spinib->snd_bufsz);
+					if (p_spcb->snd_count == p_spcb->p_spinib->snd_bufsz) {
+						if (isig_sem(p_spcb->p_spinib->snd_semid) < 0) {
+							p_spcb->errorflag = true;
+						}
 					}
+					p_spcb->snd_count--;
 				}
-				p_spcb->snd_count--;
 			}
 		}
-	}
-	else if ((p_spcb->ioctl & IOCTL_FCSND) != 0U && c == FC_START) {
-		/*
-		 *  送信に対してフロー制御している場合，START は捨てる．
-		 */
-	}
-	else if (p_spcb->rcv_count == p_spcb->p_spinib->rcv_bufsz) {
-		/*
-		 *  バッファフルの場合，受信した文字を捨てる．
-		 */
-	}
-	else {
-		/*
-		 *  受信した文字を受信バッファに入れる．
-		 */
-		p_spcb->p_spinib->rcv_buffer[p_spcb->rcv_write_ptr] = c;
-		INC_PTR(p_spcb->rcv_write_ptr, p_spcb->p_spinib->rcv_bufsz);
-		if (p_spcb->rcv_count == 0U) {
-			if (isig_sem(p_spcb->p_spinib->rcv_semid) < 0) {
-				p_spcb->errorflag = true;
+		else if ((p_spcb->ioctl & IOCTL_FCSND) != 0U && c == FC_START) {
+			/*
+			*  送信に対してフロー制御している場合，START は捨てる．
+			*/
+		}
+		else if (p_spcb->rcv_count == p_spcb->p_spinib->rcv_bufsz) {
+			/*
+			*  バッファフルの場合，受信した文字を捨てる．
+			*/
+		}
+		else {
+			/*
+			*  受信した文字を受信バッファに入れる．
+			*/
+			p_spcb->p_spinib->rcv_buffer[p_spcb->rcv_write_ptr] = c;
+			INC_PTR(p_spcb->rcv_write_ptr, p_spcb->p_spinib->rcv_bufsz);
+			if (p_spcb->rcv_count == 0U) {
+				if (isig_sem(p_spcb->p_spinib->rcv_semid) < 0) {
+					p_spcb->errorflag = true;
+				}
 			}
-		}
-		p_spcb->rcv_count++;
-
-		/*
-		 *  STOPを送信する．
-		 */
-		if ((p_spcb->ioctl & IOCTL_FCRCV) != 0U && !(p_spcb->rcv_stopped)
-						&& p_spcb->rcv_count
-							>= BUFCNT_STOP(p_spcb->p_spinib->rcv_bufsz)) {
-			if (!serial_snd_chr(p_spcb, FC_STOP)) {
-				p_spcb->rcv_fc_chr = FC_STOP;
+			p_spcb->rcv_count++;
+
+			/*
+			*  STOPを送信する．
+			*/
+			if ((p_spcb->ioctl & IOCTL_FCRCV) != 0U && !(p_spcb->rcv_stopped)
+				&& p_spcb->rcv_count >= BUFCNT_STOP(p_spcb->p_spinib->rcv_bufsz)) {
+				if (!serial_snd_chr(p_spcb, FC_STOP)) {
+					p_spcb->rcv_fc_chr = FC_STOP;
+				}
+				p_spcb->rcv_stopped = true;
 			}
-			p_spcb->rcv_stopped = true;
 		}
 	}
@@ -770,17 +778,17 @@
 serial_get_chr(ID portid, char *p_c)
 {
-	SPCB	*p_spcb;
-
-	if (1 <= portid && portid <= TNUM_PORT) {	/* ポート番号のチェック */
+	SPCB *p_spcb;
+
+	if (1 <= portid && portid <= TNUM_PORT) { /* ポート番号のチェック */
 		p_spcb = get_spcb(portid);
-		if (p_spcb->openflag) {					/* オープン済みかのチェック */
+		if (p_spcb->openflag) { /* オープン済みかのチェック */
 			if (p_spcb->snd_count > 0U) {
 				*p_c = p_spcb->p_spinib->snd_buffer[p_spcb->snd_read_ptr];
 				INC_PTR(p_spcb->snd_read_ptr, p_spcb->p_spinib->snd_bufsz);
 				p_spcb->snd_count--;
-				return(true);
+				return (true);
 			}
 		}
 	}
-	return(false);
-}
+	return (false);
+}
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/Makefile.target
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/Makefile.target	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/Makefile.target	(revision 458)
@@ -56,5 +56,5 @@
 #  リンカスクリプトの定義
 #
-LDSCRIPT = $(SRCDIR)/arch/$(PRC)_$(TOOL)/riscv64elf.ld
+LDSCRIPT = $(TARGETDIR)/kendryte-k210.ld
 
 #
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/kendryte-k210.ld
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/kendryte-k210.ld	(revision 458)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/kendryte-k210.ld	(revision 458)
@@ -0,0 +1,110 @@
+/*
+ *  @(#) $Id$
+ */
+
+MEMORY
+{
+  /*
+   * Memory with CPU cache.
+   *6M CPU SRAM
+   */
+  ram (wxa!ri) : ORIGIN = 0x80000000, LENGTH = (6 * 1024 * 1024)
+  /*
+   * Memory without CPU cache
+   * 6M CPU SRAM
+  */
+  ram_nocache (wxa!ri) : ORIGIN = 0x40000000, LENGTH = (6 * 1024 * 1024)
+}
+
+OUTPUT_ARCH(riscv)
+
+PROVIDE(hardware_init_hook = 0);
+PROVIDE(software_init_hook = 0);
+PROVIDE(software_term_hook = 0);
+PROVIDE(__idata_start = 0);
+PROVIDE(__idata_end = 0);
+STARTUP(start.o)
+
+SECTIONS
+{
+    __stack_size = DEFINED(__stack_size) ? __stack_size : 8K;
+
+    .init :
+    {
+        KEEP (*(.init))
+    }>ram
+    .text :
+    {
+        __text = . ;
+        *(.text .stub .text.* .gnu.linkonce.t.*)
+
+    }>ram
+    .fini :
+    {
+        KEEP (*(.fini))
+    }>ram
+    _etext = . ;
+    PROVIDE (etext = .) ;
+    .rodata :
+    {
+        *(.rodata .rodata.* .gnu.linkonce.r.*)
+    }>ram
+    . = ALIGN(8);
+    .data : 
+    {
+        __data_start = . ;
+        /* Writable data segment (.data segment) */
+        *(.data .data.*)
+        *(.sdata .sdata.* .sdata2 .sdata2.*)
+        . = ALIGN(8);
+        PROVIDE( __global_pointer$ = ABSOLUTE(.) + 0x800);
+    }>ram
+    .eh_frame : { KEEP (*(.eh_frame)) }>ram
+    .gcc_except_table : { *(.gcc_except_table .gcc_except_table.*) }>ram
+    .ctors :
+    {
+        KEEP (*crtbegin.o(.ctors))
+        KEEP (*(EXCLUDE_FILE (*crtend.o ) .ctors))
+        KEEP (*(SORT(.ctors.*)))
+        KEEP (*(.ctors))
+    }>ram
+    .dtors :
+    {
+        KEEP (*crtbegin.o(.dtors))
+        KEEP (*(EXCLUDE_FILE (*crtend.o ) .dtors))
+        KEEP (*(SORT(.dtors.*)))
+        KEEP (*(.dtors))
+    }>ram
+    _edata  = . ;
+    PROVIDE (edata = .) ;
+    . = ALIGN(8) ;
+    __bss_start = . ;
+    _bss = .;
+    .bss :
+    {
+        *(.bss .bss.*)
+        *(.sbss .sbss.* .sbss2 .sbss2.*)
+        *(COMMON)
+    }>ram
+    _end = . ;
+    __bss_end = . ;
+    _ebss = . ;
+    .stack (NOLOAD) :
+    {
+    	*(.stack)
+    }>ram
+    .heap (NOLOAD) :
+    {
+        PROVIDE (_heap_start = .) ;
+        *(.heap)
+    }>ram
+    PROVIDE (_heap_end = .) ;
+    PROVIDE (end = .) ;
+    .comment        0 : { *(.comment) }
+    .debug          0 : { *(.debug) }
+    .line           0 : { *(.line) }
+    .debug_srcinfo  0 : { *(.debug_srcinfo) }
+    .debug_sfnames  0 : { *(.debug_sfnames) }
+    .debug_aranges  0 : { *(.debug_aranges) }
+    .debug_pubnames 0 : { *(.debug_pubnames) }
+}
Index: azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/target_serial.c
===================================================================
--- azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/target_serial.c	(revision 454)
+++ azure_iot_hub_riscv/trunk/asp_baseplatform/target/k210_gcc/target_serial.c	(revision 458)
@@ -55,17 +55,17 @@
  *  SIL関数のマクロ定義
  */
-#define sil_orw_mem(a, b)		sil_wrw_mem((a), sil_rew_mem(a) | (b))
-#define sil_andw_mem(a, b)		sil_wrw_mem((a), sil_rew_mem(a) & ~(b))
+#define sil_orw_mem(a, b) sil_wrw_mem((a), sil_rew_mem(a) | (b))
+#define sil_andw_mem(a, b) sil_wrw_mem((a), sil_rew_mem(a) & ~(b))
 
 /*
  * レジスタ設定値
  */
-#define INDEX_PORT(x)	((x) - 1)
-#define GET_SIOPCB(x)	(&siopcb_table[INDEX_PORT(x)])
-
-#define __UART_BRATE_CONST  16
+#define INDEX_PORT(x) ((x)-1)
+#define GET_SIOPCB(x) (&siopcb_table[INDEX_PORT(x)])
+
+#define __UART_BRATE_CONST 16
 
 #ifndef COM0
-#define COM0                0
+#define COM0 0
 #endif
 
@@ -73,36 +73,36 @@
  *  ビット長パラメータ
  */
-#define UART_WordLength_5B  0x00000000
-#define UART_WordLength_6B  0x00000001
-#define UART_WordLength_7B  0x00000002
-#define UART_WordLength_8b  0x00000003
+#define UART_WordLength_5B 0x00000000
+#define UART_WordLength_6B 0x00000001
+#define UART_WordLength_7B 0x00000002
+#define UART_WordLength_8b 0x00000003
 
 /*
  *  ストップビットパラメータ
- */ 
-#define UART_StopBits_1     0x00000000
-#define UART_StopBits_1_5   UART_LCR_STB
+ */
+#define UART_StopBits_1 0x00000000
+#define UART_StopBits_1_5 UART_LCR_STB
 
 /*
  *  パリティパラメータ
  */
-#define UART_Parity_No      0x00000000
-#define UART_Parity_Odd     UART_LCR_PARITY
-#define UART_Parity_Even    (UART_LCR_PARITY | UART_LCR_PEVEN)
+#define UART_Parity_No 0x00000000
+#define UART_Parity_Odd UART_LCR_PARITY
+#define UART_Parity_Even (UART_LCR_PARITY | UART_LCR_PEVEN)
 
 /*
  *  送信FIFO
  */
-#define UART_SEND_FIFO0     0
-#define UART_SEND_FIFO2     1
-#define UART_SEND_FIFO4     2
-#define UART_SEND_FIFO8     3
+#define UART_SEND_FIFO0 0
+#define UART_SEND_FIFO2 1
+#define UART_SEND_FIFO4 2
+#define UART_SEND_FIFO8 3
 
 /*
  *  受信FIFO
  */
-#define UART_RECEIVE_FIFO1  0
-#define UART_RECEIVE_FIFO4  1
-#define UART_RECEIVE_FIFO8  2
+#define UART_RECEIVE_FIFO1 0
+#define UART_RECEIVE_FIFO4 1
+#define UART_RECEIVE_FIFO8 2
 #define UART_RECEIVE_FIFO14 3
 
@@ -112,9 +112,9 @@
 typedef struct sio_port_initialization_block {
 	uint64_t base;
-	INTNO    intno_usart;
+	INTNO intno_usart;
 	uint32_t clk;
-	uint8_t  txfunc;
-	uint8_t  rxfunc;
-	uint8_t  com;
+	uint8_t txfunc;
+	uint8_t rxfunc;
+	uint8_t com;
 } SIOPINIB;
 
@@ -123,7 +123,7 @@
  */
 struct sio_port_control_block {
-	const SIOPINIB  *p_siopinib;  /* シリアルI/Oポート初期化ブロック */
-	intptr_t        exinf;        /* 拡張情報 */
-	bool_t          opnflg;       /* オープン済みフラグ */
+	const SIOPINIB *p_siopinib; /* シリアルI/Oポート初期化ブロック */
+	intptr_t exinf;				/* 拡張情報 */
+	bool_t opnflg;				/* オープン済みフラグ */
 };
 
@@ -134,5 +134,5 @@
 	{(uint32_t)TADR_UART1_BASE, (INTNO)IRQ_VECTOR_UART1, SYSCTL_CLK_EN_PERI_UART1_CLK_EN, FUNC_UART1_TX, FUNC_UART1_RX, COM0},
 #if TNUM_SIOP >= 2
-	{(uint32_t)TADR_UART3_BASE, (INTNO)IRQ_VECTOR_UART3, SYSCTL_CLK_EN_PERI_UART3_CLK_EN, FUNC_UART3_TX, FUNC_UART3_RX, COM0^1}
+	{(uint32_t)TADR_UART3_BASE, (INTNO)IRQ_VECTOR_UART3, SYSCTL_CLK_EN_PERI_UART3_CLK_EN, FUNC_UART3_TX, FUNC_UART3_RX, COM0 ^ 1}
 #endif
 };
@@ -142,6 +142,6 @@
  */
 static uint8_t uartpin[2][2] = {
-	{5, 4},		/* com0 tx, rx */
-	{6, 7},		/* com1 tx, rx */
+	{5, 4}, /* com0 tx, rx */
+	{6, 7}, /* com1 tx, rx */
 };
 
@@ -149,11 +149,11 @@
  *  シリアルI/Oポート管理ブロックのエリア
  */
-SIOPCB	siopcb_table[TNUM_SIOP];
+SIOPCB siopcb_table[TNUM_SIOP];
 
 /*
  *  シリアルI/OポートIDから管理ブロックを取り出すためのマクロ
  */
-#define INDEX_SIOP(siopid)	((uint_t)((siopid) - 1))
-#define get_siopcb(siopid)	(&(siopcb_table[INDEX_SIOP(siopid)]))
+#define INDEX_SIOP(siopid) ((uint_t)((siopid)-1))
+#define get_siopcb(siopid) (&(siopcb_table[INDEX_SIOP(siopid)]))
 
 extern uint32_t get_pll_clock(uint8_t no);
@@ -166,15 +166,14 @@
 get_clock_aclk(void)
 {
-	uint32_t clk_sel0 = sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_CLK_SEL0));
+	uint32_t clk_sel0 = sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_CLK_SEL0));
 	uint32_t select = clk_sel0 & SYSCTL_CLK_SEL0_ACLK_SEL;
 	uint32_t source = 0;
 
-	if(select == 0)
+	if (select == 0)
 		source = SYSCTRL_CLOCK_FREQ_IN0;
-	else if(select == 1)
-		source = get_pll_clock(0) / (2UL << ((clk_sel0 & SYSCTL_CLK_SEL0_ACLK_SDIVISER)>>1));
+	else if (select == 1)
+		source = get_pll_clock(0) / (2UL << ((clk_sel0 & SYSCTL_CLK_SEL0_ACLK_SDIVISER) >> 1));
 	return source;
 }
-
 
 void put_hex(char a, int val)
@@ -183,8 +182,8 @@
 	target_fput_log(a);
 	target_fput_log(' ');
-	for(i = 28 ; i >= 0 ; i-= 4){
-		j = (val >> i) & 0xf;;
-		if(j > 9)
-			j += ('A'-10);
+	for (i = 28; i >= 0; i -= 4) {
+		j = (val >> i) & 0xf;
+		if (j > 9)
+			j += ('A' - 10);
 		else
 			j += '0';
@@ -200,6 +199,6 @@
 sio_initialize(intptr_t exinf)
 {
-	SIOPCB	*p_siopcb;
-	uint_t	i;
+	SIOPCB *p_siopcb;
+	uint_t i;
 
 	/*
@@ -212,5 +211,4 @@
 }
 
-
 /*
  *  シリアルI/Oポートのオープン
@@ -219,11 +217,11 @@
 sio_opn_por(ID siopid, intptr_t exinf)
 {
-	SIOPCB          *p_siopcb;
-	const SIOPINIB  *p_siopinib;
-	bool_t   opnflg;
-	ER       ercd;
+	SIOPCB *p_siopcb;
+	const SIOPINIB *p_siopinib;
+	bool_t opnflg;
+	ER ercd;
 	unsigned long base;
 	uint32_t divisor, threshold, tmp;
-	uint8_t  dlh, dll, dlf;
+	uint8_t dlh, dll, dlf;
 
 	p_siopcb = get_siopcb(siopid);
@@ -237,5 +235,5 @@
 	p_siopcb->exinf = exinf;
 	base = p_siopinib->base;
-	if(base == 0)				/* no uart port */
+	if (base == 0) /* no uart port */
 		goto sio_opn_exit;
 
@@ -243,31 +241,33 @@
 	 *  ハードウェアの初期化
 	 */
-	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
-
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_IER), 0x00000000);
+	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
+
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_IER), 0x00000000);
 	sil_dly_nse(10000);
 
-	threshold = (sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_CLK_SEL0)) & SYSCTL_CLK_SEL0_APB0_CLK_SEL) >> 3;
-    divisor = (get_clock_aclk() / (threshold+1)) / BPS_SETTING;
-    dlh = divisor >> 12;
-    dll = (divisor - (dlh << 12)) / __UART_BRATE_CONST;
-    dlf = divisor - (dlh << 12) - dll * __UART_BRATE_CONST;
-
-    /* Set UART registers */
-	sil_orw_mem((uint32_t *)(base+TOFF_UART_LCR), UART_LCR_DMD);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLH), dlh);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLL), dll);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLF), dlf);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_LCR), 0x00);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_LCR), (UART_WordLength_8b | UART_StopBits_1 | UART_Parity_No));
-	sil_andw_mem((uint32_t *)(base+TOFF_UART_LCR), UART_LCR_DMD);
-	sil_orw_mem((uint32_t *)(base+TOFF_UART_IER), UART_IER_THRE);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_FCR),
-			(UART_RECEIVE_FIFO1 << 6 | UART_SEND_FIFO8 << 4 | 0x1 << 3 | 0x1));
+	threshold = (sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_CLK_SEL0)) & SYSCTL_CLK_SEL0_APB0_CLK_SEL) >> 3;
+	divisor = (get_clock_aclk() / (threshold + 1)) / BPS_SETTING;
+	dlh = divisor >> 12;
+	dll = (divisor - (dlh << 12)) / __UART_BRATE_CONST;
+	dlf = divisor - (dlh << 12) - dll * __UART_BRATE_CONST;
+
+	/* Set UART registers */
+	sil_orw_mem((uint32_t *)(base + TOFF_UART_LCR), UART_LCR_DMD);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLH), dlh);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLL), dll);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLF), dlf);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_LCR), 0x00);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_LCR), (UART_WordLength_8b | UART_StopBits_1 | UART_Parity_No));
+	sil_andw_mem((uint32_t *)(base + TOFF_UART_LCR), UART_LCR_DMD);
+	sil_orw_mem((uint32_t *)(base + TOFF_UART_IER), UART_IER_THRE);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_FCR),
+				(UART_RECEIVE_FIFO14 << 6 | UART_SEND_FIFO8 << 4 /*| 0x1 << 3 DMA mode?*/ | 0x1 /*FIFO enable?*/));
+	sil_andw_mem((uint32_t *)(base + TOFF_UART_MCR), (1 << 6) | 3);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_TCR), 0x00);
 
 	fpioa_set_function(uartpin[p_siopinib->com][1], p_siopinib->rxfunc);
 	fpioa_set_function(uartpin[p_siopinib->com][0], p_siopinib->txfunc);
-	sil_orw_mem((uint32_t *)(base+TOFF_UART_IER), UART_IER_RIE);
-	tmp = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_RBR));
+	sil_orw_mem((uint32_t *)(base + TOFF_UART_IER), UART_IER_RIE);
+	tmp = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_RBR));
 	p_siopcb->opnflg = true;
 	(void)(tmp);
@@ -283,5 +283,5 @@
 
 sio_opn_exit:;
-	return(p_siopcb);
+	return (p_siopcb);
 }
 
@@ -292,5 +292,5 @@
 sio_cls_por(SIOPCB *p_siopcb)
 {
-	const SIOPINIB  *p_siopinib;
+	const SIOPINIB *p_siopinib;
 
 	p_siopinib = p_siopcb->p_siopinib;
@@ -305,6 +305,6 @@
 	 *  シリアル停止
 	 */
-	sil_wrw_mem((uint32_t *)(p_siopinib->base+TOFF_UART_IER), 0x00000000);
-	sil_andw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
+	sil_wrw_mem((uint32_t *)(p_siopinib->base + TOFF_UART_IER), 0x00000000);
+	sil_andw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
 	p_siopcb->opnflg = false;
 }
@@ -318,19 +318,25 @@
 	SIOPCB *p_siopcb = get_siopcb(exinf);
 	unsigned long base = p_siopcb->p_siopinib->base;
-	uint32_t ip = sil_rew_mem((uint32_t *)(base+TOFF_UART_IIR)) & 0x0F;
 	uint32_t tmp;
 
-	if(ip == UART_IIR_RECEIVE || ip == UART_IIR_CTIMEOUT){
-		sio_irdy_rcv(p_siopcb->exinf);
-	}
-	else if(ip == UART_IIR_SEND){
-		sio_irdy_snd(p_siopcb->exinf);
-	}
-	else{
-		tmp = sil_rew_mem((uint32_t *)(base+TOFF_UART_LSR));
-		tmp = sil_rew_mem((uint32_t *)(base+TOFF_UART_USR));
-		tmp = sil_rew_mem((uint32_t *)(base+TOFF_UART_MSR));
-	}
-	(void)(tmp);
+	for (;;) {
+		uint32_t ip = sil_rew_mem((uint32_t *)(base + TOFF_UART_IIR)) & 0x0F;
+
+		if (ip == 1) {
+			break;
+		}
+		else if (ip == UART_IIR_RECEIVE || ip == UART_IIR_CTIMEOUT) {
+			sio_irdy_rcv(p_siopcb->exinf);
+		}
+		else if (ip == UART_IIR_SEND) {
+			sio_irdy_snd(p_siopcb->exinf);
+		}
+		else {
+			tmp = sil_rew_mem((uint32_t *)(base + TOFF_UART_LSR));
+			tmp = sil_rew_mem((uint32_t *)(base + TOFF_UART_USR));
+			tmp = sil_rew_mem((uint32_t *)(base + TOFF_UART_MSR));
+		}
+		(void)(tmp);
+	}
 }
 
@@ -339,9 +345,9 @@
  */
 Inline bool_t
-sio_putready(SIOPCB* p_siopcb)
-{
-	uint32_t lsr = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_LSR));
-
-	if((lsr & UART_LSR_TFL) == 0){
+sio_putready(SIOPCB *p_siopcb)
+{
+	uint32_t lsr = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_LSR));
+
+	if ((lsr & UART_LSR_TFL) == 0) {
 		return 1;
 	}
@@ -352,6 +358,6 @@
 sio_snd_chr(SIOPCB *p_siopcb, char c)
 {
-	if(sio_putready(p_siopcb)){
-		sil_wrw_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_THR), (uint32_t)c);
+	if (sio_putready(p_siopcb)) {
+		sil_wrw_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_THR), (uint32_t)c);
 		return true;
 	}
@@ -367,6 +373,6 @@
 	int_t c = -1;
 
-	if((sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_LSR)) & UART_LSR_RFL) != 0){
-		c = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_RBR)) & 0xFF;
+	if ((sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_LSR)) & UART_LSR_RFL) != 0) {
+		c = sil_rew_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_RBR)) & 0xFF;
 	}
 	return c;
@@ -381,8 +387,8 @@
 	switch (cbrtn) {
 	case SIO_RDY_SND:
-		sil_orw_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_IER), UART_IER_TIE);
+		sil_orw_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_IER), UART_IER_TIE);
 		break;
 	case SIO_RDY_RCV:
-		sil_orw_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_IER), UART_IER_RIE);
+		sil_orw_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_IER), UART_IER_RIE);
 		break;
 	}
@@ -397,8 +403,8 @@
 	switch (cbrtn) {
 	case SIO_RDY_SND:
-		sil_andw_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_IER), UART_IER_TIE);
+		sil_andw_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_IER), UART_IER_TIE);
 		break;
 	case SIO_RDY_RCV:
-		sil_andw_mem((uint32_t *)(p_siopcb->p_siopinib->base+TOFF_UART_IER), UART_IER_RIE);
+		sil_andw_mem((uint32_t *)(p_siopcb->p_siopinib->base + TOFF_UART_IER), UART_IER_RIE);
 		break;
 	}
@@ -412,12 +418,14 @@
 	unsigned long base = siopinib_table[INDEX_PORT(siopid)].base;
 
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_THR), (uint32_t)c);
-	while(0 != (sil_rew_mem((uint32_t *)(base+TOFF_UART_LSR)) & UART_LSR_TFL));
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_THR), (uint32_t)c);
+	while (0 != (sil_rew_mem((uint32_t *)(base + TOFF_UART_LSR)) & UART_LSR_TFL))
+		;
 
 	/*
 	 *  出力が完全に終わるまで待つ
 	 */
-	volatile int n = SYS_CLOCK/BPS_SETTING;
-	while(n--);
+	volatile int n = SYS_CLOCK / BPS_SETTING;
+	while (n--)
+		;
 }
 
@@ -427,8 +435,8 @@
 void target_uart_init(ID siopid)
 {
-	const SIOPINIB  *p_siopinib;
+	const SIOPINIB *p_siopinib;
 	unsigned long base;
 	uint32_t divisor, threshold;
-	uint8_t  dlh, dll, dlf;
+	uint8_t dlh, dll, dlf;
 
 	p_siopinib = &siopinib_table[INDEX_PORT(siopid)];
@@ -438,23 +446,25 @@
 	 *  ハードウェアの初期化
 	 */
-	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
-
-	threshold = (sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE+TOFF_CLK_SEL0)) & SYSCTL_CLK_SEL0_APB0_CLK_SEL) >> 3;
-    divisor = (get_clock_aclk() / (threshold+1)) / BPS_SETTING;
-    dlh = divisor >> 12;
-    dll = (divisor - (dlh << 12)) / __UART_BRATE_CONST;
-    dlf = divisor - (dlh << 12) - dll * __UART_BRATE_CONST;
-
-    /* Set UART registers */
-	sil_orw_mem((uint32_t *)(base+TOFF_UART_LCR), UART_LCR_DMD);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLH), dlh);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLL), dll);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_DLF), dlf);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_LCR), 0x00);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_LCR), (UART_WordLength_8b | UART_StopBits_1 | UART_Parity_No));
-	sil_andw_mem((uint32_t *)(base+TOFF_UART_LCR), UART_LCR_DMD);
-	sil_orw_mem((uint32_t *)(base+TOFF_UART_IER), UART_IER_THRE);
-	sil_wrw_mem((uint32_t *)(base+TOFF_UART_FCR),
-			(UART_RECEIVE_FIFO1 << 6 | UART_SEND_FIFO8 << 4 | 0x1 << 3 | 0x1));
+	sil_orw_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_SYSCTL_CLK_EN_PERI), p_siopinib->clk);
+
+	threshold = (sil_rew_mem((uint32_t *)(TADR_SYSCTL_BASE + TOFF_CLK_SEL0)) & SYSCTL_CLK_SEL0_APB0_CLK_SEL) >> 3;
+	divisor = (get_clock_aclk() / (threshold + 1)) / BPS_SETTING;
+	dlh = divisor >> 12;
+	dll = (divisor - (dlh << 12)) / __UART_BRATE_CONST;
+	dlf = divisor - (dlh << 12) - dll * __UART_BRATE_CONST;
+
+	/* Set UART registers */
+	sil_orw_mem((uint32_t *)(base + TOFF_UART_LCR), UART_LCR_DMD);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLH), dlh);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLL), dll);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_DLF), dlf);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_LCR), 0x00);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_LCR), (UART_WordLength_8b | UART_StopBits_1 | UART_Parity_No));
+	sil_andw_mem((uint32_t *)(base + TOFF_UART_LCR), UART_LCR_DMD);
+	sil_orw_mem((uint32_t *)(base + TOFF_UART_IER), UART_IER_THRE);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_FCR),
+				(UART_RECEIVE_FIFO14 << 6 | UART_SEND_FIFO8 << 4 /*| 0x1 << 3 DMA mode?*/ | 0x1 /*FIFO enable?*/));
+	sil_andw_mem((uint32_t *)(base + TOFF_UART_MCR), (1 << 6) | 3);
+	sil_wrw_mem((uint32_t *)(base + TOFF_UART_TCR), 0x00);
 
 	fpioa_set_function(uartpin[p_siopinib->com][1], p_siopinib->rxfunc);
